diff --git a/.clang-format b/.clang-format index a8db080..56d3eef 100644 --- a/.clang-format +++ b/.clang-format @@ -1,5 +1,6 @@ AccessModifierOffset: -1 SpacesBeforeTrailingComments: 2 NamespaceIndentation: All SortIncludes: false PointerAlignment: Middle +AlwaysBreakTemplateDeclarations: true diff --git a/CMakeLists.txt b/CMakeLists.txt index 81dde43..9eaa8e1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,279 +1,292 @@ # ============================================================================= # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief Main configuration file # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= cmake_minimum_required(VERSION 3.0.0) 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) include(cpplint) string( TOLOWER "${CMAKE_BUILD_TYPE}" build_type ) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # using Clang add_compile_options(-Wno-missing-braces) if ("debug" STREQUAL "${build_type}") add_compile_options(-O0) endif() elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # using GCC add_compile_options(-Wno-non-virtual-dtor) add_compile_options(-march=native) if (("relwithdebinfo" STREQUAL "${build_type}") OR ("release" STREQUAL "${build_type}" )) add_compile_options(-march=native) endif() if ("debug" STREQUAL "${build_type}" ) add_compile_options(-O0) endif() elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") # using Intel C++ elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # using Visual Studio C++ endif() # Do not trust old gcc. the std::optional has memory bugs if(${CMAKE_COMPILER_IS_GNUCC}) if(${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 6.0.0) add_definitions(-DNO_EXPERIMENTAL) endif() endif() - add_external_package(Eigen3 VERSION 3.3.0 CONFIG) + add_external_package(pybind11 VERSION 2.2 CONFIG) find_package(PythonLibsNew ${MUSPECTRE_PYTHON_MAJOR_VERSION} MODULE REQUIRED) 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 library 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) add_executable(cp_test tests/main_test_suite tests/test_material_crystal_plasticity_finite.cc) target_link_libraries(cp_test ${Boost_LIBRARIES} muSpectre) muSpectre_add_test(cp_test TYPE BOOST cp_test --report_level=detailed) add_executable(mattb_test tests/main_test_suite tests/test_materials_toolbox.cc) target_link_libraries(mattb_test ${Boost_LIBRARIES} muSpectre) muSpectre_add_test(mattb_test TYPE BOOST mattb_test --report_level=detailed) # build header tests file( GLOB HEADER_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/header_test_*.cc") foreach(header_test ${HEADER_TEST_SRCS}) get_filename_component(header_test_name ${header_test} NAME_WE) string(SUBSTRING ${header_test_name} 12 -1 test_name) list(APPEND header_tests ${test_name}) add_executable(${test_name} tests/main_test_suite.cc ${header_test}) target_link_libraries(${test_name} ${Boost_LIBRARIES} Eigen3::Eigen) target_include_directories(${test_name} INTERFACE ${muSpectre_INCLUDES}) muSpectre_add_test(${test_name} TYPE BOOST ${test_name} --report_level=detailed) endforeach(header_test ${HEADER_TEST_SRCS}) add_custom_target(header_tests) add_dependencies(header_tests ${header_tests}) ############################################################################## # build py_comparison tests file (GLOB PY_COMP_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/py_comparison_*.cc") find_package(PythonInterp ${MUSPECTRE_PYTHON_MAJOR_VERSION} REQUIRED) foreach(py_comp_test ${PY_COMP_TEST_SRCS}) get_filename_component(py_comp_test_fname ${py_comp_test} NAME_WE) string (SUBSTRING ${py_comp_test_fname} 19 -1 py_comp_test_name) pybind11_add_module(${py_comp_test_name} ${py_comp_test}) target_include_directories(${py_comp_test_name} PUBLIC ${PYTHON_INCLUDE_DIRS}) target_link_libraries(${py_comp_test_name} PRIVATE muSpectre) configure_file( tests/${py_comp_test_fname}.py "${CMAKE_BINARY_DIR}/${py_comp_test_fname}.py" COPYONLY) muSpectre_add_test(${py_comp_test_fname} TYPE PYTHON ${py_comp_test_fname}.py) endforeach(py_comp_test ${PY_COMP_TEST_SRCS}) ############################################################################## # copy python test file( GLOB PY_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/python_*.py") foreach(pytest ${PY_TEST_SRCS}) get_filename_component(pytest_name ${pytest} NAME) configure_file( ${pytest} "${CMAKE_BINARY_DIR}/${pytest_name}" COPYONLY) endforeach(pytest ${PY_TEST_SRCS}) muSpectre_add_test(python_binding_test TYPE PYTHON python_binding_tests.py) if(${MPI_PARALLEL}) ############################################################################ # add MPI tests file( GLOB TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/mpi_test_*.cc") add_executable(mpi_main_test_suite tests/mpi_main_test_suite.cc ${TEST_SRCS}) target_link_libraries(mpi_main_test_suite ${Boost_LIBRARIES} muSpectre) muSpectre_add_test(mpi_main_test_suite1 TYPE BOOST MPI_NB_PROCS 1 mpi_main_test_suite --report_level=detailed) muSpectre_add_test(mpi_main_test_suite2 TYPE BOOST MPI_NB_PROCS 2 mpi_main_test_suite --report_level=detailed) muSpectre_add_test(python_mpi_binding_test1 TYPE PYTHON MPI_NB_PROCS 1 python_mpi_binding_tests.py) muSpectre_add_test(python_mpi_binding_test2 TYPE PYTHON MPI_NB_PROCS 2 python_mpi_binding_tests.py) endif(${MPI_PARALLEL}) endif(${MAKE_TESTS}) ################################################################################ # 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 + # or copy them file (GLOB pybins "${CMAKE_SOURCE_DIR}/bin/*.py") foreach(pybin ${pybins}) get_filename_component(binaryname ${pybin} NAME_WE) configure_file( ${pybin} "${CMAKE_BINARY_DIR}/${binaryname}.py" COPYONLY) endforeach(pybin ${pybins}) + + # additional files to copy + set (FILES_FOR_COPY + ${CMAKE_SOURCE_DIR}/bin/odd_image.npz) + + foreach(FILE_FOR_COPY ${FILES_FOR_COPY}) + + get_filename_component(binaryname ${FILE_FOR_COPY} NAME) + configure_file( + ${FILE_FOR_COPY} + "${CMAKE_BINARY_DIR}/${binaryname}" + COPYONLY) + endforeach(FILE_FOR_COPY ${FILES_FOR_COPY}) + endif (${MAKE_EXAMPLES}) ################################################################################ # 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}) cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src" "") cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/tests" "") cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/language_bindings" "") cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/bin" "--filter=-build/namespaces") diff --git a/Jenkinsfile b/Jenkinsfile index 0cafdd5..475f59f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,218 +1,218 @@ pipeline { parameters {string(defaultValue: '', description: 'api-token', name: 'API_TOKEN') string(defaultValue: '', description: 'Token for readthedocs', name: 'RTD_TOKEN') string(defaultValue: '', description: 'buildable phid', name: 'TARGET_PHID') string(defaultValue: 'docker_debian_testing', description: 'docker file to use', name: 'DOCKERFILE') string(defaultValue: '', description: 'Commit id', name: 'COMMIT_ID') } agent any environment { OMPI_MCA_plm = 'isolated' OMPI_MCA_btl = 'tcp,self' } options { disableConcurrentBuilds() } stages { stage ('wipe build') { when { anyOf{ changeset glob: "**/*.cmake" changeset glob: "**/CMakeLists.txt" } } steps { sh ' rm -rf build_*' } } stage ('configure') { parallel { stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { configure('docker_debian_testing') } } stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { configure('docker_debian_stable') } } } } stage ('build') { parallel { stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { build('docker_debian_testing') } } stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { build('docker_debian_stable') } } } } stage ('Warnings gcc') { steps { warnings(consoleParsers: [[parserName: 'GNU Make + GNU C Compiler (gcc)']]) } } stage ('test') { parallel { //////////////////////////////////////////////////// stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { run_test('docker_debian_testing', 'g++') run_test('docker_debian_testing', 'clang++') } post { always { collect_test_results('docker_debian_testing', 'g++') collect_test_results('docker_debian_testing', 'clang++') } } } //////////////////////////////////////////////////// stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { run_test('docker_debian_stable', 'g++') run_test('docker_debian_stable', 'clang++') } post { always { collect_test_results('docker_debian_stable', 'g++') collect_test_results('docker_debian_stable', 'clang++') } } } } } } post { always { createartifact() } success { send_fail_pass('pass') trigger_readthedocs() } - failure { + unsuccessful { send_fail_pass('fail') } } } def configure(container_name) { def BUILD_DIR = "build_${container_name}" for (CXX_COMPILER in ["g++", "clang++"]) { sh """ mkdir -p ${BUILD_DIR}_${CXX_COMPILER} cd ${BUILD_DIR}_${CXX_COMPILER} CXX=${CXX_COMPILER} cmake -DCMAKE_BUILD_TYPE:STRING=Release -DRUNNING_IN_CI=ON .. """ } } def build(container_name) { def BUILD_DIR = "build_${container_name}" for (CXX_COMPILER in ["g++", "clang++"]) { sh "make -C ${BUILD_DIR}_${CXX_COMPILER}" } } def run_test(container_name, cxx_compiler) { def BUILD_DIR = "build_${container_name}" sh "cd ${BUILD_DIR}_${cxx_compiler} && ctest || true" } def send_fail_pass(state) { sh """ set +x curl https://c4science.ch/api/harbormaster.sendmessage \ -d api.token=${API_TOKEN} \ -d buildTargetPHID=${TARGET_PHID} \ -d type=${state} """ } def trigger_readthedocs() { sh """ set +x curl -X POST \ -d "token=${RTD_TOKEN}" \ -d "branches=master" \ https://readthedocs.org/api/v2/webhook/muspectre/26537/ curl -X POST \ -d "token=${RTD_TOKEN}" \ https://readthedocs.org/api/v2/webhook/muspectre/26537/ """ } def collect_test_results(container_name, cxx_compiler) { def BUILD_DIR = "build_${container_name}" junit "${BUILD_DIR}_${cxx_compiler}/test_results*.xml" } def createartifact() { sh """ set +x curl https://c4science.ch/api/harbormaster.createartifact \ -d api.token=${API_TOKEN} \ -d buildTargetPHID=${TARGET_PHID} \ -d artifactKey="Jenkins URI" \ -d artifactType=uri \ -d artifactData[uri]=${BUILD_URL} \ -d artifactData[name]="View Jenkins result" \ -d artifactData[ui.external]=1 """ } diff --git a/bin/odd_image.npz b/bin/odd_image.npz new file mode 100644 index 0000000..62536ef Binary files /dev/null and b/bin/odd_image.npz differ diff --git a/bin/visualisation_example.py b/bin/visualisation_example.py new file mode 100644 index 0000000..7af088d --- /dev/null +++ b/bin/visualisation_example.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file visualisation_example.py + +@author Richard Leute + +@date 14 Jan 2019 + +@brief small example of how one can use the visualisation tools: + gradient_integration() and vtk_export() + +@section LICENSE + +Copyright © 2019 Till Junge, Richard Leute + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + + +import numpy as np +import sys +import os +sys.path.append("language_bindings/python/") +import muSpectre as µ +import muSpectre.gradient_integration as gi +import muSpectre.vtk_export as vt_ex + + +### Input parameters ### +#----------------------# +#general +resolutions = [71, 71, 3] +lengths = [1.0, 1.0, 0.2] +Nx, Ny, Nz = resolutions +formulation = µ.Formulation.finite_strain +Young = [10, 20] #Youngs modulus for each phase +Poisson = [0.3, 0.4] #Poissons ratio for each phase + +#solver +newton_tol = 1e-6 #tolerance for newton algo +cg_tol = 1e-6 #tolerance for cg algo +equil_tol = 1e-6 #tolerance for equilibrium +maxiter = 100 +verbose = 0 + +# sinusoidal bump +d = 10 #thickness of the phase with higher elasticity in pixles +l = Nx//3 #length of bump +h = Ny//4 #height of bump + +low_y = (Ny-d)//2 #lower y-boundary of phase +high_y = low_y+d #upper y-boundary of phase + +left_x = (Nx-l)//2 #boundaries in x direction left +right_x = left_x + l #boundaries in x direction right +x = np.arange(l) +p_y = h*np.sin(np.pi/(l-1)*x) #bump function + +xy_bump = np.ones((l,h,Nz)) #grid representing bumpx +for i, threshold in enumerate(np.round(p_y)): + xy_bump[i,int(threshold):,:] = 0 + +phase = np.zeros(resolutions, dtype=int) #0 for surrounding matrix +phase[:, low_y:high_y, :] = 1 +phase[left_x:right_x, high_y:high_y+h, :] = xy_bump + + +### Run muSpectre ### +#-------------------# +cell = µ.Cell(resolutions, + lengths, + formulation) +mat = µ.material.MaterialLinearElastic4_3d.make(cell, "material") + +for i, pixel in enumerate(cell): + #add Young and Poisson depending on the material index + m_i = phase.flatten()[i] #m_i = material index / phase index + mat.add_pixel(pixel, Young[m_i], Poisson[m_i]) + +cell.initialise() #initialization of fft to make faster fft +DelF = np.array([[0 , 0.7, 0], + [0 , 0 , 0], + [0 , 0 , 0]]) + +solver_newton = µ.solvers.SolverCG(cell, cg_tol, maxiter, verbose) +result = µ.solvers.newton_cg(cell, DelF, solver_newton, + newton_tol, equil_tol, verbose) + +# print solver results +print('\n\nstatus messages of OptimizeResults:') +print('-----------------------------------') +print('success: ', result.success) +print('status: ', result.status) +print('message: ', result.message) +print('# iterations: ', result.nb_it) +print('# cell evaluations: ', result.nb_fev) +print('formulation: ', result.formulation) + + +### Visualisation ### +#-------------------# +#integration of the deformation gradient field +placement_n, x = gi.compute_placement(result, lengths, resolutions, order = 0) + +### some fields which can be added to the visualisation +#2-tensor field containing the first Piola Kirchhoff stress +PK1 = gi.reshape_gradient(result.stress, resolutions) +#scalar field containing the distance to the origin O +distance_O = np.linalg.norm(placement_n, axis=-1) + +#random fields +center_shape = tuple(np.array(x.shape[:-1])-1)#shape of the center point grid +dim = len(resolutions) +scalar_c = np.random.random(center_shape) +vector_c = np.random.random(center_shape + (dim,)) +tensor2_c = np.random.random(center_shape + (dim,dim)) +scalar_n = np.random.random(x.shape[:-1]) +vector_n = np.random.random(x.shape[:-1] + (dim,)) +tensor2_n = np.random.random(x.shape[:-1] + (dim,dim)) + +#write dictionaries with cell data and point data +c_data = {"scalar field" : scalar_c, + "vector field" : vector_c, + "2-tensor field" : tensor2_c, + "PK1 stress" : PK1, + "phase" : phase} +p_data = {"scalar field" : scalar_n, + "vector field" : vector_n, + "2-tensor field" : tensor2_n, + "distance_O" : distance_O} + +vt_ex.vtk_export(fpath = "visualisation_example", + x_n = x, + placement = placement_n, + point_data = p_data, + cell_data = c_data) + +print("The file 'visualisation_example.vtr' was successfully written!\n" + "You can open it for example with paraview or some other software:\n" + "paraview visualisation_example.vtr") diff --git a/cmake/cpplint.cmake b/cmake/cpplint.cmake index d15cf4e..1ad9dae 100644 --- a/cmake/cpplint.cmake +++ b/cmake/cpplint.cmake @@ -1,105 +1,105 @@ # # CMake module to C++ static analysis against # Google C++ Style Guide (https://google.github.io/styleguide/cppguide.html) # # For more detials please follow links: # # - https://github.com/google/styleguide # - https://pypi.python.org/pypi/cpplint # - https://github.com/theandrewdavis/cpplint # # Copyright (c) 2016 Piotr L. Figlarek # Copyright on modifications © 2018 Till Junge # # Usage # ----- # Include this module via CMake include(...) command and then add each source directory # via introduced by this module cpplint_add_subdirectory(...) function. Added directory # will be recursivelly scanned and all available files will be checked. # # Example # ------- # # include CMake module # include(cmake/cpplint.cmake) # # # add all source code directories # cpplint_add_subdirectory(core) # cpplint_add_subdirectory(modules/c-bind) # # License (MIT) # ------------- # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # select files extensions to check # target to run cpplint.py for all configured sources set(CPPLINT_TARGET lint CACHE STRING "Name of C++ style checker target") # project root directory set(CPPLINT_PROJECT_ROOT ${PROJECT_SOURCE_DIR} CACHE STRING "Project ROOT directory") # find cpplint.py script -find_file(CPPLINT name cpplint HINTS $ENV{HOME}.local/bin) +find_file(CPPLINT name "cpplint.py" PATHS ${PROJECT_SOURCE_DIR}/external) if(CPPLINT) message(STATUS "cpplint parser: ${CPPLINT}") else() message(FATAL_ERROR "cpplint script: NOT FOUND! " "Please install cpplint as described on https://pypi.python.org/pypi/cpplint. " "In most cases command 'sudo pip install cpplint' should be sufficent.") endif() # common target to concatenate all cpplint.py targets add_custom_target(${CPPLINT_TARGET}) # use cpplint.py to check source code files inside DIR directory function(cpplint_add_subdirectory DIR FLAGS) # create relative path to the directory set(ABSOLUTE_DIR ${DIR}) set(EXTENSIONS cc,hh) set(FILES_TO_CHECK ${FILES_TO_CHECK} ${ABSOLUTE_DIR}/*.cc ${ABSOLUTE_DIR}/*.hh) # find all source files inside project file(GLOB_RECURSE LIST_OF_FILES ${FILES_TO_CHECK}) # create valid target name for this check get_filename_component(DNAME ${DIR} NAME) string(REGEX REPLACE "/" "." TEST_NAME ${DNAME}) set(TARGET_NAME ${CPPLINT_TARGET}.${TEST_NAME}) # perform cpplint check add_custom_target(${TARGET_NAME} - COMMAND ${CPPLINT} "--extensions=${EXTENSIONS}" - "--root=${CPPLINT_PROJECT_ROOT}" - "${FLAGS}" - ${LIST_OF_FILES} - DEPENDS ${LIST_OF_FILES} - COMMENT "cpplint: Checking source code style" - ) + COMMAND ${CPPLINT} "--extensions=${EXTENSIONS}" + "--root=${CPPLINT_PROJECT_ROOT}" + "${FLAGS}" + ${LIST_OF_FILES} + DEPENDS ${LIST_OF_FILES} + COMMENT "cpplint: Checking source code style" + ) # run this target when root cpplint.py test is triggered add_dependencies(${CPPLINT_TARGET} ${TARGET_NAME}) # add this test to CTest add_test(${TARGET_NAME} ${CMAKE_MAKE_PROGRAM} ${TARGET_NAME}) endfunction() diff --git a/doc/dev-docs/source/ConstitutiveLaws.rst b/doc/dev-docs/source/ConstitutiveLaws.rst new file mode 100644 index 0000000..9b6bc6a --- /dev/null +++ b/doc/dev-docs/source/ConstitutiveLaws.rst @@ -0,0 +1,128 @@ + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + +.. _constitutive_laws: + + +Constitutive Laws +~~~~~~~~~~~~~~~~~ + +.. toctree:: + :maxdepth: 2 + + MaterialLinearElasticGeneric + + +Testing Constitutive Laws +~~~~~~~~~~~~~~~~~~~~~~~~~ + +When writing new constitutive laws, the ability to evaluate the stress-strain +behaviour and the tangent moduli is convenient, but *µ*\Spectre's material model +makes it cumbersome to isolate and execute the :cpp:func:`evaluate_stress` and +:cpp:func:`evaluate_stress_tangent` methods than any daughter class of +:cpp:class:`MaterialMuSpectre` must implement +(e.g., :cpp:func:`evaluate_stress() +`). As a helper object, +*µ*\Spectre offers the class +:cpp:class:`MaterialEvaluator` to facilitate +precisely this: + +A :cpp:class:`MaterialEvaluator` object can be +constructed with a shared pointer to a +:cpp:class:`MaterialBase` and exposes functions to +evaluate just the stress, both the stress and tangent moduli, or a numerical +approximation to the tangent moduli. For materials with internal history +variables, :cpp:class:`MaterialEvaluator` also +exposes the +:cpp:func:`MaterialBase::save_history_variables()` +method. As a convenience function, all daughter classes of +:cpp:class:`MaterialMuSpectre` have the static +factory function :cpp:func:`make_evaluator() +` to create a material and its +evaluator at once. See the :ref:`reference` for the full class description. + +Python Usage Example +```````````````````` + +.. code-block:: python + + import numpy as np + from muSpectre import material + from muSpectre import Formulation + + # MaterialLinearElastic1 is standard linear elasticity while + # MaterialLinearElastic2 has a per pixel eigenstrain which needs to be set + LinMat1, LinMat2 = (material.MaterialLinearElastic1_2d, + material.MaterialLinearElastic2_2d) + + young, poisson = 210e9, .33 + + # the factory returns a material and it's corresponding evaluator + material1, evaluator1 = LinMat1.make_evaluator(young, poisson) + + # the material is empty (i.e., does not have any pixel/voxel), so a pixel + # needs to be added. The coordinates are irrelevant, there just needs to + # be one pixel. + material1.add_pixel([0,0]) + + # the stress and tangent can be evaluated for finite strain + F = np.array([[1., .01],[0, 1.0]]) + P, K = evaluator1.evaluate_stress_tangent(F, Formulation.finite_strain) + # or small strain + eps = .5 * ((F-np.eye(2)) + (F-np.eye(2)).T) + sigma, C = evaluator1.evaluate_stress_tangent(eps, Formulation.small_strain) + + # and the tangent can be checked against a numerical approximation + Delta_x = 1e-6 + num_C = evaluator1.estimate_tangent(eps, Formulation.small_strain, Delta_x) + + + # Materials with per-pixel data behave similarly: the factory returns a + # material and it's corresponding evaluator like before + material2, evaluator2 = LinMat2.make_evaluator(young, poisson) + + # when adding the pixel, we now need to specify also the per-pixel data: + eigenstrain = np.array([[.01, .002], [.002, 0.]]) + material2.add_pixel([0,0], eigenstrain) + + + +C++ Usage Example +````````````````` + +.. code-block:: c++ + + #include"materials/material_linear_elastic2.hh" + #include "materials/material_evaluator.hh" + #include "common/T4_map_proxy.hh" + + #include "Eigen/Dense" + + using Mat_t = MaterialLinearElastic2; + + constexpr Real Young{210e9}; + constexpr Real Poisson{.33}; + + auto mat_eval{Mat_t::make_evaluator(Young, Poisson)}; + auto & mat{*std::get<0>(mat_eval)}; + auto & evaluator{std::get<1>(mat_eval)}; + + + using T2_t = Eigen::Matrix; + using T4_t = T4Mat; + const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + + T2_t::Identity()}; + + T2_t eigen_strain{[](auto x) { + return 1e-4 * (x + x.transpose()); + }(T2_t::Random() - T2_t::Ones() * .5)}; + + mat.add_pixel({}, eigen_strain); + + T2_t P{}; + T4_t K{}; + + std::tie(P, K) = + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); diff --git a/doc/dev-docs/source/Doxyfile b/doc/dev-docs/source/Doxyfile index 3b8c664..cd8fe05 100644 --- a/doc/dev-docs/source/Doxyfile +++ b/doc/dev-docs/source/Doxyfile @@ -1,28 +1,29 @@ PROJECT_NAME = muSpectre ## this is for read the docs, which builds in-place INPUT = ../../../src ## this overwrites the INPUT path for local builds @INCLUDE = input_def RECURSIVE = YES EXTRACT_ALL = YES SOURCE_BROWSER = YES GENERATE_HTML = YES GENERATE_LATEX = NO GENERATE_XML = YES ## this is for read the docs, which builds in-place XML_OUTPUT = doxygenxml ## this overwrites the XML_OUTPUT path for local builds @INCLUDE = xml_output_def XML_PROGRAMLISTING = YES ALIASES = "rst=\verbatim embed:rst" ALIASES += "endrst=\endverbatim" QUIET = YES WARNINGS = YES WARN_IF_UNDOCUMENTED = YES +SHOW_NAMESPACES = NO EXCLUDE_PATTERNS = */CMakeLists.txt \ No newline at end of file diff --git a/doc/dev-docs/source/GettingStarted.rst b/doc/dev-docs/source/GettingStarted.rst index 8e3007e..fb2eaa8 100644 --- a/doc/dev-docs/source/GettingStarted.rst +++ b/doc/dev-docs/source/GettingStarted.rst @@ -1,102 +1,136 @@ Getting Started ~~~~~~~~~~~~~~~ Obtaining *µ*\Spectre ********************* *µ*\Spectre is hosted on a git repository on `c4science`_. To clone it, run .. code-block:: sh $ git clone https://c4science.ch/source/muSpectre.git or if you prefer identifying yourself using a public ssh-key, run .. code-block:: bash $ git clone ssh://git@c4science.ch/source/muSpectre.git -The latter option requires you to have a user account on c4science (`create `_). +The latter option requires you to have a user account on c4science (`create +`_). .. _c4science: https://c4science.ch Building *µ*\Spectre ******************** -You can compile *µ*\Spectre using `CMake `_ (3.1.0 or higher). The current (and possibly incomplete list of) dependencies are +You can compile *µ*\Spectre using `CMake `_ (3.1.0 or +higher). The current (and possibly incomplete list of) dependencies are - `CMake `_ (3.1.0 or higher) - `Boost unit test framework `_ - `FFTW `_ - `git `_ - `Python3 `_ including the header files. - `numpy `_ and `scipy `_. Recommended: -- `Sphinx `_ and `Breathe `_ (necessary if you want to build the documentation (turned off by default) -- `Eigen `_ (3.3.0 or higher). If you do not install this, it will be downloaded automatically at configuration time, so this is not strictly necessary. The download can be slow, though, so we recommend installing it on your system. +- `Sphinx `_ and `Breathe + `_ (necessary if you want to build the + documentation (turned off by default) +- `Eigen `_ (3.3.0 or higher). If you do not + install this, it will be downloaded automatically at configuration time, so + this is not strictly necessary. The download can be slow, though, so we + recommend installing it on your system. - The CMake curses graphical user interface (``ccmake``). -*µ*\Spectre requires a relatively modern compiler as it makes heavy use of C++14 features. It has successfully been compiled and tested using the following compilers under Linux +*µ*\Spectre requires a relatively modern compiler as it makes heavy use of C++14 + features. It has successfully been compiled and tested using the following + compilers under Linux - gcc-7.2 - gcc-6.4 - gcc-5.4 - clang-6.0 - clang-5.0 - clang-4.0 and using clang-4.0 under MacOS. -It does *not* compile on Intel's most recent compiler, as it is still lacking some C++14 support. Work-arounds are planned, but will have to wait for someone to pick up the `task `_. +It does *not* compile on Intel's most recent compiler, as it is still lacking +some C++14 support. Work-arounds are planned, but will have to wait for someone +to pick up the `task `_. -To compile, create a build folder and configure the CMake project. If you do this in the folder you cloned in the previous step, it can look for instance like this: +To compile, create a build folder and configure the CMake project. If you do +this in the folder you cloned in the previous step, it can look for instance +like this: .. code-block:: sh $ mkdir build-release $ cd build-release $ ccmake .. -Then, set the build type to ``Release`` to produce optimised code. *µ*\Spectre makes heavy use of expression templates, so optimisation is paramount. (As an example, the performance difference between code compiled in ``Debug`` and ``Release`` is about a factor 40 in simple linear elasticity.) +Then, set the build type to ``Release`` to produce optimised code. *µ*\Spectre +makes heavy use of expression templates, so optimisation is paramount. (As an +example, the performance difference between code compiled in ``Debug`` and +``Release`` is about a factor 40 in simple linear elasticity.) Finally, compile the library and the tests by running .. code-block:: sh $ make -j .. warning:: - When using the ``-j`` option to compile, be aware that compiling *µ*\Spectre uses quite a bit of RAM. If your machine start swapping at compile time, reduce the number of parallel compilations + When using the ``-j`` option to compile, be aware that compiling *µ*\Spectre + uses quite a bit of RAM. If your machine start swapping at compile time, + reduce the number of parallel compilations Running *µ*\Spectre ******************* -The easiest and intended way of using *µ*\Spectre is through its Python bindings. The following simple example computes the response of a two-dimensional stretched periodic RVE cell. The cell consist of a soft matrix with a circular hard inclusion. +The easiest and intended way of using *µ*\Spectre is through its Python +bindings. The following simple example computes the response of a +two-dimensional stretched periodic RVE cell. The cell consist of a soft matrix +with a circular hard inclusion. .. literalinclude:: ../../../bin/tutorial_example.py :language: python -More examples both both python and c++ executables can be found in the ``/bin`` folder. +More examples both python and c++ executables can be found in the ``/bin`` +folder. Getting help ************ -*µ*\Spectre is in a very early stage of development and the documentation is currently spotty. Also, there is no FAQ page yet. If you run into trouble, please contact us on the `µSpectre chat room `_ and someone will answer as soon as possible. You can also check the API :ref:`reference`. +*µ*\Spectre is in a very early stage of development and the documentation is + currently spotty. Also, there is no FAQ page yet. If you run into trouble, + please contact us on the `µSpectre chat room `_ and + someone will answer as soon as possible. You can also check the API + :ref:`reference`. Reporting Bugs ************** -If you think you found a bug, you are probably right. Please report it! The preferred way is for you to create a task on `µSpectre's workboard `_ and assign it to user ``junge``. Include steps to reproduce the bug if possible. Someone will answer as soon as possible. +If you think you found a bug, you are probably right. Please report it! The +preferred way is for you to create a task on `µSpectre's workboard +`_ and assign it to user +``junge``. Include steps to reproduce the bug if possible. Someone will answer +as soon as possible. Contribute ********** -We welcome contributions both for new features and bug fixes. New features must be documented and have unit tests. Please submit contributions for review as `Arcanist revisions `_. More detailed guidelines for submissions will follow soonᵀᴹ. +We welcome contributions both for new features and bug fixes. New features must +be documented and have unit tests. Please submit contributions for review as +`Arcanist revisions +`_. More +detailed guidelines for submissions will follow soonᵀᴹ. diff --git a/doc/dev-docs/source/MaterialLinearElasticGeneric.rst b/doc/dev-docs/source/MaterialLinearElasticGeneric.rst new file mode 100644 index 0000000..ef62739 --- /dev/null +++ b/doc/dev-docs/source/MaterialLinearElasticGeneric.rst @@ -0,0 +1,51 @@ +Generic Linear Elastic Material +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The generic linear elastic material is implemented in the classes +:cpp:class:`MaterialLinearElasticGeneric1` and +:cpp:class:`MaterialLinearElasticGeneric2`, and is defined solely by +the elastic stiffness tensor :math:`\mathbb{C}`, which has to be specified in +`Voigt notation `_. In the case of +:cpp:class:`MaterialLinearElasticGeneric2`, additionally, a per-pixel +eigenstrain :math:`\bar{\boldsymbol{\varepsilon}}` can be supplied. The +constitutive relation between the Cauchy stress :math:`\boldsymbol{\sigma}` and +the small strain tensor :math:`\boldsymbol{\varepsilon}` is given by + +.. math:: + :nowrap: + + \begin{align} + \boldsymbol{\sigma} &= \mathbb{C}:\boldsymbol{\varepsilon}\\ + \sigma_{ij} &= C_{ijkl}\,\varepsilon_{kl}, \quad\mbox{for the simple version, and}\\ + \boldsymbol{\sigma} &= \mathbb{C}:\left(\boldsymbol{\varepsilon}-\bar{\boldsymbol{\varepsilon}}\right)\\ + \sigma_{ij} &= C_{ijkl}\,\left(\varepsilon_{kl} - \bar\varepsilon_{kl}\right) \quad\mbox{ for the version with eigenstrain} + \end{align} + +This implementation is convenient, as it covers all possible linear elastic +behaviours, but it is by far not as efficient as +:cpp:class:`MaterialLinearElastic1` for isotropic linear elasticity. + +This law can be used in both small strain and finite strain calculations. + +The following snippet shows how to use this law in python to implement isotropic +linear elasticity: + +.. code-block:: python + + C = np.array([[2 * mu + lam, lam, lam, 0, 0, 0], + [ lam, 2 * mu + lam, lam, 0, 0, 0], + [ lam, lam, 2 * mu + lam, 0, 0, 0], + [ 0, 0, 0, mu, 0, 0], + [ 0, 0, 0, 0, mu, 0], + [ 0, 0, 0, 0, 0, mu]]) + + eigenstrain = np.array([[ 0, .01], + [.01, 0]]) + + mat1 = muSpectre.material.MaterialLinearElasticGeneric1_3d.make( + cell, "material", C) + mat1.add_pixel(pixel) + mat2 = muSpectre.material.MaterialLinearElasticGeneric2_3d.make( + cell, "material", C) + mat2.add_pixel(pixel, eigenstrain) + diff --git a/doc/dev-docs/source/NewMaterial.rst b/doc/dev-docs/source/NewMaterial.rst index c093398..fc75006 100644 --- a/doc/dev-docs/source/NewMaterial.rst +++ b/doc/dev-docs/source/NewMaterial.rst @@ -1,191 +1,250 @@ Writing a New Constitutive Law ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The abstraction for a constitutive law in *µ*\Spectre** is the ``Material``, and new such materials must inherit from the class :cpp:class:`muSpectre::MaterialBase`. Most often, however, it will be most convenient to inherit from the derived class :cpp:class:`muSpectre::MaterialMuSpectre`, as it implements a lot of the machinery that is commonly used by constitutive laws. This section describes how to implement a new constitutive law with internal variables (sometimes also called state variables). The example material implemented here is :cpp:class:`MaterialTutorial`, an objective linear elastic law with a distribution of eigenstrains as internal variables. The constitutive law is defined by the relationship between material (or second Piola-Kirchhoff) stress :math:`\mathbf{S}` and Green-Lagrange strain :math:`\mathbf{E}` +The abstraction for a constitutive law in *µ*\Spectre** is the ``Material``, and +new such materials must inherit from the class +:cpp:class:`muSpectre::MaterialBase`. Most often, however, it will be most +convenient to inherit from the derived class +:cpp:class:`muSpectre::MaterialMuSpectre`, as it implements a lot of the +machinery that is commonly used by constitutive laws. This section describes how +to implement a new constitutive law with internal variables (sometimes also +called state variables). The example material implemented here is +:cpp:class:`MaterialTutorial`, an objective linear elastic law with a +distribution of eigenstrains as internal variables. The constitutive law is +defined by the relationship between material (or second Piola-Kirchhoff) stress +:math:`\mathbf{S}` and Green-Lagrange strain :math:`\mathbf{E}` .. math:: :nowrap: \begin{align} \mathbf{S} &= \mathbb C:\left(\mathbf{E}-\mathbf{e}\right), \\ S_{ij} &= C_{ijkl}\left(E_{kl}-e_{kl}\right), \\ \end{align} -where :math:`\mathbb C` is the elastic stiffness tensor and :math:`\mathbf e` is the local eigenstrain. Note that the implementation sketched out here is the most convenient to quickly get started with using *µ*\Spectre**, but not the most efficient one. For a most efficient implementation, refer to the implementation of :cpp:class:`muSpectre::MaterialLinearElastic2`. +where :math:`\mathbb C` is the elastic stiffness tensor and :math:`\mathbf e` is +the local eigenstrain. Note that the implementation sketched out here is the +most convenient to quickly get started with using *µ*\Spectre**, but not the +most efficient one. For a most efficient implementation, refer to the +implementation of :cpp:class:`muSpectre::MaterialLinearElastic2`. The :cpp:class:`muSpectre::MaterialMuSpectre` class *************************************************** -The class :cpp:class:`muSpectre::MaterialMuSpectre` is defined in ``material_muSpectre_base.hh`` and takes three template parameters; - -#. ``class Material`` is a `CRTP `_ and names the material inheriting from it. The reason for this construction is that we want to avoid virtual method calls from :cpp:class:`muSpectre::MaterialMuSpectre` to its derived classes. Rather, we want :cpp:class:`muSpectre::MaterialMuSpectre` to be able to call methods of the inheriting class directly without runtime overhead. -#. ``Dim_t DimS`` defines the number of spatial dimensions of the problem, i.e., whether we are dealing with a two- or three-dimensional grid of pixels/voxels. -#. ``Dim_t DimM`` defines the number of dimensions of our material description. This value will typically be the same as ``DimS``, but in cases like generalised plane strain, we can for instance have a three three-dimensional material response in a two-dimensional pixel grid. +The class :cpp:class:`muSpectre::MaterialMuSpectre` is defined in +``material_muSpectre_base.hh`` and takes three template parameters; + +#. ``class Material`` is a `CRTP + `_ and + names the material inheriting from it. The reason for this construction is + that we want to avoid virtual method calls from + :cpp:class:`muSpectre::MaterialMuSpectre` to its derived classes. Rather, we + want :cpp:class:`muSpectre::MaterialMuSpectre` to be able to call methods of + the inheriting class directly without runtime overhead. +#. ``Dim_t DimS`` defines the number of spatial dimensions of the problem, i.e., + whether we are dealing with a two- or three-dimensional grid of + pixels/voxels. +#. ``Dim_t DimM`` defines the number of dimensions of our material + description. This value will typically be the same as ``DimS``, but in cases + like generalised plane strain, we can for instance have a three + three-dimensional material response in a two-dimensional pixel grid. The main job of :cpp:class:`muSpectre::MaterialMuSpectre` is to -#. loop over all pixels to which this material has been assigned, transform the global gradient :math:`\mathbf{F}` (or small strain tensor :math:`\boldsymbol\varepsilon`) into the new material's required strain measure (e.g., the Green-Lagrange strain tensor :math:`\mathbf{E}`), -#. for each pixel evaluate the constitutive law by calling its ``evaluate_stress`` (computes the stress response) or ``evaluate_stress_tangent`` (computes both stress and consistent tangent) method with the local strain and internal variables, and finally -#. transform the stress (and possibly tangent) response from the material's stress measure into first Piola-Kirchhoff stress :math:`\mathbf{P}` (or Cauchy stress :math:`\boldsymbol\sigma` in small strain). - -In order to use these facilities, the new material needs to inherit from :cpp:class:`muSpectre::MaterialMuSpectre` (where we calculation of the response) and specialise the type :cpp:class:`muSpectre::MaterialMuSpectre_traits` (where we tell :cpp:class:`muSpectre::MaterialMuSpectre` how to use the new material). These two steps are described here for our example material. +#. loop over all pixels to which this material has been assigned, transform the + global gradient :math:`\mathbf{F}` (or small strain tensor + :math:`\boldsymbol\varepsilon`) into the new material's required strain + measure (e.g., the Green-Lagrange strain tensor :math:`\mathbf{E}`), +#. for each pixel evaluate the constitutive law by calling its + ``evaluate_stress`` (computes the stress response) or + ``evaluate_stress_tangent`` (computes both stress and consistent tangent) + method with the local strain and internal variables, and finally +#. transform the stress (and possibly tangent) response from the material's + stress measure into first Piola-Kirchhoff stress :math:`\mathbf{P}` (or + Cauchy stress :math:`\boldsymbol\sigma` in small strain). + +In order to use these facilities, the new material needs to inherit from +:cpp:class:`muSpectre::MaterialMuSpectre` (where we calculation of the response) +and specialise the type :cpp:class:`muSpectre::MaterialMuSpectre_traits` (where +we tell :cpp:class:`muSpectre::MaterialMuSpectre` how to use the new +material). These two steps are described here for our example material. Specialising the :cpp:class:`muSpectre::MaterialMuSpectre_traits` structure -*************************************************************************** -This structure is templated by the new material (in this case :cpp:class:`MaterialTutorial`) and needs to specify - -#. the types used to communicate per-pixel strains, stresses and stiffness tensors to the material (i.e., whether you want to get maps to `Eigen` matrices or raw pointers, or ...). Here we will use the convenient :cpp:type:`muSpectre::MatrixFieldMap` for strains and stresses, and :cpp:type:`muSpectre::T4MatrixFieldMap` for the stiffness. Look through the classes deriving from :cpp:type:`muSpectre::FieldMap` for all available options. -#. the strain measure that is expected (e.g., gradient, Green-Lagrange strain, left Cauchy-Green strain, etc.). Here we will use Green-Lagrange strain. The options are defined by the enum :cpp:enum:`muSpectre::StrainMeasure`. -#. the stress measure that is computed by the law (e.g., Cauchy, first Piola-Kirchhoff, etc,). Here, it will be first Piola-Kirchhoff stress. The available options are defined by the enum :cpp:enum:`muSpectre::StressMeasure`. +*************************************************************************** This +structure is templated by the new material (in this case +:cpp:class:`MaterialTutorial`) and needs to specify + +#. the types used to communicate per-pixel strains, stresses and stiffness + tensors to the material (i.e., whether you want to get maps to `Eigen` + matrices or raw pointers, or ...). Here we will use the convenient + :cpp:type:`muSpectre::MatrixFieldMap` for strains and stresses, and + :cpp:type:`muSpectre::T4MatrixFieldMap` for the stiffness. Look through the + classes deriving from :cpp:type:`muSpectre::FieldMap` for all available + options. +#. the strain measure that is expected (e.g., gradient, Green-Lagrange strain, + left Cauchy-Green strain, etc.). Here we will use Green-Lagrange strain. The + options are defined by the enum :cpp:enum:`muSpectre::StrainMeasure`. +#. the stress measure that is computed by the law (e.g., Cauchy, first + Piola-Kirchhoff, etc,). Here, it will be first Piola-Kirchhoff stress. The + available options are defined by the enum + :cpp:enum:`muSpectre::StressMeasure`. Our traits look like this (assuming we are in the namespace ``muSpectre``:: template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename GlobalFieldCollection; //! 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals using LFieldColl_t = LocalFieldCollection; //! local strain type using LStrainMap_t = MatrixFieldMap; //! elasticity with eigenstrain using InternalVariables = std::tuple; }; Implementing the new material ***************************** -The new law needs to implement the methods ``add_pixel``, ``get_internals``, ``evaluate_stress``, and ``evaluate_stress_tangent``. Below is a commented example header:: +The new law needs to implement the methods ``add_pixel``, ``get_internals``, +``evaluate_stress``, and ``evaluate_stress_tangent``. Below is a commented +example header:: template class MaterialTutorial: public MaterialMuSpectre, DimS, DimM> { public: //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Construct by name, Young's modulus and Poisson's ratio MaterialTutorial(std::string name, Real young, Real poisson); /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(s_t && E, eigen_s_t && E_eig); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, eigen_s_t && E_eig); /** * return the internals tuple (needed by `muSpectre::MaterialMuSpectre`) */ InternalVariables & get_internals() { return this->internal_variables;}; /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel, const Eigen::Matrix & E_eig); protected: //! stiffness tensor T4Mat C; //! storage for eigenstrain using Field_t = TensorField, Real, secondOrder, DimM>; Field_t & eigen_field; //!< field of eigenstrains //! tuple for iterable eigen_field InternalVariables internal_variables; private: }; A possible implementation for the constructor would be:: template MaterialTutorial::MaterialTutorial(std::string name, Real young, Real poisson) :MaterialMuSpectre(name) { // Lamé parameters Real lambda{young*poisson/((1+poisson)*(1-2*poisson))}; Real mu{young/(2*(1+poisson))}; // Kronecker delta Eigen::Matrix del{Eigen::Matrix::Identity()}; // fill the stiffness tensor this->C.setZero(); for (Dim_t i = 0; i < DimM; ++i) { for (Dim_t j = 0; j < DimM; ++j) { for (Dim_t k = 0; k < DimM; ++k) { for (Dim_t l = 0; l < DimM; ++l) { get(this->C, i, j, k, l) += (lambda * del(i,j)*del(k,l) + mu * (del(i,k)*del(j,l) + del(i,l)*del(j,k))); } } } } } -as an exercise, you could check how :cpp:class:`muSpectre::MaterialLinearElastic1` uses *µ*\Spectre**'s materials toolbox (in namespace ``MatTB``) to compute :math:`\mathbb C` in a much more convenient fashion. The evaluation of the stress could be (here, we make use of the ``Matrices`` namespace that defines common tensor algebra operations):: +as an exercise, you could check how +:cpp:class:`muSpectre::MaterialLinearElastic1` uses *µ*\Spectre**'s materials +toolbox (in namespace ``MatTB``) to compute :math:`\mathbb C` in a much more +convenient fashion. The evaluation of the stress could be (here, we make use of +the ``Matrices`` namespace that defines common tensor algebra operations):: template template decltype(auto) MaterialTutorial:: evaluate_stress(s_t && E, eigen_s_t && E_eig) { return Matrices::tens_mult(this->C, E-E_eig); } The remaining two methods are straight-forward:: template template decltype(auto) MaterialTutorial:: evaluate_stress_tangent(s_t && E, eigen_s_t && E_eig) { return return std::make_tuple (evaluate_stress(E, E_eig), this->C); } template InternalVariables & MaterialTutorial::get_internals() { return this->internal_variables; } -Note that the methods ``evaluate_stress`` and ``evaluate_stress_tangent`` need to be in the header, as both their input parameter types and output type depend on the compile-time context. +Note that the methods ``evaluate_stress`` and ``evaluate_stress_tangent`` need +to be in the header, as both their input parameter types and output type depend +on the compile-time context. diff --git a/doc/dev-docs/source/conf.py b/doc/dev-docs/source/conf.py index 12bbc54..e4ece92 100644 --- a/doc/dev-docs/source/conf.py +++ b/doc/dev-docs/source/conf.py @@ -1,224 +1,226 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # µSpectre documentation build configuration file, created by # sphinx-quickstart on Thu Feb 1 12:01:24 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import subprocess # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'breathe'] read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if os.environ.get('READTHEDOCS', None) is not None: print("${READTHEDOCS} = " + os.environ.get('READTHEDOCS', None)) if read_the_docs_build: muspectre_path = "." else: muspectre_path = "@CMAKE_CURRENT_BINARY_DIR@" os.makedirs("@CMAKE_CURRENT_BINARY_DIR@/_static", exist_ok=True) print("muspectre_path = '{}'".format(muspectre_path)) subprocess.call('ls; pwd', shell=True) subprocess.call("cd {} && doxygen".format(muspectre_path), shell=True) breathe_projects = {"µSpectre": os.path.join(muspectre_path, "doxygenxml")} breathe_default_project = "µSpectre" # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'µSpectre' copyright = '2018, Till Junge' author = 'Till Junge' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = 'v0.1' # The full version, including alpha/beta/rc tags. release = 'v0.1 α' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["CmakeLists.txt"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # on_rtd = os.environ.get('READTHEDOCS') == 'True' if on_rtd: html_theme = 'default' else: html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'Spectredoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # - # 'preamble': '', + 'preamble': r''' +\usepackage{amsmath} +''', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Spectre.tex', 'µSpectre Documentation', 'Till Junge', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'spectre', 'µSpectre Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Spectre', 'µSpectre Documentation', author, 'Spectre', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} primary_domain = 'cpp' highlight_language = 'cpp' diff --git a/doc/dev-docs/source/index.rst b/doc/dev-docs/source/index.rst index b1dd156..aea28cf 100644 --- a/doc/dev-docs/source/index.rst +++ b/doc/dev-docs/source/index.rst @@ -1,41 +1,42 @@ .. image:: ../logo_flat.png *µ*\Spectre, FFT-based Homogenisation without Linear Reference Medium ===================================================================== .. toctree:: :maxdepth: 2 :caption: Contents: Summary Tutorials CodingConvention + ConstitutiveLaws Reference License *µ*\Spectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. *µ*\Spectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` diff --git a/external/cpplint.py b/external/cpplint.py new file mode 100755 index 0000000..fb550b5 --- /dev/null +++ b/external/cpplint.py @@ -0,0 +1,6470 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2009 Google Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Modified by Till Junge to handle boolean operators "and" +# and "or" correctly + +"""Does google-lint on c++ files. + +The goal of this script is to identify places in the code that *may* +be in non-compliance with google style. It does not attempt to fix +up these problems -- the point is to educate. It does also not +attempt to find all problems, or to ensure that everything it does +find is legitimately a problem. + +In particular, we can get very confused by /* and // inside strings! +We do a small hack, which is to ignore //'s with "'s after them on the +same line, but it is far from perfect (in either direction). +""" + +import codecs +import copy +import getopt +import glob +import itertools +import math # for log +import os +import re +import sre_compile +import string +import sys +import unicodedata +import xml.etree.ElementTree + +# if empty, use defaults +_header_extensions = set([]) + +# if empty, use defaults +_valid_extensions = set([]) + + +# Files with any of these extensions are considered to be +# header files (and will undergo different style checks). +# This set can be extended by using the --headers +# option (also supported in CPPLINT.cfg) +def GetHeaderExtensions(): + if not _header_extensions: + return set(['h', 'hpp', 'hxx', 'h++', 'cuh']) + return _header_extensions + +# The allowed extensions for file names +# This is set by --extensions flag +def GetAllExtensions(): + if not _valid_extensions: + return GetHeaderExtensions().union(set(['c', 'cc', 'cpp', 'cxx', 'c++', 'cu'])) + return _valid_extensions + +def GetNonHeaderExtensions(): + return GetAllExtensions().difference(GetHeaderExtensions()) + + +_USAGE = """ +Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit] + [--filter=-x,+y,...] + [--counting=total|toplevel|detailed] [--repository=path] + [--root=subdir] [--linelength=digits] [--recursive] + [--exclude=path] + [--headers=ext1,ext2] + [--extensions=hpp,cpp,...] + [file] ... + + The style guidelines this tries to follow are those in + https://google.github.io/styleguide/cppguide.html + + Every problem is given a confidence score from 1-5, with 5 meaning we are + certain of the problem, and 1 meaning it could be a legitimate construct. + This will miss some errors, and is not a substitute for a code review. + + To suppress false-positive errors of a certain category, add a + 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) + suppresses errors of all categories on that line. + + The files passed in will be linted; at least one file must be provided. + Default linted extensions are %s. + Other file types will be ignored. + Change the extensions with the --extensions flag. + + Flags: + + output=emacs|eclipse|vs7|junit + By default, the output is formatted to ease emacs parsing. Output + compatible with eclipse (eclipse), Visual Studio (vs7), and JUnit + XML parsers such as those used in Jenkins and Bamboo may also be + used. Other formats are unsupported. + + verbose=# + Specify a number 0-5 to restrict errors to certain verbosity levels. + Errors with lower verbosity levels have lower confidence and are more + likely to be false positives. + + quiet + Supress output other than linting errors, such as information about + which files have been processed and excluded. + + filter=-x,+y,... + Specify a comma-separated list of category-filters to apply: only + error messages whose category names pass the filters will be printed. + (Category names are printed with the message and look like + "[whitespace/indent]".) Filters are evaluated left to right. + "-FOO" and "FOO" means "do not print categories that start with FOO". + "+FOO" means "do print categories that start with FOO". + + Examples: --filter=-whitespace,+whitespace/braces + --filter=whitespace,runtime/printf,+runtime/printf_format + --filter=-,+build/include_what_you_use + + To see a list of all the categories used in cpplint, pass no arg: + --filter= + + counting=total|toplevel|detailed + The total number of errors found is always printed. If + 'toplevel' is provided, then the count of errors in each of + the top-level categories like 'build' and 'whitespace' will + also be printed. If 'detailed' is provided, then a count + is provided for each category like 'build/class'. + + repository=path + The top level directory of the repository, used to derive the header + guard CPP variable. By default, this is determined by searching for a + path that contains .git, .hg, or .svn. When this flag is specified, the + given path is used instead. This option allows the header guard CPP + variable to remain consistent even if members of a team have different + repository root directories (such as when checking out a subdirectory + with SVN). In addition, users of non-mainstream version control systems + can use this flag to ensure readable header guard CPP variables. + + Examples: + Assuming that Alice checks out ProjectName and Bob checks out + ProjectName/trunk and trunk contains src/chrome/ui/browser.h, then + with no --repository flag, the header guard CPP variable will be: + + Alice => TRUNK_SRC_CHROME_BROWSER_UI_BROWSER_H_ + Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ + + If Alice uses the --repository=trunk flag and Bob omits the flag or + uses --repository=. then the header guard CPP variable will be: + + Alice => SRC_CHROME_BROWSER_UI_BROWSER_H_ + Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ + + root=subdir + The root directory used for deriving header guard CPP variables. This + directory is relative to the top level directory of the repository which + by default is determined by searching for a directory that contains .git, + .hg, or .svn but can also be controlled with the --repository flag. If + the specified directory does not exist, this flag is ignored. + + Examples: + Assuming that src is the top level directory of the repository, the + header guard CPP variables for src/chrome/browser/ui/browser.h are: + + No flag => CHROME_BROWSER_UI_BROWSER_H_ + --root=chrome => BROWSER_UI_BROWSER_H_ + --root=chrome/browser => UI_BROWSER_H_ + + linelength=digits + This is the allowed line length for the project. The default value is + 80 characters. + + Examples: + --linelength=120 + + recursive + Search for files to lint recursively. Each directory given in the list + of files to be linted is replaced by all files that descend from that + directory. Files with extensions not in the valid extensions list are + excluded. + + exclude=path + Exclude the given path from the list of files to be linted. Relative + paths are evaluated relative to the current directory and shell globbing + is performed. This flag can be provided multiple times to exclude + multiple files. + + Examples: + --exclude=one.cc + --exclude=src/*.cc + --exclude=src/*.cc --exclude=test/*.cc + + extensions=extension,extension,... + The allowed file extensions that cpplint will check + + Examples: + --extensions=%s + + headers=extension,extension,... + The allowed header extensions that cpplint will consider to be header files + (by default, only files with extensions %s + will be assumed to be headers) + + Examples: + --headers=%s + + cpplint.py supports per-directory configurations specified in CPPLINT.cfg + files. CPPLINT.cfg file can contain a number of key=value pairs. + Currently the following options are supported: + + set noparent + filter=+filter1,-filter2,... + exclude_files=regex + linelength=80 + root=subdir + + "set noparent" option prevents cpplint from traversing directory tree + upwards looking for more .cfg files in parent directories. This option + is usually placed in the top-level project directory. + + The "filter" option is similar in function to --filter flag. It specifies + message filters in addition to the |_DEFAULT_FILTERS| and those specified + through --filter command-line flag. + + "exclude_files" allows to specify a regular expression to be matched against + a file name. If the expression matches, the file is skipped and not run + through the linter. + + "linelength" specifies the allowed line length for the project. + + The "root" option is similar in function to the --root flag (see example + above). + + CPPLINT.cfg has an effect on files in the same directory and all + subdirectories, unless overridden by a nested configuration file. + + Example file: + filter=-build/include_order,+build/include_alpha + exclude_files=.*\\.cc + + The above example disables build/include_order warning and enables + build/include_alpha as well as excludes all .cc from being + processed by linter, in the current directory (where the .cfg + file is located) and all subdirectories. +""" % (list(GetAllExtensions()), + ','.join(list(GetAllExtensions())), + GetHeaderExtensions(), + ','.join(GetHeaderExtensions())) + +# We categorize each error message we print. Here are the categories. +# We want an explicit list so we can list them all in cpplint --filter=. +# If you add a new error message with a new category, add it to the list +# here! cpplint_unittest.py should tell you if you forget to do this. +_ERROR_CATEGORIES = [ + 'build/class', + 'build/c++11', + 'build/c++14', + 'build/c++tr1', + 'build/deprecated', + 'build/endif_comment', + 'build/explicit_make_pair', + 'build/forward_decl', + 'build/header_guard', + 'build/include', + 'build/include_subdir', + 'build/include_alpha', + 'build/include_order', + 'build/include_what_you_use', + 'build/namespaces_literals', + 'build/namespaces', + 'build/printf_format', + 'build/storage_class', + 'legal/copyright', + 'readability/alt_tokens', + 'readability/braces', + 'readability/casting', + 'readability/check', + 'readability/constructors', + 'readability/fn_size', + 'readability/inheritance', + 'readability/multiline_comment', + 'readability/multiline_string', + 'readability/namespace', + 'readability/nolint', + 'readability/nul', + 'readability/strings', + 'readability/todo', + 'readability/utf8', + 'runtime/arrays', + 'runtime/casting', + 'runtime/explicit', + 'runtime/int', + 'runtime/init', + 'runtime/invalid_increment', + 'runtime/member_string_references', + 'runtime/memset', + 'runtime/indentation_namespace', + 'runtime/operator', + 'runtime/printf', + 'runtime/printf_format', + 'runtime/references', + 'runtime/string', + 'runtime/threadsafe_fn', + 'runtime/vlog', + 'whitespace/blank_line', + 'whitespace/braces', + 'whitespace/comma', + 'whitespace/comments', + 'whitespace/empty_conditional_body', + 'whitespace/empty_if_body', + 'whitespace/empty_loop_body', + 'whitespace/end_of_line', + 'whitespace/ending_newline', + 'whitespace/forcolon', + 'whitespace/indent', + 'whitespace/line_length', + 'whitespace/newline', + 'whitespace/operators', + 'whitespace/parens', + 'whitespace/semicolon', + 'whitespace/tab', + 'whitespace/todo', + ] + +# These error categories are no longer enforced by cpplint, but for backwards- +# compatibility they may still appear in NOLINT comments. +_LEGACY_ERROR_CATEGORIES = [ + 'readability/streams', + 'readability/function', + ] + +# The default state of the category filter. This is overridden by the --filter= +# flag. By default all errors are on, so only add here categories that should be +# off by default (i.e., categories that must be enabled by the --filter= flags). +# All entries here should start with a '-' or '+', as in the --filter= flag. +_DEFAULT_FILTERS = ['-build/include_alpha'] + +# The default list of categories suppressed for C (not C++) files. +_DEFAULT_C_SUPPRESSED_CATEGORIES = [ + 'readability/casting', + ] + +# The default list of categories suppressed for Linux Kernel files. +_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [ + 'whitespace/tab', + ] + +# We used to check for high-bit characters, but after much discussion we +# decided those were OK, as long as they were in UTF-8 and didn't represent +# hard-coded international strings, which belong in a separate i18n file. + +# C++ headers +_CPP_HEADERS = frozenset([ + # Legacy + 'algobase.h', + 'algo.h', + 'alloc.h', + 'builtinbuf.h', + 'bvector.h', + 'complex.h', + 'defalloc.h', + 'deque.h', + 'editbuf.h', + 'fstream.h', + 'function.h', + 'hash_map', + 'hash_map.h', + 'hash_set', + 'hash_set.h', + 'hashtable.h', + 'heap.h', + 'indstream.h', + 'iomanip.h', + 'iostream.h', + 'istream.h', + 'iterator.h', + 'list.h', + 'map.h', + 'multimap.h', + 'multiset.h', + 'ostream.h', + 'pair.h', + 'parsestream.h', + 'pfstream.h', + 'procbuf.h', + 'pthread_alloc', + 'pthread_alloc.h', + 'rope', + 'rope.h', + 'ropeimpl.h', + 'set.h', + 'slist', + 'slist.h', + 'stack.h', + 'stdiostream.h', + 'stl_alloc.h', + 'stl_relops.h', + 'streambuf.h', + 'stream.h', + 'strfile.h', + 'strstream.h', + 'tempbuf.h', + 'tree.h', + 'type_traits.h', + 'vector.h', + # 17.6.1.2 C++ library headers + 'algorithm', + 'array', + 'atomic', + 'bitset', + 'chrono', + 'codecvt', + 'complex', + 'condition_variable', + 'deque', + 'exception', + 'forward_list', + 'fstream', + 'functional', + 'future', + 'initializer_list', + 'iomanip', + 'ios', + 'iosfwd', + 'iostream', + 'istream', + 'iterator', + 'limits', + 'list', + 'locale', + 'map', + 'memory', + 'mutex', + 'new', + 'numeric', + 'ostream', + 'queue', + 'random', + 'ratio', + 'regex', + 'scoped_allocator', + 'set', + 'sstream', + 'stack', + 'stdexcept', + 'streambuf', + 'string', + 'strstream', + 'system_error', + 'thread', + 'tuple', + 'typeindex', + 'typeinfo', + 'type_traits', + 'unordered_map', + 'unordered_set', + 'utility', + 'valarray', + 'vector', + # 17.6.1.2 C++ headers for C library facilities + 'cassert', + 'ccomplex', + 'cctype', + 'cerrno', + 'cfenv', + 'cfloat', + 'cinttypes', + 'ciso646', + 'climits', + 'clocale', + 'cmath', + 'csetjmp', + 'csignal', + 'cstdalign', + 'cstdarg', + 'cstdbool', + 'cstddef', + 'cstdint', + 'cstdio', + 'cstdlib', + 'cstring', + 'ctgmath', + 'ctime', + 'cuchar', + 'cwchar', + 'cwctype', + ]) + +# Type names +_TYPES = re.compile( + r'^(?:' + # [dcl.type.simple] + r'(char(16_t|32_t)?)|wchar_t|' + r'bool|short|int|long|signed|unsigned|float|double|' + # [support.types] + r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|' + # [cstdint.syn] + r'(u?int(_fast|_least)?(8|16|32|64)_t)|' + r'(u?int(max|ptr)_t)|' + r')$') + + +# These headers are excluded from [build/include] and [build/include_order] +# checks: +# - Anything not following google file name conventions (containing an +# uppercase character, such as Python.h or nsStringAPI.h, for example). +# - Lua headers. +_THIRD_PARTY_HEADERS_PATTERN = re.compile( + r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') + +# Pattern for matching FileInfo.BaseName() against test file name +_test_suffixes = ['_test', '_regtest', '_unittest'] +_TEST_FILE_SUFFIX = '(' + '|'.join(_test_suffixes) + r')$' + +# Pattern that matches only complete whitespace, possibly across multiple lines. +_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL) + +# Assertion macros. These are defined in base/logging.h and +# testing/base/public/gunit.h. +_CHECK_MACROS = [ + 'DCHECK', 'CHECK', + 'EXPECT_TRUE', 'ASSERT_TRUE', + 'EXPECT_FALSE', 'ASSERT_FALSE', + ] + +# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE +_CHECK_REPLACEMENT = dict([(macro_var, {}) for macro_var in _CHECK_MACROS]) + +for op, replacement in [('==', 'EQ'), ('!=', 'NE'), + ('>=', 'GE'), ('>', 'GT'), + ('<=', 'LE'), ('<', 'LT')]: + _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement + _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement + _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement + _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement + +for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), + ('>=', 'LT'), ('>', 'LE'), + ('<=', 'GT'), ('<', 'GE')]: + _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement + _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement + +# Alternative tokens and their replacements. For full list, see section 2.5 +# Alternative tokens [lex.digraph] in the C++ standard. +# +# Digraphs (such as '%:') are not included here since it's a mess to +# match those on a word boundary. +_ALT_TOKEN_REPLACEMENT = { + 'and': '&&', + 'bitor': '|', + 'or': '||', + 'xor': '^', + 'compl': '~', + 'bitand': '&', + 'and_eq': '&=', + 'or_eq': '|=', + 'xor_eq': '^=', + 'not': '!', + 'not_eq': '!=' + } + +# Compile regular expression that matches all the above keywords. The "[ =()]" +# bit is meant to avoid matching these keywords outside of boolean expressions. +# +# False positives include C-style multi-line comments and multi-line strings +# but those have always been troublesome for cpplint. +_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( + r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') + + +# These constants define types of headers for use with +# _IncludeState.CheckNextIncludeOrder(). +_C_SYS_HEADER = 1 +_CPP_SYS_HEADER = 2 +_LIKELY_MY_HEADER = 3 +_POSSIBLE_MY_HEADER = 4 +_OTHER_HEADER = 5 + +# These constants define the current inline assembly state +_NO_ASM = 0 # Outside of inline assembly block +_INSIDE_ASM = 1 # Inside inline assembly block +_END_ASM = 2 # Last line of inline assembly block +_BLOCK_ASM = 3 # The whole block is an inline assembly block + +# Match start of assembly blocks +_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' + r'(?:\s+(volatile|__volatile__))?' + r'\s*[{(]') + +# Match strings that indicate we're working on a C (not C++) file. +_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|' + r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))') + +# Match string that indicates we're working on a Linux Kernel file. +_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)') + +_regexp_compile_cache = {} + +# {str, set(int)}: a map from error categories to sets of linenumbers +# on which those errors are expected and should be suppressed. +_error_suppressions = {} + +# The root directory used for deriving header guard CPP variable. +# This is set by --root flag. +_root = None + +# The top level repository directory. If set, _root is calculated relative to +# this directory instead of the directory containing version control artifacts. +# This is set by the --repository flag. +_repository = None + +# Files to exclude from linting. This is set by the --exclude flag. +_excludes = None + +# Whether to supress PrintInfo messages +_quiet = False + +# The allowed line length of files. +# This is set by --linelength flag. +_line_length = 80 + +try: + xrange(1, 0) +except NameError: + # -- pylint: disable=redefined-builtin + xrange = range + +try: + unicode +except NameError: + # -- pylint: disable=redefined-builtin + basestring = unicode = str + +try: + long(2) +except NameError: + # -- pylint: disable=redefined-builtin + long = int + +if sys.version_info < (3,): + # -- pylint: disable=no-member + # BINARY_TYPE = str + itervalues = dict.itervalues + iteritems = dict.iteritems +else: + # BINARY_TYPE = bytes + itervalues = dict.values + iteritems = dict.items + +def unicode_escape_decode(x): + if sys.version_info < (3,): + return codecs.unicode_escape_decode(x)[0] + else: + return x + +# {str, bool}: a map from error categories to booleans which indicate if the +# category should be suppressed for every line. +_global_error_suppressions = {} + + + + +def ParseNolintSuppressions(filename, raw_line, linenum, error): + """Updates the global list of line error-suppressions. + + Parses any NOLINT comments on the current line, updating the global + error_suppressions store. Reports an error if the NOLINT comment + was malformed. + + Args: + filename: str, the name of the input file. + raw_line: str, the line of input text, with comments. + linenum: int, the number of the current line. + error: function, an error handler. + """ + matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) + if matched: + if matched.group(1): + suppressed_line = linenum + 1 + else: + suppressed_line = linenum + category = matched.group(2) + if category in (None, '(*)'): # => "suppress all" + _error_suppressions.setdefault(None, set()).add(suppressed_line) + else: + if category.startswith('(') and category.endswith(')'): + category = category[1:-1] + if category in _ERROR_CATEGORIES: + _error_suppressions.setdefault(category, set()).add(suppressed_line) + elif category not in _LEGACY_ERROR_CATEGORIES: + error(filename, linenum, 'readability/nolint', 5, + 'Unknown NOLINT error category: %s' % category) + + +def ProcessGlobalSuppresions(lines): + """Updates the list of global error suppressions. + + Parses any lint directives in the file that have global effect. + + Args: + lines: An array of strings, each representing a line of the file, with the + last element being empty if the file is terminated with a newline. + """ + for line in lines: + if _SEARCH_C_FILE.search(line): + for category in _DEFAULT_C_SUPPRESSED_CATEGORIES: + _global_error_suppressions[category] = True + if _SEARCH_KERNEL_FILE.search(line): + for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES: + _global_error_suppressions[category] = True + + +def ResetNolintSuppressions(): + """Resets the set of NOLINT suppressions to empty.""" + _error_suppressions.clear() + _global_error_suppressions.clear() + + +def IsErrorSuppressedByNolint(category, linenum): + """Returns true if the specified error category is suppressed on this line. + + Consults the global error_suppressions map populated by + ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. + + Args: + category: str, the category of the error. + linenum: int, the current line number. + Returns: + bool, True iff the error should be suppressed due to a NOLINT comment or + global suppression. + """ + return (_global_error_suppressions.get(category, False) or + linenum in _error_suppressions.get(category, set()) or + linenum in _error_suppressions.get(None, set())) + + +def Match(pattern, s): + """Matches the string with the pattern, caching the compiled regexp.""" + # The regexp compilation caching is inlined in both Match and Search for + # performance reasons; factoring it out into a separate function turns out + # to be noticeably expensive. + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].match(s) + + +def ReplaceAll(pattern, rep, s): + """Replaces instances of pattern in a string with a replacement. + + The compiled regex is kept in a cache shared by Match and Search. + + Args: + pattern: regex pattern + rep: replacement text + s: search string + + Returns: + string with replacements made (or original string if no replacements) + """ + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].sub(rep, s) + + +def Search(pattern, s): + """Searches the string for the pattern, caching the compiled regexp.""" + if pattern not in _regexp_compile_cache: + _regexp_compile_cache[pattern] = sre_compile.compile(pattern) + return _regexp_compile_cache[pattern].search(s) + + +def _IsSourceExtension(s): + """File extension (excluding dot) matches a source file extension.""" + return s in GetNonHeaderExtensions() + + +class _IncludeState(object): + """Tracks line numbers for includes, and the order in which includes appear. + + include_list contains list of lists of (header, line number) pairs. + It's a lists of lists rather than just one flat list to make it + easier to update across preprocessor boundaries. + + Call CheckNextIncludeOrder() once for each header in the file, passing + in the type constants defined above. Calls in an illegal order will + raise an _IncludeError with an appropriate error message. + + """ + # self._section will move monotonically through this set. If it ever + # needs to move backwards, CheckNextIncludeOrder will raise an error. + _INITIAL_SECTION = 0 + _MY_H_SECTION = 1 + _C_SECTION = 2 + _CPP_SECTION = 3 + _OTHER_H_SECTION = 4 + + _TYPE_NAMES = { + _C_SYS_HEADER: 'C system header', + _CPP_SYS_HEADER: 'C++ system header', + _LIKELY_MY_HEADER: 'header this file implements', + _POSSIBLE_MY_HEADER: 'header this file may implement', + _OTHER_HEADER: 'other header', + } + _SECTION_NAMES = { + _INITIAL_SECTION: "... nothing. (This can't be an error.)", + _MY_H_SECTION: 'a header this file implements', + _C_SECTION: 'C system header', + _CPP_SECTION: 'C++ system header', + _OTHER_H_SECTION: 'other header', + } + + def __init__(self): + self.include_list = [[]] + self._section = None + self._last_header = None + self.ResetSection('') + + def FindHeader(self, header): + """Check if a header has already been included. + + Args: + header: header to check. + Returns: + Line number of previous occurrence, or -1 if the header has not + been seen before. + """ + for section_list in self.include_list: + for f in section_list: + if f[0] == header: + return f[1] + return -1 + + def ResetSection(self, directive): + """Reset section checking for preprocessor directive. + + Args: + directive: preprocessor directive (e.g. "if", "else"). + """ + # The name of the current section. + self._section = self._INITIAL_SECTION + # The path of last found header. + self._last_header = '' + + # Update list of includes. Note that we never pop from the + # include list. + if directive in ('if', 'ifdef', 'ifndef'): + self.include_list.append([]) + elif directive in ('else', 'elif'): + self.include_list[-1] = [] + + def SetLastHeader(self, header_path): + self._last_header = header_path + + def CanonicalizeAlphabeticalOrder(self, header_path): + """Returns a path canonicalized for alphabetical comparison. + + - replaces "-" with "_" so they both cmp the same. + - removes '-inl' since we don't require them to be after the main header. + - lowercase everything, just in case. + + Args: + header_path: Path to be canonicalized. + + Returns: + Canonicalized path. + """ + return header_path.replace('-inl.h', '.h').replace('-', '_').lower() + + def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): + """Check if a header is in alphabetical order with the previous header. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + header_path: Canonicalized header to be checked. + + Returns: + Returns true if the header is in alphabetical order. + """ + # If previous section is different from current section, _last_header will + # be reset to empty string, so it's always less than current header. + # + # If previous line was a blank line, assume that the headers are + # intentionally sorted the way they are. + if (self._last_header > header_path and + Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): + return False + return True + + def CheckNextIncludeOrder(self, header_type): + """Returns a non-empty error message if the next header is out of order. + + This function also updates the internal state to be ready to check + the next include. + + Args: + header_type: One of the _XXX_HEADER constants defined above. + + Returns: + The empty string if the header is in the right order, or an + error message describing what's wrong. + + """ + error_message = ('Found %s after %s' % + (self._TYPE_NAMES[header_type], + self._SECTION_NAMES[self._section])) + + last_section = self._section + + if header_type == _C_SYS_HEADER: + if self._section <= self._C_SECTION: + self._section = self._C_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _CPP_SYS_HEADER: + if self._section <= self._CPP_SECTION: + self._section = self._CPP_SECTION + else: + self._last_header = '' + return error_message + elif header_type == _LIKELY_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + self._section = self._OTHER_H_SECTION + elif header_type == _POSSIBLE_MY_HEADER: + if self._section <= self._MY_H_SECTION: + self._section = self._MY_H_SECTION + else: + # This will always be the fallback because we're not sure + # enough that the header is associated with this file. + self._section = self._OTHER_H_SECTION + else: + assert header_type == _OTHER_HEADER + self._section = self._OTHER_H_SECTION + + if last_section != self._section: + self._last_header = '' + + return '' + + +class _CppLintState(object): + """Maintains module-wide state..""" + + def __init__(self): + self.verbose_level = 1 # global setting. + self.error_count = 0 # global count of reported errors + # filters to apply when emitting error messages + self.filters = _DEFAULT_FILTERS[:] + # backup of filter list. Used to restore the state after each file. + self._filters_backup = self.filters[:] + self.counting = 'total' # In what way are we counting errors? + self.errors_by_category = {} # string to int dict storing error counts + + # output format: + # "emacs" - format that emacs can parse (default) + # "eclipse" - format that eclipse can parse + # "vs7" - format that Microsoft Visual Studio 7 can parse + # "junit" - format that Jenkins, Bamboo, etc can parse + self.output_format = 'emacs' + + # For JUnit output, save errors and failures until the end so that they + # can be written into the XML + self._junit_errors = [] + self._junit_failures = [] + + def SetOutputFormat(self, output_format): + """Sets the output format for errors.""" + self.output_format = output_format + + def SetVerboseLevel(self, level): + """Sets the module's verbosity, and returns the previous setting.""" + last_verbose_level = self.verbose_level + self.verbose_level = level + return last_verbose_level + + def SetCountingStyle(self, counting_style): + """Sets the module's counting options.""" + self.counting = counting_style + + def SetFilters(self, filters): + """Sets the error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "+whitespace/indent"). + Each filter should start with + or -; else we die. + + Raises: + ValueError: The comma-separated filters did not all start with '+' or '-'. + E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" + """ + # Default filters always have less priority than the flag ones. + self.filters = _DEFAULT_FILTERS[:] + self.AddFilters(filters) + + def AddFilters(self, filters): + """ Adds more filters to the existing list of error-message filters. """ + for filt in filters.split(','): + clean_filt = filt.strip() + if clean_filt: + self.filters.append(clean_filt) + for filt in self.filters: + if not (filt.startswith('+') or filt.startswith('-')): + raise ValueError('Every filter in --filters must start with + or -' + ' (%s does not)' % filt) + + def BackupFilters(self): + """ Saves the current filter list to backup storage.""" + self._filters_backup = self.filters[:] + + def RestoreFilters(self): + """ Restores filters previously backed up.""" + self.filters = self._filters_backup[:] + + def ResetErrorCounts(self): + """Sets the module's error statistic back to zero.""" + self.error_count = 0 + self.errors_by_category = {} + + def IncrementErrorCount(self, category): + """Bumps the module's error statistic.""" + self.error_count += 1 + if self.counting in ('toplevel', 'detailed'): + if self.counting != 'detailed': + category = category.split('/')[0] + if category not in self.errors_by_category: + self.errors_by_category[category] = 0 + self.errors_by_category[category] += 1 + + def PrintErrorCounts(self): + """Print a summary of errors by category, and the total.""" + for category, count in sorted(iteritems(self.errors_by_category)): + self.PrintInfo('Category \'%s\' errors found: %d\n' % + (category, count)) + if self.error_count > 0: + self.PrintInfo('Total errors found: %d\n' % self.error_count) + + def PrintInfo(self, message): + if not _quiet and self.output_format != 'junit': + sys.stderr.write(message) + + def PrintError(self, message): + if self.output_format == 'junit': + self._junit_errors.append(message) + else: + sys.stderr.write(message) + + def AddJUnitFailure(self, filename, linenum, message, category, confidence): + self._junit_failures.append((filename, linenum, message, category, + confidence)) + + def FormatJUnitXML(self): + num_errors = len(self._junit_errors) + num_failures = len(self._junit_failures) + + testsuite = xml.etree.ElementTree.Element('testsuite') + testsuite.attrib['name'] = 'cpplint' + testsuite.attrib['errors'] = str(num_errors) + testsuite.attrib['failures'] = str(num_failures) + + if num_errors == 0 and num_failures == 0: + testsuite.attrib['tests'] = str(1) + xml.etree.ElementTree.SubElement(testsuite, 'testcase', name='passed') + + else: + testsuite.attrib['tests'] = str(num_errors + num_failures) + if num_errors > 0: + testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') + testcase.attrib['name'] = 'errors' + error = xml.etree.ElementTree.SubElement(testcase, 'error') + error.text = '\n'.join(self._junit_errors) + if num_failures > 0: + # Group failures by file + failed_file_order = [] + failures_by_file = {} + for failure in self._junit_failures: + failed_file = failure[0] + if failed_file not in failed_file_order: + failed_file_order.append(failed_file) + failures_by_file[failed_file] = [] + failures_by_file[failed_file].append(failure) + # Create a testcase for each file + for failed_file in failed_file_order: + failures = failures_by_file[failed_file] + testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') + testcase.attrib['name'] = failed_file + failure = xml.etree.ElementTree.SubElement(testcase, 'failure') + template = '{0}: {1} [{2}] [{3}]' + texts = [template.format(f[1], f[2], f[3], f[4]) for f in failures] + failure.text = '\n'.join(texts) + + xml_decl = '\n' + return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8') + + +_cpplint_state = _CppLintState() + + +def _OutputFormat(): + """Gets the module's output format.""" + return _cpplint_state.output_format + + +def _SetOutputFormat(output_format): + """Sets the module's output format.""" + _cpplint_state.SetOutputFormat(output_format) + + +def _VerboseLevel(): + """Returns the module's verbosity setting.""" + return _cpplint_state.verbose_level + + +def _SetVerboseLevel(level): + """Sets the module's verbosity, and returns the previous setting.""" + return _cpplint_state.SetVerboseLevel(level) + + +def _SetCountingStyle(level): + """Sets the module's counting options.""" + _cpplint_state.SetCountingStyle(level) + + +def _Filters(): + """Returns the module's list of output filters, as a list.""" + return _cpplint_state.filters + + +def _SetFilters(filters): + """Sets the module's error-message filters. + + These filters are applied when deciding whether to emit a given + error message. + + Args: + filters: A string of comma-separated filters (eg "whitespace/indent"). + Each filter should start with + or -; else we die. + """ + _cpplint_state.SetFilters(filters) + +def _AddFilters(filters): + """Adds more filter overrides. + + Unlike _SetFilters, this function does not reset the current list of filters + available. + + Args: + filters: A string of comma-separated filters (eg "whitespace/indent"). + Each filter should start with + or -; else we die. + """ + _cpplint_state.AddFilters(filters) + +def _BackupFilters(): + """ Saves the current filter list to backup storage.""" + _cpplint_state.BackupFilters() + +def _RestoreFilters(): + """ Restores filters previously backed up.""" + _cpplint_state.RestoreFilters() + +class _FunctionState(object): + """Tracks current function name and the number of lines in its body.""" + + _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. + _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. + + def __init__(self): + self.in_a_function = False + self.lines_in_function = 0 + self.current_function = '' + + def Begin(self, function_name): + """Start analyzing function body. + + Args: + function_name: The name of the function being tracked. + """ + self.in_a_function = True + self.lines_in_function = 0 + self.current_function = function_name + + def Count(self): + """Count line in current function body.""" + if self.in_a_function: + self.lines_in_function += 1 + + def Check(self, error, filename, linenum): + """Report if too many lines in function body. + + Args: + error: The function to call with any errors found. + filename: The name of the current file. + linenum: The number of the line to check. + """ + if not self.in_a_function: + return + + if Match(r'T(EST|est)', self.current_function): + base_trigger = self._TEST_TRIGGER + else: + base_trigger = self._NORMAL_TRIGGER + trigger = base_trigger * 2**_VerboseLevel() + + if self.lines_in_function > trigger: + error_level = int(math.log(self.lines_in_function / base_trigger, 2)) + # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... + if error_level > 5: + error_level = 5 + error(filename, linenum, 'readability/fn_size', error_level, + 'Small and focused functions are preferred:' + ' %s has %d non-comment lines' + ' (error triggered by exceeding %d lines).' % ( + self.current_function, self.lines_in_function, trigger)) + + def End(self): + """Stop analyzing function body.""" + self.in_a_function = False + + +class _IncludeError(Exception): + """Indicates a problem with the include order in a file.""" + pass + + +class FileInfo(object): + """Provides utility functions for filenames. + + FileInfo provides easy access to the components of a file's path + relative to the project root. + """ + + def __init__(self, filename): + self._filename = filename + + def FullName(self): + """Make Windows paths like Unix.""" + return os.path.abspath(self._filename).replace('\\', '/') + + def RepositoryName(self): + r"""FullName after removing the local path to the repository. + + If we have a real absolute path name here we can try to do something smart: + detecting the root of the checkout and truncating /path/to/checkout from + the name so that we get header guards that don't include things like + "C:\Documents and Settings\..." or "/home/username/..." in them and thus + people on different computers who have checked the source out to different + locations won't see bogus errors. + """ + fullname = self.FullName() + + if os.path.exists(fullname): + project_dir = os.path.dirname(fullname) + + # If the user specified a repository path, it exists, and the file is + # contained in it, use the specified repository path + if _repository: + repo = FileInfo(_repository).FullName() + root_dir = project_dir + while os.path.exists(root_dir): + # allow case insensitive compare on Windows + if os.path.normcase(root_dir) == os.path.normcase(repo): + return os.path.relpath(fullname, root_dir).replace('\\', '/') + one_up_dir = os.path.dirname(root_dir) + if one_up_dir == root_dir: + break + root_dir = one_up_dir + + if os.path.exists(os.path.join(project_dir, ".svn")): + # If there's a .svn file in the current directory, we recursively look + # up the directory tree for the top of the SVN checkout + root_dir = project_dir + one_up_dir = os.path.dirname(root_dir) + while os.path.exists(os.path.join(one_up_dir, ".svn")): + root_dir = os.path.dirname(root_dir) + one_up_dir = os.path.dirname(one_up_dir) + + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by + # searching up from the current path. + root_dir = current_dir = os.path.dirname(fullname) + while current_dir != os.path.dirname(current_dir): + if (os.path.exists(os.path.join(current_dir, ".git")) or + os.path.exists(os.path.join(current_dir, ".hg")) or + os.path.exists(os.path.join(current_dir, ".svn"))): + root_dir = current_dir + current_dir = os.path.dirname(current_dir) + + if (os.path.exists(os.path.join(root_dir, ".git")) or + os.path.exists(os.path.join(root_dir, ".hg")) or + os.path.exists(os.path.join(root_dir, ".svn"))): + prefix = os.path.commonprefix([root_dir, project_dir]) + return fullname[len(prefix) + 1:] + + # Don't know what to do; header guard warnings may be wrong... + return fullname + + def Split(self): + """Splits the file into the directory, basename, and extension. + + For 'chrome/browser/browser.cc', Split() would + return ('chrome/browser', 'browser', '.cc') + + Returns: + A tuple of (directory, basename, extension). + """ + + googlename = self.RepositoryName() + project, rest = os.path.split(googlename) + return (project,) + os.path.splitext(rest) + + def BaseName(self): + """File base name - text after the final slash, before the final period.""" + return self.Split()[1] + + def Extension(self): + """File extension - text following the final period, includes that period.""" + return self.Split()[2] + + def NoExtension(self): + """File has no source file extension.""" + return '/'.join(self.Split()[0:2]) + + def IsSource(self): + """File has a source file extension.""" + return _IsSourceExtension(self.Extension()[1:]) + + +def _ShouldPrintError(category, confidence, linenum): + """If confidence >= verbose, category passes filter and is not suppressed.""" + + # There are three ways we might decide not to print an error message: + # a "NOLINT(category)" comment appears in the source, + # the verbosity level isn't high enough, or the filters filter it out. + if IsErrorSuppressedByNolint(category, linenum): + return False + + if confidence < _cpplint_state.verbose_level: + return False + + is_filtered = False + for one_filter in _Filters(): + if one_filter.startswith('-'): + if category.startswith(one_filter[1:]): + is_filtered = True + elif one_filter.startswith('+'): + if category.startswith(one_filter[1:]): + is_filtered = False + else: + assert False # should have been checked for in SetFilter. + if is_filtered: + return False + + return True + + +def Error(filename, linenum, category, confidence, message): + """Logs the fact we've found a lint error. + + We log where the error was found, and also our confidence in the error, + that is, how certain we are this is a legitimate style regression, and + not a misidentification or a use that's sometimes justified. + + False positives can be suppressed by the use of + "cpplint(category)" comments on the offending line. These are + parsed into _error_suppressions. + + Args: + filename: The name of the file containing the error. + linenum: The number of the line containing the error. + category: A string used to describe the "category" this bug + falls under: "whitespace", say, or "runtime". Categories + may have a hierarchy separated by slashes: "whitespace/indent". + confidence: A number from 1-5 representing a confidence score for + the error, with 5 meaning that we are certain of the problem, + and 1 meaning that it could be a legitimate construct. + message: The error message. + """ + if _ShouldPrintError(category, confidence, linenum): + _cpplint_state.IncrementErrorCount(category) + if _cpplint_state.output_format == 'vs7': + _cpplint_state.PrintError('%s(%s): warning: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + elif _cpplint_state.output_format == 'eclipse': + sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence)) + elif _cpplint_state.output_format == 'junit': + _cpplint_state.AddJUnitFailure(filename, linenum, message, category, + confidence) + else: + final_message = '%s:%s: %s [%s] [%d]\n' % ( + filename, linenum, message, category, confidence) + sys.stderr.write(final_message) + +# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. +_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( + r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') +# Match a single C style comment on the same line. +_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' +# Matches multi-line C style comments. +# This RE is a little bit more complicated than one might expect, because we +# have to take care of space removals tools so we can handle comments inside +# statements better. +# The current rule is: We only clear spaces from both sides when we're at the +# end of the line. Otherwise, we try to remove spaces from the right side, +# if this doesn't work we try on left side but only if there's a non-character +# on the right. +_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( + r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + + _RE_PATTERN_C_COMMENTS + r'\s+|' + + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + + _RE_PATTERN_C_COMMENTS + r')') + + +def IsCppString(line): + """Does line terminate so, that the next symbol is in string constant. + + This function does not consider single-line nor multi-line comments. + + Args: + line: is a partial line of code starting from the 0..n. + + Returns: + True, if next character appended to 'line' is inside a + string constant. + """ + + line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" + return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 + + +def CleanseRawStrings(raw_lines): + """Removes C++11 raw strings from lines. + + Before: + static const char kData[] = R"( + multi-line string + )"; + + After: + static const char kData[] = "" + (replaced by blank line) + ""; + + Args: + raw_lines: list of raw lines. + + Returns: + list of lines with C++11 raw strings replaced by empty strings. + """ + + delimiter = None + lines_without_raw_strings = [] + for line in raw_lines: + if delimiter: + # Inside a raw string, look for the end + end = line.find(delimiter) + if end >= 0: + # Found the end of the string, match leading space for this + # line and resume copying the original lines, and also insert + # a "" on the last line. + leading_space = Match(r'^(\s*)\S', line) + line = leading_space.group(1) + '""' + line[end + len(delimiter):] + delimiter = None + else: + # Haven't found the end yet, append a blank line. + line = '""' + + # Look for beginning of a raw string, and replace them with + # empty strings. This is done in a loop to handle multiple raw + # strings on the same line. + while delimiter is None: + # Look for beginning of a raw string. + # See 2.14.15 [lex.string] for syntax. + # + # Once we have matched a raw string, we check the prefix of the + # line to make sure that the line is not part of a single line + # comment. It's done this way because we remove raw strings + # before removing comments as opposed to removing comments + # before removing raw strings. This is because there are some + # cpplint checks that requires the comments to be preserved, but + # we don't want to check comments that are inside raw strings. + matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) + if (matched and + not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//', + matched.group(1))): + delimiter = ')' + matched.group(2) + '"' + + end = matched.group(3).find(delimiter) + if end >= 0: + # Raw string ended on same line + line = (matched.group(1) + '""' + + matched.group(3)[end + len(delimiter):]) + delimiter = None + else: + # Start of a multi-line raw string + line = matched.group(1) + '""' + else: + break + + lines_without_raw_strings.append(line) + + # TODO(unknown): if delimiter is not None here, we might want to + # emit a warning for unterminated string. + return lines_without_raw_strings + + +def FindNextMultiLineCommentStart(lines, lineix): + """Find the beginning marker for a multiline comment.""" + while lineix < len(lines): + if lines[lineix].strip().startswith('/*'): + # Only return this marker if the comment goes beyond this line + if lines[lineix].strip().find('*/', 2) < 0: + return lineix + lineix += 1 + return len(lines) + + +def FindNextMultiLineCommentEnd(lines, lineix): + """We are inside a comment, find the end marker.""" + while lineix < len(lines): + if lines[lineix].strip().endswith('*/'): + return lineix + lineix += 1 + return len(lines) + + +def RemoveMultiLineCommentsFromRange(lines, begin, end): + """Clears a range of lines for multi-line comments.""" + # Having // dummy comments makes the lines non-empty, so we will not get + # unnecessary blank line warnings later in the code. + for i in range(begin, end): + lines[i] = '/**/' + + +def RemoveMultiLineComments(filename, lines, error): + """Removes multiline (c-style) comments from lines.""" + lineix = 0 + while lineix < len(lines): + lineix_begin = FindNextMultiLineCommentStart(lines, lineix) + if lineix_begin >= len(lines): + return + lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) + if lineix_end >= len(lines): + error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, + 'Could not find end of multi-line comment') + return + RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) + lineix = lineix_end + 1 + + +def CleanseComments(line): + """Removes //-comments and single-line C-style /* */ comments. + + Args: + line: A line of C++ source. + + Returns: + The line with single-line comments removed. + """ + commentpos = line.find('//') + if commentpos != -1 and not IsCppString(line[:commentpos]): + line = line[:commentpos].rstrip() + # get rid of /* ... */ + return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) + + +class CleansedLines(object): + """Holds 4 copies of all lines with different preprocessing applied to them. + + 1) elided member contains lines without strings and comments. + 2) lines member contains lines without comments. + 3) raw_lines member contains all the lines without processing. + 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw + strings removed. + All these members are of , and of the same length. + """ + + def __init__(self, lines): + self.elided = [] + self.lines = [] + self.raw_lines = lines + self.num_lines = len(lines) + self.lines_without_raw_strings = CleanseRawStrings(lines) + for linenum in range(len(self.lines_without_raw_strings)): + self.lines.append(CleanseComments( + self.lines_without_raw_strings[linenum])) + elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) + self.elided.append(CleanseComments(elided)) + + def NumLines(self): + """Returns the number of lines represented.""" + return self.num_lines + + @staticmethod + def _CollapseStrings(elided): + """Collapses strings and chars on a line to simple "" or '' blocks. + + We nix strings first so we're not fooled by text like '"http://"' + + Args: + elided: The line being processed. + + Returns: + The line with collapsed strings. + """ + if _RE_PATTERN_INCLUDE.match(elided): + return elided + + # Remove escaped characters first to make quote/single quote collapsing + # basic. Things that look like escaped characters shouldn't occur + # outside of strings and chars. + elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) + + # Replace quoted strings and digit separators. Both single quotes + # and double quotes are processed in the same loop, otherwise + # nested quotes wouldn't work. + collapsed = '' + while True: + # Find the first quote character + match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) + if not match: + collapsed += elided + break + head, quote, tail = match.groups() + + if quote == '"': + # Collapse double quoted strings + second_quote = tail.find('"') + if second_quote >= 0: + collapsed += head + '""' + elided = tail[second_quote + 1:] + else: + # Unmatched double quote, don't bother processing the rest + # of the line since this is probably a multiline string. + collapsed += elided + break + else: + # Found single quote, check nearby text to eliminate digit separators. + # + # There is no special handling for floating point here, because + # the integer/fractional/exponent parts would all be parsed + # correctly as long as there are digits on both sides of the + # separator. So we are fine as long as we don't see something + # like "0.'3" (gcc 4.9.0 will not allow this literal). + if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): + match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) + collapsed += head + match_literal.group(1).replace("'", '') + elided = match_literal.group(2) + else: + second_quote = tail.find('\'') + if second_quote >= 0: + collapsed += head + "''" + elided = tail[second_quote + 1:] + else: + # Unmatched single quote + collapsed += elided + break + + return collapsed + + +def FindEndOfExpressionInLine(line, startpos, stack): + """Find the position just after the end of current parenthesized expression. + + Args: + line: a CleansedLines line. + startpos: start searching at this position. + stack: nesting stack at startpos. + + Returns: + On finding matching end: (index just after matching end, None) + On finding an unclosed expression: (-1, None) + Otherwise: (-1, new stack at end of this line) + """ + for i in xrange(startpos, len(line)): + char = line[i] + if char in '([{': + # Found start of parenthesized expression, push to expression stack + stack.append(char) + elif char == '<': + # Found potential start of template argument list + if i > 0 and line[i - 1] == '<': + # Left shift operator + if stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + elif i > 0 and Search(r'\boperator\s*$', line[0:i]): + # operator<, don't add to stack + continue + else: + # Tentative start of template argument list + stack.append('<') + elif char in ')]}': + # Found end of parenthesized expression. + # + # If we are currently expecting a matching '>', the pending '<' + # must have been an operator. Remove them from expression stack. + while stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + if ((stack[-1] == '(' and char == ')') or + (stack[-1] == '[' and char == ']') or + (stack[-1] == '{' and char == '}')): + stack.pop() + if not stack: + return (i + 1, None) + else: + # Mismatched parentheses + return (-1, None) + elif char == '>': + # Found potential end of template argument list. + + # Ignore "->" and operator functions + if (i > 0 and + (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): + continue + + # Pop the stack if there is a matching '<'. Otherwise, ignore + # this '>' since it must be an operator. + if stack: + if stack[-1] == '<': + stack.pop() + if not stack: + return (i + 1, None) + elif char == ';': + # Found something that look like end of statements. If we are currently + # expecting a '>', the matching '<' must have been an operator, since + # template argument list should not contain statements. + while stack and stack[-1] == '<': + stack.pop() + if not stack: + return (-1, None) + + # Did not find end of expression or unbalanced parentheses on this line + return (-1, stack) + + +def CloseExpression(clean_lines, linenum, pos): + """If input points to ( or { or [ or <, finds the position that closes it. + + If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the + linenum/pos that correspond to the closing of the expression. + + TODO(unknown): cpplint spends a fair bit of time matching parentheses. + Ideally we would want to index all opening and closing parentheses once + and have CloseExpression be just a simple lookup, but due to preprocessor + tricks, this is not so easy. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: A position on the line. + + Returns: + A tuple (line, linenum, pos) pointer *past* the closing brace, or + (line, len(lines), -1) if we never find a close. Note we ignore + strings and comments when matching; and the line we return is the + 'cleansed' line at linenum. + """ + + line = clean_lines.elided[linenum] + if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): + return (line, clean_lines.NumLines(), -1) + + # Check first line + (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) + if end_pos > -1: + return (line, linenum, end_pos) + + # Continue scanning forward + while stack and linenum < clean_lines.NumLines() - 1: + linenum += 1 + line = clean_lines.elided[linenum] + (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) + if end_pos > -1: + return (line, linenum, end_pos) + + # Did not find end of expression before end of file, give up + return (line, clean_lines.NumLines(), -1) + + +def FindStartOfExpressionInLine(line, endpos, stack): + """Find position at the matching start of current expression. + + This is almost the reverse of FindEndOfExpressionInLine, but note + that the input position and returned position differs by 1. + + Args: + line: a CleansedLines line. + endpos: start searching at this position. + stack: nesting stack at endpos. + + Returns: + On finding matching start: (index at matching start, None) + On finding an unclosed expression: (-1, None) + Otherwise: (-1, new stack at beginning of this line) + """ + i = endpos + while i >= 0: + char = line[i] + if char in ')]}': + # Found end of expression, push to expression stack + stack.append(char) + elif char == '>': + # Found potential end of template argument list. + # + # Ignore it if it's a "->" or ">=" or "operator>" + if (i > 0 and + (line[i - 1] == '-' or + Match(r'\s>=\s', line[i - 1:]) or + Search(r'\boperator\s*$', line[0:i]))): + i -= 1 + else: + stack.append('>') + elif char == '<': + # Found potential start of template argument list + if i > 0 and line[i - 1] == '<': + # Left shift operator + i -= 1 + else: + # If there is a matching '>', we can pop the expression stack. + # Otherwise, ignore this '<' since it must be an operator. + if stack and stack[-1] == '>': + stack.pop() + if not stack: + return (i, None) + elif char in '([{': + # Found start of expression. + # + # If there are any unmatched '>' on the stack, they must be + # operators. Remove those. + while stack and stack[-1] == '>': + stack.pop() + if not stack: + return (-1, None) + if ((char == '(' and stack[-1] == ')') or + (char == '[' and stack[-1] == ']') or + (char == '{' and stack[-1] == '}')): + stack.pop() + if not stack: + return (i, None) + else: + # Mismatched parentheses + return (-1, None) + elif char == ';': + # Found something that look like end of statements. If we are currently + # expecting a '<', the matching '>' must have been an operator, since + # template argument list should not contain statements. + while stack and stack[-1] == '>': + stack.pop() + if not stack: + return (-1, None) + + i -= 1 + + return (-1, stack) + + +def ReverseCloseExpression(clean_lines, linenum, pos): + """If input points to ) or } or ] or >, finds the position that opens it. + + If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the + linenum/pos that correspond to the opening of the expression. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: A position on the line. + + Returns: + A tuple (line, linenum, pos) pointer *at* the opening brace, or + (line, 0, -1) if we never find the matching opening brace. Note + we ignore strings and comments when matching; and the line we + return is the 'cleansed' line at linenum. + """ + line = clean_lines.elided[linenum] + if line[pos] not in ')}]>': + return (line, 0, -1) + + # Check last line + (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) + if start_pos > -1: + return (line, linenum, start_pos) + + # Continue scanning backward + while stack and linenum > 0: + linenum -= 1 + line = clean_lines.elided[linenum] + (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) + if start_pos > -1: + return (line, linenum, start_pos) + + # Did not find start of expression before beginning of file, give up + return (line, 0, -1) + + +def CheckForCopyright(filename, lines, error): + """Logs an error if no Copyright message appears at the top of the file.""" + + # We'll say it should occur by line 10. Don't forget there's a + # dummy line at the front. + for line in range(1, min(len(lines), 11)): + if re.search(r'Copyright', lines[line], re.I): break + else: # means no copyright line was found + error(filename, 0, 'legal/copyright', 5, + 'No copyright message found. ' + 'You should have a line: "Copyright [year] "') + + +def GetIndentLevel(line): + """Return the number of leading spaces in line. + + Args: + line: A string to check. + + Returns: + An integer count of leading spaces, possibly zero. + """ + indent = Match(r'^( *)\S', line) + if indent: + return len(indent.group(1)) + else: + return 0 + + +def GetHeaderGuardCPPVariable(filename): + """Returns the CPP variable that should be used as a header guard. + + Args: + filename: The name of a C++ header file. + + Returns: + The CPP variable that should be used as a header guard in the + named file. + + """ + + # Restores original filename in case that cpplint is invoked from Emacs's + # flymake. + filename = re.sub(r'_flymake\.h$', '.h', filename) + filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) + # Replace 'c++' with 'cpp'. + filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') + + fileinfo = FileInfo(filename) + file_path_from_root = fileinfo.RepositoryName() + if _root: + suffix = os.sep + # On Windows using directory separator will leave us with + # "bogus escape error" unless we properly escape regex. + if suffix == '\\': + suffix += '\\' + file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root) + return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' + + +def CheckForHeaderGuard(filename, clean_lines, error): + """Checks that the file contains a header guard. + + Logs an error if no #ifndef header guard is present. For other + headers, checks that the full pathname is used. + + Args: + filename: The name of the C++ header file. + clean_lines: A CleansedLines instance containing the file. + error: The function to call with any errors found. + """ + + # Don't check for header guards if there are error suppression + # comments somewhere in this file. + # + # Because this is silencing a warning for a nonexistent line, we + # only support the very specific NOLINT(build/header_guard) syntax, + # and not the general NOLINT or NOLINT(*) syntax. + raw_lines = clean_lines.lines_without_raw_strings + for i in raw_lines: + if Search(r'//\s*NOLINT\(build/header_guard\)', i): + return + + # Allow pragma once instead of header guards + for i in raw_lines: + if Search(r'^\s*#pragma\s+once', i): + return + + cppvar = GetHeaderGuardCPPVariable(filename) + + ifndef = '' + ifndef_linenum = 0 + define = '' + endif = '' + endif_linenum = 0 + for linenum, line in enumerate(raw_lines): + linesplit = line.split() + if len(linesplit) >= 2: + # find the first occurrence of #ifndef and #define, save arg + if not ifndef and linesplit[0] == '#ifndef': + # set ifndef to the header guard presented on the #ifndef line. + ifndef = linesplit[1] + ifndef_linenum = linenum + if not define and linesplit[0] == '#define': + define = linesplit[1] + # find the last occurrence of #endif, save entire line + if line.startswith('#endif'): + endif = line + endif_linenum = linenum + + if not ifndef or not define or ifndef != define: + error(filename, 0, 'build/header_guard', 5, + 'No #ifndef header guard found, suggested CPP variable is: %s' % + cppvar) + return + + # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ + # for backward compatibility. + if ifndef != cppvar: + error_level = 0 + if ifndef != cppvar + '_': + error_level = 5 + + ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, + error) + error(filename, ifndef_linenum, 'build/header_guard', error_level, + '#ifndef header guard has wrong style, please use: %s' % cppvar) + + # Check for "//" comments on endif line. + ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, + error) + match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) + if match: + if match.group(1) == '_': + # Issue low severity warning for deprecated double trailing underscore + error(filename, endif_linenum, 'build/header_guard', 0, + '#endif line should be "#endif // %s"' % cppvar) + return + + # Didn't find the corresponding "//" comment. If this file does not + # contain any "//" comments at all, it could be that the compiler + # only wants "/**/" comments, look for those instead. + no_single_line_comments = True + for i in xrange(1, len(raw_lines) - 1): + line = raw_lines[i] + if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): + no_single_line_comments = False + break + + if no_single_line_comments: + match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) + if match: + if match.group(1) == '_': + # Low severity warning for double trailing underscore + error(filename, endif_linenum, 'build/header_guard', 0, + '#endif line should be "#endif /* %s */"' % cppvar) + return + + # Didn't find anything + error(filename, endif_linenum, 'build/header_guard', 5, + '#endif line should be "#endif // %s"' % cppvar) + + +def CheckHeaderFileIncluded(filename, include_state, error): + """Logs an error if a source file does not include its header.""" + + # Do not check test files + fileinfo = FileInfo(filename) + if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): + return + + for ext in GetHeaderExtensions(): + basefilename = filename[0:len(filename) - len(fileinfo.Extension())] + headerfile = basefilename + '.' + ext + if not os.path.exists(headerfile): + continue + headername = FileInfo(headerfile).RepositoryName() + first_include = None + for section_list in include_state.include_list: + for f in section_list: + if headername in f[0] or f[0] in headername: + return + if not first_include: + first_include = f[1] + + error(filename, first_include, 'build/include', 5, + '%s should include its header file %s' % (fileinfo.RepositoryName(), + headername)) + + +def CheckForBadCharacters(filename, lines, error): + """Logs an error for each line containing bad characters. + + Two kinds of bad characters: + + 1. Unicode replacement characters: These indicate that either the file + contained invalid UTF-8 (likely) or Unicode replacement characters (which + it shouldn't). Note that it's possible for this to throw off line + numbering if the invalid UTF-8 occurred adjacent to a newline. + + 2. NUL bytes. These are problematic for some tools. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + for linenum, line in enumerate(lines): + if unicode_escape_decode('\ufffd') in line: + error(filename, linenum, 'readability/utf8', 5, + 'Line contains invalid UTF-8 (or Unicode replacement character).') + if '\0' in line: + error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') + + +def CheckForNewlineAtEOF(filename, lines, error): + """Logs an error if there is no newline char at the end of the file. + + Args: + filename: The name of the current file. + lines: An array of strings, each representing a line of the file. + error: The function to call with any errors found. + """ + + # The array lines() was created by adding two newlines to the + # original file (go figure), then splitting on \n. + # To verify that the file ends in \n, we just have to make sure the + # last-but-two element of lines() exists and is empty. + if len(lines) < 3 or lines[-2]: + error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, + 'Could not find a newline character at the end of the file.') + + +def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): + """Logs an error if we see /* ... */ or "..." that extend past one line. + + /* ... */ comments are legit inside macros, for one line. + Otherwise, we prefer // comments, so it's ok to warn about the + other. Likewise, it's ok for strings to extend across multiple + lines, as long as a line continuation character (backslash) + terminates each line. Although not currently prohibited by the C++ + style guide, it's ugly and unnecessary. We don't do well with either + in this lint program, so we warn about both. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Remove all \\ (escaped backslashes) from the line. They are OK, and the + # second (escaped) slash may trigger later \" detection erroneously. + line = line.replace('\\\\', '') + + if line.count('/*') > line.count('*/'): + error(filename, linenum, 'readability/multiline_comment', 5, + 'Complex multi-line /*...*/-style comment found. ' + 'Lint may give bogus warnings. ' + 'Consider replacing these with //-style comments, ' + 'with #if 0...#endif, ' + 'or with more clearly structured multi-line comments.') + + if (line.count('"') - line.count('\\"')) % 2: + error(filename, linenum, 'readability/multiline_string', 5, + 'Multi-line string ("...") found. This lint script doesn\'t ' + 'do well with such strings, and may give bogus warnings. ' + 'Use C++11 raw strings or concatenation instead.') + + +# (non-threadsafe name, thread-safe alternative, validation pattern) +# +# The validation pattern is used to eliminate false positives such as: +# _rand(); // false positive due to substring match. +# ->rand(); // some member function rand(). +# ACMRandom rand(seed); // some variable named rand. +# ISAACRandom rand(); // another variable named rand. +# +# Basically we require the return value of these functions to be used +# in some expression context on the same line by matching on some +# operator before the function name. This eliminates constructors and +# member function calls. +_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' +_THREADING_LIST = ( + ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), + ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), + ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), + ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), + ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), + ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), + ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), + ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), + ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), + ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), + ('strtok(', 'strtok_r(', + _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), + ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), + ) + + +def CheckPosixThreading(filename, clean_lines, linenum, error): + """Checks for calls to thread-unsafe functions. + + Much code has been originally written without consideration of + multi-threading. Also, engineers are relying on their old experience; + they have learned posix before threading extensions were added. These + tests guide the engineers to use thread-safe functions (when using + posix directly). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: + # Additional pattern matching check to confirm that this is the + # function we are looking for + if Search(pattern, line): + error(filename, linenum, 'runtime/threadsafe_fn', 2, + 'Consider using ' + multithread_safe_func + + '...) instead of ' + single_thread_func + + '...) for improved thread safety.') + + +def CheckVlogArguments(filename, clean_lines, linenum, error): + """Checks that VLOG() is only used for defining a logging level. + + For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and + VLOG(FATAL) are not. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): + error(filename, linenum, 'runtime/vlog', 5, + 'VLOG() should be used with numeric verbosity level. ' + 'Use LOG() if you want symbolic severity levels.') + +# Matches invalid increment: *count++, which moves pointer instead of +# incrementing a value. +_RE_PATTERN_INVALID_INCREMENT = re.compile( + r'^\s*\*\w+(\+\+|--);') + + +def CheckInvalidIncrement(filename, clean_lines, linenum, error): + """Checks for invalid increment *count++. + + For example following function: + void increment_counter(int* count) { + *count++; + } + is invalid, because it effectively does count++, moving pointer, and should + be replaced with ++*count, (*count)++ or *count += 1. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + if _RE_PATTERN_INVALID_INCREMENT.match(line): + error(filename, linenum, 'runtime/invalid_increment', 5, + 'Changing pointer instead of value (or unused value of operator*).') + + +def IsMacroDefinition(clean_lines, linenum): + if Search(r'^#define', clean_lines[linenum]): + return True + + if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): + return True + + return False + + +def IsForwardClassDeclaration(clean_lines, linenum): + return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) + + +class _BlockInfo(object): + """Stores information about a generic block of code.""" + + def __init__(self, linenum, seen_open_brace): + self.starting_linenum = linenum + self.seen_open_brace = seen_open_brace + self.open_parentheses = 0 + self.inline_asm = _NO_ASM + self.check_namespace_indentation = False + + def CheckBegin(self, filename, clean_lines, linenum, error): + """Run checks that applies to text up to the opening brace. + + This is mostly for checking the text after the class identifier + and the "{", usually where the base class is specified. For other + blocks, there isn't much to check, so we always pass. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + pass + + def CheckEnd(self, filename, clean_lines, linenum, error): + """Run checks that applies to text after the closing brace. + + This is mostly used for checking end of namespace comments. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + pass + + def IsBlockInfo(self): + """Returns true if this block is a _BlockInfo. + + This is convenient for verifying that an object is an instance of + a _BlockInfo, but not an instance of any of the derived classes. + + Returns: + True for this class, False for derived classes. + """ + return self.__class__ == _BlockInfo + + +class _ExternCInfo(_BlockInfo): + """Stores information about an 'extern "C"' block.""" + + def __init__(self, linenum): + _BlockInfo.__init__(self, linenum, True) + + +class _ClassInfo(_BlockInfo): + """Stores information about a class.""" + + def __init__(self, name, class_or_struct, clean_lines, linenum): + _BlockInfo.__init__(self, linenum, False) + self.name = name + self.is_derived = False + self.check_namespace_indentation = True + if class_or_struct == 'struct': + self.access = 'public' + self.is_struct = True + else: + self.access = 'private' + self.is_struct = False + + # Remember initial indentation level for this class. Using raw_lines here + # instead of elided to account for leading comments. + self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) + + # Try to find the end of the class. This will be confused by things like: + # class A { + # } *x = { ... + # + # But it's still good enough for CheckSectionSpacing. + self.last_line = 0 + depth = 0 + for i in range(linenum, clean_lines.NumLines()): + line = clean_lines.elided[i] + depth += line.count('{') - line.count('}') + if not depth: + self.last_line = i + break + + def CheckBegin(self, filename, clean_lines, linenum, error): + # Look for a bare ':' + if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): + self.is_derived = True + + def CheckEnd(self, filename, clean_lines, linenum, error): + # If there is a DISALLOW macro, it should appear near the end of + # the class. + seen_last_thing_in_class = False + for i in xrange(linenum - 1, self.starting_linenum, -1): + match = Search( + r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + + self.name + r'\)', + clean_lines.elided[i]) + if match: + if seen_last_thing_in_class: + error(filename, i, 'readability/constructors', 3, + match.group(1) + ' should be the last thing in the class') + break + + if not Match(r'^\s*$', clean_lines.elided[i]): + seen_last_thing_in_class = True + + # Check that closing brace is aligned with beginning of the class. + # Only do this if the closing brace is indented by only whitespaces. + # This means we will not check single-line class definitions. + indent = Match(r'^( *)\}', clean_lines.elided[linenum]) + if indent and len(indent.group(1)) != self.class_indent: + if self.is_struct: + parent = 'struct ' + self.name + else: + parent = 'class ' + self.name + error(filename, linenum, 'whitespace/indent', 3, + 'Closing brace should be aligned with beginning of %s' % parent) + + +class _NamespaceInfo(_BlockInfo): + """Stores information about a namespace.""" + + def __init__(self, name, linenum): + _BlockInfo.__init__(self, linenum, False) + self.name = name or '' + self.check_namespace_indentation = True + + def CheckEnd(self, filename, clean_lines, linenum, error): + """Check end of namespace comments.""" + line = clean_lines.raw_lines[linenum] + + # Check how many lines is enclosed in this namespace. Don't issue + # warning for missing namespace comments if there aren't enough + # lines. However, do apply checks if there is already an end of + # namespace comment and it's incorrect. + # + # TODO(unknown): We always want to check end of namespace comments + # if a namespace is large, but sometimes we also want to apply the + # check if a short namespace contained nontrivial things (something + # other than forward declarations). There is currently no logic on + # deciding what these nontrivial things are, so this check is + # triggered by namespace size only, which works most of the time. + if (linenum - self.starting_linenum < 10 + and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): + return + + # Look for matching comment at end of namespace. + # + # Note that we accept C style "/* */" comments for terminating + # namespaces, so that code that terminate namespaces inside + # preprocessor macros can be cpplint clean. + # + # We also accept stuff like "// end of namespace ." with the + # period at the end. + # + # Besides these, we don't accept anything else, otherwise we might + # get false negatives when existing comment is a substring of the + # expected namespace. + if self.name: + # Named namespace + if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + + re.escape(self.name) + r'[\*/\.\\\s]*$'), + line): + error(filename, linenum, 'readability/namespace', 5, + 'Namespace should be terminated with "// namespace %s"' % + self.name) + else: + # Anonymous namespace + if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): + # If "// namespace anonymous" or "// anonymous namespace (more text)", + # mention "// anonymous namespace" as an acceptable form + if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): + error(filename, linenum, 'readability/namespace', 5, + 'Anonymous namespace should be terminated with "// namespace"' + ' or "// anonymous namespace"') + else: + error(filename, linenum, 'readability/namespace', 5, + 'Anonymous namespace should be terminated with "// namespace"') + + +class _PreprocessorInfo(object): + """Stores checkpoints of nesting stacks when #if/#else is seen.""" + + def __init__(self, stack_before_if): + # The entire nesting stack before #if + self.stack_before_if = stack_before_if + + # The entire nesting stack up to #else + self.stack_before_else = [] + + # Whether we have already seen #else or #elif + self.seen_else = False + + +class NestingState(object): + """Holds states related to parsing braces.""" + + def __init__(self): + # Stack for tracking all braces. An object is pushed whenever we + # see a "{", and popped when we see a "}". Only 3 types of + # objects are possible: + # - _ClassInfo: a class or struct. + # - _NamespaceInfo: a namespace. + # - _BlockInfo: some other type of block. + self.stack = [] + + # Top of the previous stack before each Update(). + # + # Because the nesting_stack is updated at the end of each line, we + # had to do some convoluted checks to find out what is the current + # scope at the beginning of the line. This check is simplified by + # saving the previous top of nesting stack. + # + # We could save the full stack, but we only need the top. Copying + # the full nesting stack would slow down cpplint by ~10%. + self.previous_stack_top = [] + + # Stack of _PreprocessorInfo objects. + self.pp_stack = [] + + def SeenOpenBrace(self): + """Check if we have seen the opening brace for the innermost block. + + Returns: + True if we have seen the opening brace, False if the innermost + block is still expecting an opening brace. + """ + return (not self.stack) or self.stack[-1].seen_open_brace + + def InNamespaceBody(self): + """Check if we are currently one level inside a namespace body. + + Returns: + True if top of the stack is a namespace block, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _NamespaceInfo) + + def InExternC(self): + """Check if we are currently one level inside an 'extern "C"' block. + + Returns: + True if top of the stack is an extern block, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _ExternCInfo) + + def InClassDeclaration(self): + """Check if we are currently one level inside a class or struct declaration. + + Returns: + True if top of the stack is a class/struct, False otherwise. + """ + return self.stack and isinstance(self.stack[-1], _ClassInfo) + + def InAsmBlock(self): + """Check if we are currently one level inside an inline ASM block. + + Returns: + True if the top of the stack is a block containing inline ASM. + """ + return self.stack and self.stack[-1].inline_asm != _NO_ASM + + def InTemplateArgumentList(self, clean_lines, linenum, pos): + """Check if current position is inside template argument list. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + pos: position just after the suspected template argument. + Returns: + True if (linenum, pos) is inside template arguments. + """ + while linenum < clean_lines.NumLines(): + # Find the earliest character that might indicate a template argument + line = clean_lines.elided[linenum] + match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) + if not match: + linenum += 1 + pos = 0 + continue + token = match.group(1) + pos += len(match.group(0)) + + # These things do not look like template argument list: + # class Suspect { + # class Suspect x; } + if token in ('{', '}', ';'): return False + + # These things look like template argument list: + # template + # template + # template + # template + if token in ('>', '=', '[', ']', '.'): return True + + # Check if token is an unmatched '<'. + # If not, move on to the next character. + if token != '<': + pos += 1 + if pos >= len(line): + linenum += 1 + pos = 0 + continue + + # We can't be sure if we just find a single '<', and need to + # find the matching '>'. + (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) + if end_pos < 0: + # Not sure if template argument list or syntax error in file + return False + linenum = end_line + pos = end_pos + return False + + def UpdatePreprocessor(self, line): + """Update preprocessor stack. + + We need to handle preprocessors due to classes like this: + #ifdef SWIG + struct ResultDetailsPageElementExtensionPoint { + #else + struct ResultDetailsPageElementExtensionPoint : public Extension { + #endif + + We make the following assumptions (good enough for most files): + - Preprocessor condition evaluates to true from #if up to first + #else/#elif/#endif. + + - Preprocessor condition evaluates to false from #else/#elif up + to #endif. We still perform lint checks on these lines, but + these do not affect nesting stack. + + Args: + line: current line to check. + """ + if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): + # Beginning of #if block, save the nesting stack here. The saved + # stack will allow us to restore the parsing state in the #else case. + self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) + elif Match(r'^\s*#\s*(else|elif)\b', line): + # Beginning of #else block + if self.pp_stack: + if not self.pp_stack[-1].seen_else: + # This is the first #else or #elif block. Remember the + # whole nesting stack up to this point. This is what we + # keep after the #endif. + self.pp_stack[-1].seen_else = True + self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) + + # Restore the stack to how it was before the #if + self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) + else: + # TODO(unknown): unexpected #else, issue warning? + pass + elif Match(r'^\s*#\s*endif\b', line): + # End of #if or #else blocks. + if self.pp_stack: + # If we saw an #else, we will need to restore the nesting + # stack to its former state before the #else, otherwise we + # will just continue from where we left off. + if self.pp_stack[-1].seen_else: + # Here we can just use a shallow copy since we are the last + # reference to it. + self.stack = self.pp_stack[-1].stack_before_else + # Drop the corresponding #if + self.pp_stack.pop() + else: + # TODO(unknown): unexpected #endif, issue warning? + pass + + # TODO(unknown): Update() is too long, but we will refactor later. + def Update(self, filename, clean_lines, linenum, error): + """Update nesting state with current line. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Remember top of the previous nesting stack. + # + # The stack is always pushed/popped and not modified in place, so + # we can just do a shallow copy instead of copy.deepcopy. Using + # deepcopy would slow down cpplint by ~28%. + if self.stack: + self.previous_stack_top = self.stack[-1] + else: + self.previous_stack_top = None + + # Update pp_stack + self.UpdatePreprocessor(line) + + # Count parentheses. This is to avoid adding struct arguments to + # the nesting stack. + if self.stack: + inner_block = self.stack[-1] + depth_change = line.count('(') - line.count(')') + inner_block.open_parentheses += depth_change + + # Also check if we are starting or ending an inline assembly block. + if inner_block.inline_asm in (_NO_ASM, _END_ASM): + if (depth_change != 0 and + inner_block.open_parentheses == 1 and + _MATCH_ASM.match(line)): + # Enter assembly block + inner_block.inline_asm = _INSIDE_ASM + else: + # Not entering assembly block. If previous line was _END_ASM, + # we will now shift to _NO_ASM state. + inner_block.inline_asm = _NO_ASM + elif (inner_block.inline_asm == _INSIDE_ASM and + inner_block.open_parentheses == 0): + # Exit assembly block + inner_block.inline_asm = _END_ASM + + # Consume namespace declaration at the beginning of the line. Do + # this in a loop so that we catch same line declarations like this: + # namespace proto2 { namespace bridge { class MessageSet; } } + while True: + # Match start of namespace. The "\b\s*" below catches namespace + # declarations even if it weren't followed by a whitespace, this + # is so that we don't confuse our namespace checker. The + # missing spaces will be flagged by CheckSpacing. + namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) + if not namespace_decl_match: + break + + new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) + self.stack.append(new_namespace) + + line = namespace_decl_match.group(2) + if line.find('{') != -1: + new_namespace.seen_open_brace = True + line = line[line.find('{') + 1:] + + # Look for a class declaration in whatever is left of the line + # after parsing namespaces. The regexp accounts for decorated classes + # such as in: + # class LOCKABLE API Object { + # }; + class_decl_match = Match( + r'^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?' + r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' + r'(.*)$', line) + if (class_decl_match and + (not self.stack or self.stack[-1].open_parentheses == 0)): + # We do not want to accept classes that are actually template arguments: + # template , + # template class Ignore3> + # void Function() {}; + # + # To avoid template argument cases, we scan forward and look for + # an unmatched '>'. If we see one, assume we are inside a + # template argument list. + end_declaration = len(class_decl_match.group(1)) + if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): + self.stack.append(_ClassInfo( + class_decl_match.group(3), class_decl_match.group(2), + clean_lines, linenum)) + line = class_decl_match.group(4) + + # If we have not yet seen the opening brace for the innermost block, + # run checks here. + if not self.SeenOpenBrace(): + self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) + + # Update access control if we are inside a class/struct + if self.stack and isinstance(self.stack[-1], _ClassInfo): + classinfo = self.stack[-1] + access_match = Match( + r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' + r':(?:[^:]|$)', + line) + if access_match: + classinfo.access = access_match.group(2) + + # Check that access keywords are indented +1 space. Skip this + # check if the keywords are not preceded by whitespaces. + indent = access_match.group(1) + if (len(indent) != classinfo.class_indent + 1 and + Match(r'^\s*$', indent)): + if classinfo.is_struct: + parent = 'struct ' + classinfo.name + else: + parent = 'class ' + classinfo.name + slots = '' + if access_match.group(3): + slots = access_match.group(3) + error(filename, linenum, 'whitespace/indent', 3, + '%s%s: should be indented +1 space inside %s' % ( + access_match.group(2), slots, parent)) + + # Consume braces or semicolons from what's left of the line + while True: + # Match first brace, semicolon, or closed parenthesis. + matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) + if not matched: + break + + token = matched.group(1) + if token == '{': + # If namespace or class hasn't seen a opening brace yet, mark + # namespace/class head as complete. Push a new block onto the + # stack otherwise. + if not self.SeenOpenBrace(): + self.stack[-1].seen_open_brace = True + elif Match(r'^extern\s*"[^"]*"\s*\{', line): + self.stack.append(_ExternCInfo(linenum)) + else: + self.stack.append(_BlockInfo(linenum, True)) + if _MATCH_ASM.match(line): + self.stack[-1].inline_asm = _BLOCK_ASM + + elif token == ';' or token == ')': + # If we haven't seen an opening brace yet, but we already saw + # a semicolon, this is probably a forward declaration. Pop + # the stack for these. + # + # Similarly, if we haven't seen an opening brace yet, but we + # already saw a closing parenthesis, then these are probably + # function arguments with extra "class" or "struct" keywords. + # Also pop these stack for these. + if not self.SeenOpenBrace(): + self.stack.pop() + else: # token == '}' + # Perform end of block checks and pop the stack. + if self.stack: + self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) + self.stack.pop() + line = matched.group(2) + + def InnermostClass(self): + """Get class info on the top of the stack. + + Returns: + A _ClassInfo object if we are inside a class, or None otherwise. + """ + for i in range(len(self.stack), 0, -1): + classinfo = self.stack[i - 1] + if isinstance(classinfo, _ClassInfo): + return classinfo + return None + + def CheckCompletedBlocks(self, filename, error): + """Checks that all classes and namespaces have been completely parsed. + + Call this when all lines in a file have been processed. + Args: + filename: The name of the current file. + error: The function to call with any errors found. + """ + # Note: This test can result in false positives if #ifdef constructs + # get in the way of brace matching. See the testBuildClass test in + # cpplint_unittest.py for an example of this. + for obj in self.stack: + if isinstance(obj, _ClassInfo): + error(filename, obj.starting_linenum, 'build/class', 5, + 'Failed to find complete declaration of class %s' % + obj.name) + elif isinstance(obj, _NamespaceInfo): + error(filename, obj.starting_linenum, 'build/namespaces', 5, + 'Failed to find complete declaration of namespace %s' % + obj.name) + + +def CheckForNonStandardConstructs(filename, clean_lines, linenum, + nesting_state, error): + r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. + + Complain about several constructs which gcc-2 accepts, but which are + not standard C++. Warning about these in lint is one way to ease the + transition to new compilers. + - put storage class first (e.g. "static const" instead of "const static"). + - "%lld" instead of %qd" in printf-type functions. + - "%1$d" is non-standard in printf-type functions. + - "\%" is an undefined character escape sequence. + - text after #endif is not allowed. + - invalid inner-style forward declaration. + - >? and ?= and )\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', + line): + error(filename, linenum, 'build/deprecated', 3, + '>? and ))?' + # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' + error(filename, linenum, 'runtime/member_string_references', 2, + 'const string& members are dangerous. It is much better to use ' + 'alternatives, such as pointers or simple constants.') + + # Everything else in this function operates on class declarations. + # Return early if the top of the nesting stack is not a class, or if + # the class head is not completed yet. + classinfo = nesting_state.InnermostClass() + if not classinfo or not classinfo.seen_open_brace: + return + + # The class may have been declared with namespace or classname qualifiers. + # The constructor and destructor will not have those qualifiers. + base_classname = classinfo.name.split('::')[-1] + + # Look for single-argument constructors that aren't marked explicit. + # Technically a valid construct, but against style. + explicit_constructor_match = Match( + r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' + r'\(((?:[^()]|\([^()]*\))*)\)' + % re.escape(base_classname), + line) + + if explicit_constructor_match: + is_marked_explicit = explicit_constructor_match.group(1) + + if not explicit_constructor_match.group(2): + constructor_args = [] + else: + constructor_args = explicit_constructor_match.group(2).split(',') + + # collapse arguments so that commas in template parameter lists and function + # argument parameter lists don't split arguments in two + i = 0 + while i < len(constructor_args): + constructor_arg = constructor_args[i] + while (constructor_arg.count('<') > constructor_arg.count('>') or + constructor_arg.count('(') > constructor_arg.count(')')): + constructor_arg += ',' + constructor_args[i + 1] + del constructor_args[i + 1] + constructor_args[i] = constructor_arg + i += 1 + + variadic_args = [arg for arg in constructor_args if '&&...' in arg] + defaulted_args = [arg for arg in constructor_args if '=' in arg] + noarg_constructor = (not constructor_args or # empty arg list + # 'void' arg specifier + (len(constructor_args) == 1 and + constructor_args[0].strip() == 'void')) + onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg + not noarg_constructor) or + # all but at most one arg defaulted + (len(constructor_args) >= 1 and + not noarg_constructor and + len(defaulted_args) >= len(constructor_args) - 1) or + # variadic arguments with zero or one argument + (len(constructor_args) <= 2 and + len(variadic_args) >= 1)) + initializer_list_constructor = bool( + onearg_constructor and + Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) + copy_constructor = bool( + onearg_constructor and + Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' + % re.escape(base_classname), constructor_args[0].strip())) + + if (not is_marked_explicit and + onearg_constructor and + not initializer_list_constructor and + not copy_constructor): + if defaulted_args or variadic_args: + error(filename, linenum, 'runtime/explicit', 5, + 'Constructors callable with one argument ' + 'should be marked explicit.') + else: + error(filename, linenum, 'runtime/explicit', 5, + 'Single-parameter constructors should be marked explicit.') + elif is_marked_explicit and not onearg_constructor: + if noarg_constructor: + error(filename, linenum, 'runtime/explicit', 5, + 'Zero-parameter constructors should not be marked explicit.') + + +def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): + """Checks for the correctness of various spacing around function calls. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Since function calls often occur inside if/for/while/switch + # expressions - which have their own, more liberal conventions - we + # first see if we should be looking inside such an expression for a + # function call, to which we can apply more strict standards. + fncall = line # if there's no control flow construct, look at whole line + for pattern in (r'\bif\s*\((.*)\)\s*{', + r'\bfor\s*\((.*)\)\s*{', + r'\bwhile\s*\((.*)\)\s*[{;]', + r'\bswitch\s*\((.*)\)\s*{'): + match = Search(pattern, line) + if match: + fncall = match.group(1) # look inside the parens for function calls + break + + # Except in if/for/while/switch, there should never be space + # immediately inside parens (eg "f( 3, 4 )"). We make an exception + # for nested parens ( (a+b) + c ). Likewise, there should never be + # a space before a ( when it's a function argument. I assume it's a + # function argument when the char before the whitespace is legal in + # a function name (alnum + _) and we're not starting a macro. Also ignore + # pointers and references to arrays and functions coz they're too tricky: + # we use a very simple way to recognize these: + # " (something)(maybe-something)" or + # " (something)(maybe-something," or + # " (something)[something]" + # Note that we assume the contents of [] to be short enough that + # they'll never need to wrap. + if ( # Ignore control structures. + not Search(r'\b(if|or|and|for|while|switch|return|new|delete|catch|sizeof)\b', + fncall) and + # Ignore pointers/references to functions. + not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and + # Ignore pointers/references to arrays. + not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): + if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call + error(filename, linenum, 'whitespace/parens', 4, + 'Extra space after ( in function call') + elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): + error(filename, linenum, 'whitespace/parens', 2, + 'Extra space after (') + if (Search(r'\w\s+\(', fncall) and + not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and + not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and + not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and + not Search(r'\bcase\s+\(', fncall)): + # TODO(unknown): Space after an operator function seem to be a common + # error, silence those for now by restricting them to highest verbosity. + if Search(r'\boperator_*\b', line): + error(filename, linenum, 'whitespace/parens', 0, + 'Extra space before ( in function call') + else: + error(filename, linenum, 'whitespace/parens', 4, + 'Extra space before ( in function call') + # If the ) is followed only by a newline or a { + newline, assume it's + # part of a control statement (if/while/etc), and don't complain + if Search(r'[^)]\s+\)\s*[^{\s]', fncall): + # If the closing parenthesis is preceded by only whitespaces, + # try to give a more descriptive error message. + if Search(r'^\s+\)', fncall): + error(filename, linenum, 'whitespace/parens', 2, + 'Closing ) should be moved to the previous line') + else: + error(filename, linenum, 'whitespace/parens', 2, + 'Extra space before )') + + +def IsBlankLine(line): + """Returns true if the given line is blank. + + We consider a line to be blank if the line is empty or consists of + only white spaces. + + Args: + line: A line of a string. + + Returns: + True, if the given line is blank. + """ + return not line or line.isspace() + + +def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, + error): + is_namespace_indent_item = ( + len(nesting_state.stack) > 1 and + nesting_state.stack[-1].check_namespace_indentation and + isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and + nesting_state.previous_stack_top == nesting_state.stack[-2]) + + if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, + clean_lines.elided, line): + CheckItemIndentationInNamespace(filename, clean_lines.elided, + line, error) + + +def CheckForFunctionLengths(filename, clean_lines, linenum, + function_state, error): + """Reports for long function bodies. + + For an overview why this is done, see: + https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions + + Uses a simplistic algorithm assuming other style guidelines + (especially spacing) are followed. + Only checks unindented functions, so class members are unchecked. + Trivial bodies are unchecked, so constructors with huge initializer lists + may be missed. + Blank/comment lines are not counted so as to avoid encouraging the removal + of vertical space and comments just to get through a lint check. + NOLINT *on the last line of a function* disables this check. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + function_state: Current function name and lines in body so far. + error: The function to call with any errors found. + """ + lines = clean_lines.lines + line = lines[linenum] + joined_line = '' + + starting_func = False + regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... + match_result = Match(regexp, line) + if match_result: + # If the name is all caps and underscores, figure it's a macro and + # ignore it, unless it's TEST or TEST_F. + function_name = match_result.group(1).split()[-1] + if function_name == 'TEST' or function_name == 'TEST_F' or ( + not Match(r'[A-Z_]+$', function_name)): + starting_func = True + + if starting_func: + body_found = False + for start_linenum in range(linenum, clean_lines.NumLines()): + start_line = lines[start_linenum] + joined_line += ' ' + start_line.lstrip() + if Search(r'(;|})', start_line): # Declarations and trivial functions + body_found = True + break # ... ignore + elif Search(r'{', start_line): + body_found = True + function = Search(r'((\w|:)*)\(', line).group(1) + if Match(r'TEST', function): # Handle TEST... macros + parameter_regexp = Search(r'(\(.*\))', joined_line) + if parameter_regexp: # Ignore bad syntax + function += parameter_regexp.group(1) + else: + function += '()' + function_state.Begin(function) + break + if not body_found: + # No body for the function (or evidence of a non-function) was found. + error(filename, linenum, 'readability/fn_size', 5, + 'Lint failed to find start of function body.') + elif Match(r'^\}\s*$', line): # function end + function_state.Check(error, filename, linenum) + function_state.End() + elif not Match(r'^\s*$', line): + function_state.Count() # Count non-blank/non-comment lines. + + +_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') + + +def CheckComment(line, filename, linenum, next_line_start, error): + """Checks for common mistakes in comments. + + Args: + line: The line in question. + filename: The name of the current file. + linenum: The number of the line to check. + next_line_start: The first non-whitespace column of the next line. + error: The function to call with any errors found. + """ + commentpos = line.find('//') + if commentpos != -1: + # Check if the // may be in quotes. If so, ignore it + if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: + # Allow one space for new scopes, two spaces otherwise: + if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and + ((commentpos >= 1 and + line[commentpos-1] not in string.whitespace) or + (commentpos >= 2 and + line[commentpos-2] not in string.whitespace))): + error(filename, linenum, 'whitespace/comments', 2, + 'At least two spaces is best between code and comments') + + # Checks for common mistakes in TODO comments. + comment = line[commentpos:] + match = _RE_PATTERN_TODO.match(comment) + if match: + # One whitespace is correct; zero whitespace is handled elsewhere. + leading_whitespace = match.group(1) + if len(leading_whitespace) > 1: + error(filename, linenum, 'whitespace/todo', 2, + 'Too many spaces before TODO') + + username = match.group(2) + if not username: + error(filename, linenum, 'readability/todo', 2, + 'Missing username in TODO; it should look like ' + '"// TODO(my_username): Stuff."') + + middle_whitespace = match.group(3) + # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison + if middle_whitespace != ' ' and middle_whitespace != '': + error(filename, linenum, 'whitespace/todo', 2, + 'TODO(my_username) should be followed by a space') + + # If the comment contains an alphanumeric character, there + # should be a space somewhere between it and the // unless + # it's a /// or //! Doxygen comment. + if (Match(r'//[^ ]*\w', comment) and + not Match(r'(///|//\!)(\s+|$)', comment)): + error(filename, linenum, 'whitespace/comments', 4, + 'Should have a space between // and comment') + + +def CheckAccess(filename, clean_lines, linenum, nesting_state, error): + """Checks for improper use of DISALLOW* macros. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] # get rid of comments and strings + + matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' + r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) + if not matched: + return + if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): + if nesting_state.stack[-1].access != 'private': + error(filename, linenum, 'readability/constructors', 3, + '%s must be in the private: section' % matched.group(1)) + + else: + # Found DISALLOW* macro outside a class declaration, or perhaps it + # was used inside a function when it should have been part of the + # class declaration. We could issue a warning here, but it + # probably resulted in a compiler error already. + pass + + +def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): + """Checks for the correctness of various spacing issues in the code. + + Things we check for: spaces around operators, spaces after + if/for/while/switch, no spaces around parens in function calls, two + spaces between code and comment, don't start a block with a blank + line, don't end a function with a blank line, don't add a blank line + after public/protected/private, don't have too many blank lines in a row. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + + # Don't use "elided" lines here, otherwise we can't check commented lines. + # Don't want to use "raw" either, because we don't want to check inside C++11 + # raw strings, + raw = clean_lines.lines_without_raw_strings + line = raw[linenum] + + # Before nixing comments, check if the line is blank for no good + # reason. This includes the first line after a block is opened, and + # blank lines at the end of a function (ie, right before a line like '}' + # + # Skip all the blank line checks if we are immediately inside a + # namespace body. In other words, don't issue blank line warnings + # for this block: + # namespace { + # + # } + # + # A warning about missing end of namespace comments will be issued instead. + # + # Also skip blank line checks for 'extern "C"' blocks, which are formatted + # like namespaces. + if (IsBlankLine(line) and + not nesting_state.InNamespaceBody() and + not nesting_state.InExternC()): + elided = clean_lines.elided + prev_line = elided[linenum - 1] + prevbrace = prev_line.rfind('{') + # TODO(unknown): Don't complain if line before blank line, and line after, + # both start with alnums and are indented the same amount. + # This ignores whitespace at the start of a namespace block + # because those are not usually indented. + if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: + # OK, we have a blank line at the start of a code block. Before we + # complain, we check if it is an exception to the rule: The previous + # non-empty line has the parameters of a function header that are indented + # 4 spaces (because they did not fit in a 80 column line when placed on + # the same line as the function name). We also check for the case where + # the previous line is indented 6 spaces, which may happen when the + # initializers of a constructor do not fit into a 80 column line. + exception = False + if Match(r' {6}\w', prev_line): # Initializer list? + # We are looking for the opening column of initializer list, which + # should be indented 4 spaces to cause 6 space indentation afterwards. + search_position = linenum-2 + while (search_position >= 0 + and Match(r' {6}\w', elided[search_position])): + search_position -= 1 + exception = (search_position >= 0 + and elided[search_position][:5] == ' :') + else: + # Search for the function arguments or an initializer list. We use a + # simple heuristic here: If the line is indented 4 spaces; and we have a + # closing paren, without the opening paren, followed by an opening brace + # or colon (for initializer lists) we assume that it is the last line of + # a function header. If we have a colon indented 4 spaces, it is an + # initializer list. + exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', + prev_line) + or Match(r' {4}:', prev_line)) + + if not exception: + error(filename, linenum, 'whitespace/blank_line', 2, + 'Redundant blank line at the start of a code block ' + 'should be deleted.') + # Ignore blank lines at the end of a block in a long if-else + # chain, like this: + # if (condition1) { + # // Something followed by a blank line + # + # } else if (condition2) { + # // Something else + # } + if linenum + 1 < clean_lines.NumLines(): + next_line = raw[linenum + 1] + if (next_line + and Match(r'\s*}', next_line) + and next_line.find('} else ') == -1): + error(filename, linenum, 'whitespace/blank_line', 3, + 'Redundant blank line at the end of a code block ' + 'should be deleted.') + + matched = Match(r'\s*(public|protected|private):', prev_line) + if matched: + error(filename, linenum, 'whitespace/blank_line', 3, + 'Do not leave a blank line after "%s:"' % matched.group(1)) + + # Next, check comments + next_line_start = 0 + if linenum + 1 < clean_lines.NumLines(): + next_line = raw[linenum + 1] + next_line_start = len(next_line) - len(next_line.lstrip()) + CheckComment(line, filename, linenum, next_line_start, error) + + # get rid of comments and strings + line = clean_lines.elided[linenum] + + # You shouldn't have spaces before your brackets, except maybe after + # 'delete []' or 'return []() {};' + if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): + error(filename, linenum, 'whitespace/braces', 5, + 'Extra space before [') + + # In range-based for, we wanted spaces before and after the colon, but + # not around "::" tokens that might appear. + if (Search(r'for *\(.*[^:]:[^: ]', line) or + Search(r'for *\(.*[^: ]:[^:]', line)): + error(filename, linenum, 'whitespace/forcolon', 2, + 'Missing space around colon in range-based for loop') + + +def CheckOperatorSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing around operators. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Don't try to do spacing checks for operator methods. Do this by + # replacing the troublesome characters with something else, + # preserving column position for all other characters. + # + # The replacement is done repeatedly to avoid false positives from + # operators that call operators. + while True: + match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) + if match: + line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) + else: + break + + # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". + # Otherwise not. Note we only check for non-spaces on *both* sides; + # sometimes people put non-spaces on one side when aligning ='s among + # many lines (not that this is behavior that I approve of...) + if ((Search(r'[\w.]=', line) or + Search(r'=[\w.]', line)) + and not Search(r'\b(if|while|for) ', line) + # Operators taken from [lex.operators] in C++11 standard. + and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) + and not Search(r'operator=', line)): + error(filename, linenum, 'whitespace/operators', 4, + 'Missing spaces around =') + + # It's ok not to have spaces around binary operators like + - * /, but if + # there's too little whitespace, we get concerned. It's hard to tell, + # though, so we punt on this one for now. TODO. + + # You should always have whitespace around binary operators. + # + # Check <= and >= first to avoid false positives with < and >, then + # check non-include lines for spacing around < and >. + # + # If the operator is followed by a comma, assume it's be used in a + # macro context and don't do any checks. This avoids false + # positives. + # + # Note that && is not included here. This is because there are too + # many false positives due to RValue references. + match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around %s' % match.group(1)) + elif not Match(r'#.*include', line): + # Look for < that is not surrounded by spaces. This is only + # triggered if both sides are missing spaces, even though + # technically should should flag if at least one side is missing a + # space. This is done to avoid some false positives with shifts. + match = Match(r'^(.*[^\s<])<[^\s=<,]', line) + if match: + (_, _, end_pos) = CloseExpression( + clean_lines, linenum, len(match.group(1))) + if end_pos <= -1: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around <') + + # Look for > that is not surrounded by spaces. Similar to the + # above, we only trigger if both sides are missing spaces to avoid + # false positives with shifts. + match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) + if match: + (_, _, start_pos) = ReverseCloseExpression( + clean_lines, linenum, len(match.group(1))) + if start_pos <= -1: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around >') + + # We allow no-spaces around << when used like this: 10<<20, but + # not otherwise (particularly, not when used as streams) + # + # We also allow operators following an opening parenthesis, since + # those tend to be macros that deal with operators. + match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line) + if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and + not (match.group(1) == 'operator' and match.group(2) == ';')): + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around <<') + + # We allow no-spaces around >> for almost anything. This is because + # C++11 allows ">>" to close nested templates, which accounts for + # most cases when ">>" is not followed by a space. + # + # We still warn on ">>" followed by alpha character, because that is + # likely due to ">>" being used for right shifts, e.g.: + # value >> alpha + # + # When ">>" is used to close templates, the alphanumeric letter that + # follows would be part of an identifier, and there should still be + # a space separating the template type and the identifier. + # type> alpha + match = Search(r'>>[a-zA-Z_]', line) + if match: + error(filename, linenum, 'whitespace/operators', 3, + 'Missing spaces around >>') + + # There shouldn't be space around unary operators + match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) + if match: + error(filename, linenum, 'whitespace/operators', 4, + 'Extra space for operator %s' % match.group(1)) + + +def CheckParenthesisSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing around parentheses. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # No spaces after an if, while, switch, or for + match = Search(r' (if\(|for\(|while\(|switch\()', line) + if match: + error(filename, linenum, 'whitespace/parens', 5, + 'Missing space before ( in %s' % match.group(1)) + + # For if/for/while/switch, the left and right parens should be + # consistent about how many spaces are inside the parens, and + # there should either be zero or one spaces inside the parens. + # We don't want: "if ( foo)" or "if ( foo )". + # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. + match = Search(r'\b(if|for|while|switch)\s*' + r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', + line) + if match: + if len(match.group(2)) != len(match.group(4)): + if not (match.group(3) == ';' and + len(match.group(2)) == 1 + len(match.group(4)) or + not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): + error(filename, linenum, 'whitespace/parens', 5, + 'Mismatching spaces inside () in %s' % match.group(1)) + if len(match.group(2)) not in [0, 1]: + error(filename, linenum, 'whitespace/parens', 5, + 'Should have zero or one spaces inside ( and ) in %s' % + match.group(1)) + + +def CheckCommaSpacing(filename, clean_lines, linenum, error): + """Checks for horizontal spacing near commas and semicolons. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + raw = clean_lines.lines_without_raw_strings + line = clean_lines.elided[linenum] + + # You should always have a space after a comma (either as fn arg or operator) + # + # This does not apply when the non-space character following the + # comma is another comma, since the only time when that happens is + # for empty macro arguments. + # + # We run this check in two passes: first pass on elided lines to + # verify that lines contain missing whitespaces, second pass on raw + # lines to confirm that those missing whitespaces are not due to + # elided comments. + if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and + Search(r',[^,\s]', raw[linenum])): + error(filename, linenum, 'whitespace/comma', 3, + 'Missing space after ,') + + # You should always have a space after a semicolon + # except for few corner cases + # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more + # space after ; + if Search(r';[^\s};\\)/]', line): + error(filename, linenum, 'whitespace/semicolon', 3, + 'Missing space after ;') + + +def _IsType(clean_lines, nesting_state, expr): + """Check if expression looks like a type name, returns true if so. + + Args: + clean_lines: A CleansedLines instance containing the file. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + expr: The expression to check. + Returns: + True, if token looks like a type. + """ + # Keep only the last token in the expression + last_word = Match(r'^.*(\b\S+)$', expr) + if last_word: + token = last_word.group(1) + else: + token = expr + + # Match native types and stdint types + if _TYPES.match(token): + return True + + # Try a bit harder to match templated types. Walk up the nesting + # stack until we find something that resembles a typename + # declaration for what we are looking for. + typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) + + r'\b') + block_index = len(nesting_state.stack) - 1 + while block_index >= 0: + if isinstance(nesting_state.stack[block_index], _NamespaceInfo): + return False + + # Found where the opening brace is. We want to scan from this + # line up to the beginning of the function, minus a few lines. + # template + # class C + # : public ... { // start scanning here + last_line = nesting_state.stack[block_index].starting_linenum + + next_block_start = 0 + if block_index > 0: + next_block_start = nesting_state.stack[block_index - 1].starting_linenum + first_line = last_line + while first_line >= next_block_start: + if clean_lines.elided[first_line].find('template') >= 0: + break + first_line -= 1 + if first_line < next_block_start: + # Didn't find any "template" keyword before reaching the next block, + # there are probably no template things to check for this block + block_index -= 1 + continue + + # Look for typename in the specified range + for i in xrange(first_line, last_line + 1, 1): + if Search(typename_pattern, clean_lines.elided[i]): + return True + block_index -= 1 + + return False + + +def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): + """Checks for horizontal spacing near commas. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Except after an opening paren, or after another opening brace (in case of + # an initializer list, for instance), you should have spaces before your + # braces when they are delimiting blocks, classes, namespaces etc. + # And since you should never have braces at the beginning of a line, + # this is an easy test. Except that braces used for initialization don't + # follow the same rule; we often don't want spaces before those. + match = Match(r'^(.*[^ ({>]){', line) + + if match: + # Try a bit harder to check for brace initialization. This + # happens in one of the following forms: + # Constructor() : initializer_list_{} { ... } + # Constructor{}.MemberFunction() + # Type variable{}; + # FunctionCall(type{}, ...); + # LastArgument(..., type{}); + # LOG(INFO) << type{} << " ..."; + # map_of_type[{...}] = ...; + # ternary = expr ? new type{} : nullptr; + # OuterTemplate{}> + # + # We check for the character following the closing brace, and + # silence the warning if it's one of those listed above, i.e. + # "{.;,)<>]:". + # + # To account for nested initializer list, we allow any number of + # closing braces up to "{;,)<". We can't simply silence the + # warning on first sight of closing brace, because that would + # cause false negatives for things that are not initializer lists. + # Silence this: But not this: + # Outer{ if (...) { + # Inner{...} if (...){ // Missing space before { + # }; } + # + # There is a false negative with this approach if people inserted + # spurious semicolons, e.g. "if (cond){};", but we will catch the + # spurious semicolon with a separate check. + leading_text = match.group(1) + (endline, endlinenum, endpos) = CloseExpression( + clean_lines, linenum, len(match.group(1))) + trailing_text = '' + if endpos > -1: + trailing_text = endline[endpos:] + for offset in xrange(endlinenum + 1, + min(endlinenum + 3, clean_lines.NumLines() - 1)): + trailing_text += clean_lines.elided[offset] + # We also suppress warnings for `uint64_t{expression}` etc., as the style + # guide recommends brace initialization for integral types to avoid + # overflow/truncation. + if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text) + and not _IsType(clean_lines, nesting_state, leading_text)): + error(filename, linenum, 'whitespace/braces', 5, + 'Missing space before {') + + # Make sure '} else {' has spaces. + if Search(r'}else', line): + error(filename, linenum, 'whitespace/braces', 5, + 'Missing space before else') + + # You shouldn't have a space before a semicolon at the end of the line. + # There's a special case for "for" since the style guide allows space before + # the semicolon there. + if Search(r':\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Semicolon defining empty statement. Use {} instead.') + elif Search(r'^\s*;\s*$', line): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Line contains only semicolon. If this should be an empty statement, ' + 'use {} instead.') + elif (Search(r'\s+;\s*$', line) and + not Search(r'\bfor\b', line)): + error(filename, linenum, 'whitespace/semicolon', 5, + 'Extra space before last semicolon. If this should be an empty ' + 'statement, use {} instead.') + + +def IsDecltype(clean_lines, linenum, column): + """Check if the token ending on (linenum, column) is decltype(). + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: the number of the line to check. + column: end column of the token to check. + Returns: + True if this token is decltype() expression, False otherwise. + """ + (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) + if start_col < 0: + return False + if Search(r'\bdecltype\s*$', text[0:start_col]): + return True + return False + +def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): + """Checks for additional blank line issues related to sections. + + Currently the only thing checked here is blank line before protected/private. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + class_info: A _ClassInfo objects. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Skip checks if the class is small, where small means 25 lines or less. + # 25 lines seems like a good cutoff since that's the usual height of + # terminals, and any class that can't fit in one screen can't really + # be considered "small". + # + # Also skip checks if we are on the first line. This accounts for + # classes that look like + # class Foo { public: ... }; + # + # If we didn't find the end of the class, last_line would be zero, + # and the check will be skipped by the first condition. + if (class_info.last_line - class_info.starting_linenum <= 24 or + linenum <= class_info.starting_linenum): + return + + matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) + if matched: + # Issue warning if the line before public/protected/private was + # not a blank line, but don't do this if the previous line contains + # "class" or "struct". This can happen two ways: + # - We are at the beginning of the class. + # - We are forward-declaring an inner class that is semantically + # private, but needed to be public for implementation reasons. + # Also ignores cases where the previous line ends with a backslash as can be + # common when defining classes in C macros. + prev_line = clean_lines.lines[linenum - 1] + if (not IsBlankLine(prev_line) and + not Search(r'\b(class|struct)\b', prev_line) and + not Search(r'\\$', prev_line)): + # Try a bit harder to find the beginning of the class. This is to + # account for multi-line base-specifier lists, e.g.: + # class Derived + # : public Base { + end_class_head = class_info.starting_linenum + for i in range(class_info.starting_linenum, linenum): + if Search(r'\{\s*$', clean_lines.lines[i]): + end_class_head = i + break + if end_class_head < linenum - 1: + error(filename, linenum, 'whitespace/blank_line', 3, + '"%s:" should be preceded by a blank line' % matched.group(1)) + + +def GetPreviousNonBlankLine(clean_lines, linenum): + """Return the most recent non-blank line and its line number. + + Args: + clean_lines: A CleansedLines instance containing the file contents. + linenum: The number of the line to check. + + Returns: + A tuple with two elements. The first element is the contents of the last + non-blank line before the current line, or the empty string if this is the + first non-blank line. The second is the line number of that line, or -1 + if this is the first non-blank line. + """ + + prevlinenum = linenum - 1 + while prevlinenum >= 0: + prevline = clean_lines.elided[prevlinenum] + if not IsBlankLine(prevline): # if not a blank line... + return (prevline, prevlinenum) + prevlinenum -= 1 + return ('', -1) + + +def CheckBraces(filename, clean_lines, linenum, error): + """Looks for misplaced braces (e.g. at the end of line). + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[linenum] # get rid of comments and strings + + if Match(r'\s*{\s*$', line): + # We allow an open brace to start a line in the case where someone is using + # braces in a block to explicitly create a new scope, which is commonly used + # to control the lifetime of stack-allocated variables. Braces are also + # used for brace initializers inside function calls. We don't detect this + # perfectly: we just don't complain if the last non-whitespace character on + # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the + # previous line starts a preprocessor block. We also allow a brace on the + # following line if it is part of an array initialization and would not fit + # within the 80 character limit of the preceding line. + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if (not Search(r'[,;:}{(]\s*$', prevline) and + not Match(r'\s*#', prevline) and + not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)): + error(filename, linenum, 'whitespace/braces', 4, + '{ should almost always be at the end of the previous line') + + # An else clause should be on the same line as the preceding closing brace. + if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if Match(r'\s*}\s*$', prevline): + error(filename, linenum, 'whitespace/newline', 4, + 'An else should appear on the same line as the preceding }') + + # If braces come on one side of an else, they should be on both. + # However, we have to worry about "else if" that spans multiple lines! + if Search(r'else if\s*\(', line): # could be multi-line if + brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) + # find the ( after the if + pos = line.find('else if') + pos = line.find('(', pos) + if pos > 0: + (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) + brace_on_right = endline[endpos:].find('{') != -1 + if brace_on_left != brace_on_right: # must be brace after if + error(filename, linenum, 'readability/braces', 5, + 'If an else has a brace on one side, it should have it on both') + elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): + error(filename, linenum, 'readability/braces', 5, + 'If an else has a brace on one side, it should have it on both') + + # Likewise, an else should never have the else clause on the same line + if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): + error(filename, linenum, 'whitespace/newline', 4, + 'Else clause should never be on same line as else (use 2 lines)') + + # In the same way, a do/while should never be on one line + if Match(r'\s*do [^\s{]', line): + error(filename, linenum, 'whitespace/newline', 4, + 'do/while clauses should not be on a single line') + + # Check single-line if/else bodies. The style guide says 'curly braces are not + # required for single-line statements'. We additionally allow multi-line, + # single statements, but we reject anything with more than one semicolon in + # it. This means that the first semicolon after the if should be at the end of + # its line, and the line after that should have an indent level equal to or + # lower than the if. We also check for ambiguous if/else nesting without + # braces. + if_else_match = Search(r'\b(if\s*\(|else\b)', line) + if if_else_match and not Match(r'\s*#', line): + if_indent = GetIndentLevel(line) + endline, endlinenum, endpos = line, linenum, if_else_match.end() + if_match = Search(r'\bif\s*\(', line) + if if_match: + # This could be a multiline if condition, so find the end first. + pos = if_match.end() - 1 + (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) + # Check for an opening brace, either directly after the if or on the next + # line. If found, this isn't a single-statement conditional. + if (not Match(r'\s*{', endline[endpos:]) + and not (Match(r'\s*$', endline[endpos:]) + and endlinenum < (len(clean_lines.elided) - 1) + and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): + while (endlinenum < len(clean_lines.elided) + and ';' not in clean_lines.elided[endlinenum][endpos:]): + endlinenum += 1 + endpos = 0 + if endlinenum < len(clean_lines.elided): + endline = clean_lines.elided[endlinenum] + # We allow a mix of whitespace and closing braces (e.g. for one-liner + # methods) and a single \ after the semicolon (for macros) + endpos = endline.find(';') + if not Match(r';[\s}]*(\\?)$', endline[endpos:]): + # Semicolon isn't the last character, there's something trailing. + # Output a warning if the semicolon is not contained inside + # a lambda expression. + if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', + endline): + error(filename, linenum, 'readability/braces', 4, + 'If/else bodies with multiple statements require braces') + elif endlinenum < len(clean_lines.elided) - 1: + # Make sure the next line is dedented + next_line = clean_lines.elided[endlinenum + 1] + next_indent = GetIndentLevel(next_line) + # With ambiguous nested if statements, this will error out on the + # if that *doesn't* match the else, regardless of whether it's the + # inner one or outer one. + if (if_match and Match(r'\s*else\b', next_line) + and next_indent != if_indent): + error(filename, linenum, 'readability/braces', 4, + 'Else clause should be indented at the same level as if. ' + 'Ambiguous nested if/else chains require braces.') + elif next_indent > if_indent: + error(filename, linenum, 'readability/braces', 4, + 'If/else bodies with multiple statements require braces') + + +def CheckTrailingSemicolon(filename, clean_lines, linenum, error): + """Looks for redundant trailing semicolon. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + line = clean_lines.elided[linenum] + + # Block bodies should not be followed by a semicolon. Due to C++11 + # brace initialization, there are more places where semicolons are + # required than not, so we use a whitelist approach to check these + # rather than a blacklist. These are the places where "};" should + # be replaced by just "}": + # 1. Some flavor of block following closing parenthesis: + # for (;;) {}; + # while (...) {}; + # switch (...) {}; + # Function(...) {}; + # if (...) {}; + # if (...) else if (...) {}; + # + # 2. else block: + # if (...) else {}; + # + # 3. const member function: + # Function(...) const {}; + # + # 4. Block following some statement: + # x = 42; + # {}; + # + # 5. Block at the beginning of a function: + # Function(...) { + # {}; + # } + # + # Note that naively checking for the preceding "{" will also match + # braces inside multi-dimensional arrays, but this is fine since + # that expression will not contain semicolons. + # + # 6. Block following another block: + # while (true) {} + # {}; + # + # 7. End of namespaces: + # namespace {}; + # + # These semicolons seems far more common than other kinds of + # redundant semicolons, possibly due to people converting classes + # to namespaces. For now we do not warn for this case. + # + # Try matching case 1 first. + match = Match(r'^(.*\)\s*)\{', line) + if match: + # Matched closing parenthesis (case 1). Check the token before the + # matching opening parenthesis, and don't warn if it looks like a + # macro. This avoids these false positives: + # - macro that defines a base class + # - multi-line macro that defines a base class + # - macro that defines the whole class-head + # + # But we still issue warnings for macros that we know are safe to + # warn, specifically: + # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P + # - TYPED_TEST + # - INTERFACE_DEF + # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: + # + # We implement a whitelist of safe macros instead of a blacklist of + # unsafe macros, even though the latter appears less frequently in + # google code and would have been easier to implement. This is because + # the downside for getting the whitelist wrong means some extra + # semicolons, while the downside for getting the blacklist wrong + # would result in compile errors. + # + # In addition to macros, we also don't want to warn on + # - Compound literals + # - Lambdas + # - alignas specifier with anonymous structs + # - decltype + closing_brace_pos = match.group(1).rfind(')') + opening_parenthesis = ReverseCloseExpression( + clean_lines, linenum, closing_brace_pos) + if opening_parenthesis[2] > -1: + line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] + macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix) + func = Match(r'^(.*\])\s*$', line_prefix) + if ((macro and + macro.group(1) not in ( + 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', + 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', + 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or + (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or + Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or + Search(r'\bdecltype$', line_prefix) or + Search(r'\s+=\s*$', line_prefix)): + match = None + if (match and + opening_parenthesis[1] > 1 and + Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): + # Multi-line lambda-expression + match = None + + else: + # Try matching cases 2-3. + match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) + if not match: + # Try matching cases 4-6. These are always matched on separate lines. + # + # Note that we can't simply concatenate the previous line to the + # current line and do a single match, otherwise we may output + # duplicate warnings for the blank line case: + # if (cond) { + # // blank line + # } + prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] + if prevline and Search(r'[;{}]\s*$', prevline): + match = Match(r'^(\s*)\{', line) + + # Check matching closing brace + if match: + (endline, endlinenum, endpos) = CloseExpression( + clean_lines, linenum, len(match.group(1))) + if endpos > -1 and Match(r'^\s*;', endline[endpos:]): + # Current {} pair is eligible for semicolon check, and we have found + # the redundant semicolon, output warning here. + # + # Note: because we are scanning forward for opening braces, and + # outputting warnings for the matching closing brace, if there are + # nested blocks with trailing semicolons, we will get the error + # messages in reversed order. + + # We need to check the line forward for NOLINT + raw_lines = clean_lines.raw_lines + ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1, + error) + ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, + error) + + error(filename, endlinenum, 'readability/braces', 4, + "You don't need a ; after a }") + + +def CheckEmptyBlockBody(filename, clean_lines, linenum, error): + """Look for empty loop/conditional body with only a single semicolon. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + # Search for loop keywords at the beginning of the line. Because only + # whitespaces are allowed before the keywords, this will also ignore most + # do-while-loops, since those lines should start with closing brace. + # + # We also check "if" blocks here, since an empty conditional block + # is likely an error. + line = clean_lines.elided[linenum] + matched = Match(r'\s*(for|while|if)\s*\(', line) + if matched: + # Find the end of the conditional expression. + (end_line, end_linenum, end_pos) = CloseExpression( + clean_lines, linenum, line.find('(')) + + # Output warning if what follows the condition expression is a semicolon. + # No warning for all other cases, including whitespace or newline, since we + # have a separate check for semicolons preceded by whitespace. + if end_pos >= 0 and Match(r';', end_line[end_pos:]): + if matched.group(1) == 'if': + error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, + 'Empty conditional bodies should use {}') + else: + error(filename, end_linenum, 'whitespace/empty_loop_body', 5, + 'Empty loop bodies should use {} or continue') + + # Check for if statements that have completely empty bodies (no comments) + # and no else clauses. + if end_pos >= 0 and matched.group(1) == 'if': + # Find the position of the opening { for the if statement. + # Return without logging an error if it has no brackets. + opening_linenum = end_linenum + opening_line_fragment = end_line[end_pos:] + # Loop until EOF or find anything that's not whitespace or opening {. + while not Search(r'^\s*\{', opening_line_fragment): + if Search(r'^(?!\s*$)', opening_line_fragment): + # Conditional has no brackets. + return + opening_linenum += 1 + if opening_linenum == len(clean_lines.elided): + # Couldn't find conditional's opening { or any code before EOF. + return + opening_line_fragment = clean_lines.elided[opening_linenum] + # Set opening_line (opening_line_fragment may not be entire opening line). + opening_line = clean_lines.elided[opening_linenum] + + # Find the position of the closing }. + opening_pos = opening_line_fragment.find('{') + if opening_linenum == end_linenum: + # We need to make opening_pos relative to the start of the entire line. + opening_pos += end_pos + (closing_line, closing_linenum, closing_pos) = CloseExpression( + clean_lines, opening_linenum, opening_pos) + if closing_pos < 0: + return + + # Now construct the body of the conditional. This consists of the portion + # of the opening line after the {, all lines until the closing line, + # and the portion of the closing line before the }. + if (clean_lines.raw_lines[opening_linenum] != + CleanseComments(clean_lines.raw_lines[opening_linenum])): + # Opening line ends with a comment, so conditional isn't empty. + return + if closing_linenum > opening_linenum: + # Opening line after the {. Ignore comments here since we checked above. + bodylist = list(opening_line[opening_pos+1:]) + # All lines until closing line, excluding closing line, with comments. + bodylist.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum]) + # Closing line before the }. Won't (and can't) have comments. + bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1]) + body = '\n'.join(bodylist) + else: + # If statement has brackets and fits on a single line. + body = opening_line[opening_pos+1:closing_pos-1] + + # Check if the body is empty + if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body): + return + # The body is empty. Now make sure there's not an else clause. + current_linenum = closing_linenum + current_line_fragment = closing_line[closing_pos:] + # Loop until EOF or find anything that's not whitespace or else clause. + while Search(r'^\s*$|^(?=\s*else)', current_line_fragment): + if Search(r'^(?=\s*else)', current_line_fragment): + # Found an else clause, so don't log an error. + return + current_linenum += 1 + if current_linenum == len(clean_lines.elided): + break + current_line_fragment = clean_lines.elided[current_linenum] + + # The body is empty and there's no else clause until EOF or other code. + error(filename, end_linenum, 'whitespace/empty_if_body', 4, + ('If statement had no body and no else clause')) + + +def FindCheckMacro(line): + """Find a replaceable CHECK-like macro. + + Args: + line: line to search on. + Returns: + (macro name, start position), or (None, -1) if no replaceable + macro is found. + """ + for macro in _CHECK_MACROS: + i = line.find(macro) + if i >= 0: + # Find opening parenthesis. Do a regular expression match here + # to make sure that we are matching the expected CHECK macro, as + # opposed to some other macro that happens to contain the CHECK + # substring. + matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) + if not matched: + continue + return (macro, len(matched.group(1))) + return (None, -1) + + +def CheckCheck(filename, clean_lines, linenum, error): + """Checks the use of CHECK and EXPECT macros. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + + # Decide the set of replacement macros that should be suggested + lines = clean_lines.elided + (check_macro, start_pos) = FindCheckMacro(lines[linenum]) + if not check_macro: + return + + # Find end of the boolean expression by matching parentheses + (last_line, end_line, end_pos) = CloseExpression( + clean_lines, linenum, start_pos) + if end_pos < 0: + return + + # If the check macro is followed by something other than a + # semicolon, assume users will log their own custom error messages + # and don't suggest any replacements. + if not Match(r'\s*;', last_line[end_pos:]): + return + + if linenum == end_line: + expression = lines[linenum][start_pos + 1:end_pos - 1] + else: + expression = lines[linenum][start_pos + 1:] + for i in xrange(linenum + 1, end_line): + expression += lines[i] + expression += last_line[0:end_pos - 1] + + # Parse expression so that we can take parentheses into account. + # This avoids false positives for inputs like "CHECK((a < 4) == b)", + # which is not replaceable by CHECK_LE. + lhs = '' + rhs = '' + operator = None + while expression: + matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' + r'==|!=|>=|>|<=|<|\()(.*)$', expression) + if matched: + token = matched.group(1) + if token == '(': + # Parenthesized operand + expression = matched.group(2) + (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) + if end < 0: + return # Unmatched parenthesis + lhs += '(' + expression[0:end] + expression = expression[end:] + elif token in ('&&', '||'): + # Logical and/or operators. This means the expression + # contains more than one term, for example: + # CHECK(42 < a && a < b); + # + # These are not replaceable with CHECK_LE, so bail out early. + return + elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): + # Non-relational operator + lhs += token + expression = matched.group(2) + else: + # Relational operator + operator = token + rhs = matched.group(2) + break + else: + # Unparenthesized operand. Instead of appending to lhs one character + # at a time, we do another regular expression match to consume several + # characters at once if possible. Trivial benchmark shows that this + # is more efficient when the operands are longer than a single + # character, which is generally the case. + matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) + if not matched: + matched = Match(r'^(\s*\S)(.*)$', expression) + if not matched: + break + lhs += matched.group(1) + expression = matched.group(2) + + # Only apply checks if we got all parts of the boolean expression + if not (lhs and operator and rhs): + return + + # Check that rhs do not contain logical operators. We already know + # that lhs is fine since the loop above parses out && and ||. + if rhs.find('&&') > -1 or rhs.find('||') > -1: + return + + # At least one of the operands must be a constant literal. This is + # to avoid suggesting replacements for unprintable things like + # CHECK(variable != iterator) + # + # The following pattern matches decimal, hex integers, strings, and + # characters (in that order). + lhs = lhs.strip() + rhs = rhs.strip() + match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' + if Match(match_constant, lhs) or Match(match_constant, rhs): + # Note: since we know both lhs and rhs, we can provide a more + # descriptive error message like: + # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) + # Instead of: + # Consider using CHECK_EQ instead of CHECK(a == b) + # + # We are still keeping the less descriptive message because if lhs + # or rhs gets long, the error message might become unreadable. + error(filename, linenum, 'readability/check', 2, + 'Consider using %s instead of %s(a %s b)' % ( + _CHECK_REPLACEMENT[check_macro][operator], + check_macro, operator)) + + +def CheckAltTokens(filename, clean_lines, linenum, error): + """Check alternative keywords being used in boolean expressions. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Avoid preprocessor lines + if Match(r'^\s*#', line): + return + + # Last ditch effort to avoid multi-line comments. This will not help + # if the comment started before the current line or ended after the + # current line, but it catches most of the false positives. At least, + # it provides a way to workaround this warning for people who use + # multi-line comments in preprocessor macros. + # + # TODO(unknown): remove this once cpplint has better support for + # multi-line comments. + if line.find('/*') >= 0 or line.find('*/') >= 0: + return + + for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): + error(filename, linenum, 'readability/alt_tokens', 2, + 'Use operator %s instead of %s' % ( + _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) + + +def GetLineWidth(line): + """Determines the width of the line in column positions. + + Args: + line: A string, which may be a Unicode string. + + Returns: + The width of the line in column positions, accounting for Unicode + combining characters and wide characters. + """ + if isinstance(line, unicode): + width = 0 + for uc in unicodedata.normalize('NFC', line): + if unicodedata.east_asian_width(uc) in ('W', 'F'): + width += 2 + elif not unicodedata.combining(uc): + width += 1 + return width + else: + return len(line) + + +def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, + error): + """Checks rules from the 'C++ style rules' section of cppguide.html. + + Most of these rules are hard to test (naming, comment style), but we + do what we can. In particular we check for 2-space indents, line lengths, + tab usage, spaces inside code, etc. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + + # Don't use "elided" lines here, otherwise we can't check commented lines. + # Don't want to use "raw" either, because we don't want to check inside C++11 + # raw strings, + raw_lines = clean_lines.lines_without_raw_strings + line = raw_lines[linenum] + prev = raw_lines[linenum - 1] if linenum > 0 else '' + + if line.find('\t') != -1: + error(filename, linenum, 'whitespace/tab', 1, + 'Tab found; better to use spaces') + + # One or three blank spaces at the beginning of the line is weird; it's + # hard to reconcile that with 2-space indents. + # NOTE: here are the conditions rob pike used for his tests. Mine aren't + # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces + # if(RLENGTH > 20) complain = 0; + # if(match($0, " +(error|private|public|protected):")) complain = 0; + # if(match(prev, "&& *$")) complain = 0; + # if(match(prev, "\\|\\| *$")) complain = 0; + # if(match(prev, "[\",=><] *$")) complain = 0; + # if(match($0, " <<")) complain = 0; + # if(match(prev, " +for \\(")) complain = 0; + # if(prevodd && match(prevprev, " +for \\(")) complain = 0; + scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' + classinfo = nesting_state.InnermostClass() + initial_spaces = 0 + cleansed_line = clean_lines.elided[linenum] + while initial_spaces < len(line) and line[initial_spaces] == ' ': + initial_spaces += 1 + # There are certain situations we allow one space, notably for + # section labels, and also lines containing multi-line raw strings. + # We also don't check for lines that look like continuation lines + # (of lines ending in double quotes, commas, equals, or angle brackets) + # because the rules for how to indent those are non-trivial. + if (not Search(r'[",=><] *$', prev) and + (initial_spaces == 1 or initial_spaces == 3) and + not Match(scope_or_label_pattern, cleansed_line) and + not (clean_lines.raw_lines[linenum] != line and + Match(r'^\s*""', line))): + error(filename, linenum, 'whitespace/indent', 3, + 'Weird number of spaces at line-start. ' + 'Are you using a 2-space indent?') + + if line and line[-1].isspace(): + error(filename, linenum, 'whitespace/end_of_line', 4, + 'Line ends in whitespace. Consider deleting these extra spaces.') + + # Check if the line is a header guard. + is_header_guard = False + if file_extension in GetHeaderExtensions(): + cppvar = GetHeaderGuardCPPVariable(filename) + if (line.startswith('#ifndef %s' % cppvar) or + line.startswith('#define %s' % cppvar) or + line.startswith('#endif // %s' % cppvar)): + is_header_guard = True + # #include lines and header guards can be long, since there's no clean way to + # split them. + # + # URLs can be long too. It's possible to split these, but it makes them + # harder to cut&paste. + # + # The "$Id:...$" comment may also get very long without it being the + # developers fault. + # + # Doxygen documentation copying can get pretty long when using an overloaded + # function declaration + if (not line.startswith('#include') and not is_header_guard and + not Match(r'^\s*//.*http(s?)://\S*$', line) and + not Match(r'^\s*//\s*[^\s]*$', line) and + not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and + not Match(r'^\s*/// [@\\](copydoc|copydetails|copybrief) .*$', line)): + line_width = GetLineWidth(line) + if line_width > _line_length: + error(filename, linenum, 'whitespace/line_length', 2, + 'Lines should be <= %i characters long' % _line_length) + + if (cleansed_line.count(';') > 1 and + # allow simple single line lambdas + not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}\n\r]*\}', + line) and + # for loops are allowed two ;'s (and may run over two lines). + cleansed_line.find('for') == -1 and + (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or + GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and + # It's ok to have many commands in a switch case that fits in 1 line + not ((cleansed_line.find('case ') != -1 or + cleansed_line.find('default:') != -1) and + cleansed_line.find('break;') != -1)): + error(filename, linenum, 'whitespace/newline', 0, + 'More than one command on the same line') + + # Some more style checks + CheckBraces(filename, clean_lines, linenum, error) + CheckTrailingSemicolon(filename, clean_lines, linenum, error) + CheckEmptyBlockBody(filename, clean_lines, linenum, error) + CheckAccess(filename, clean_lines, linenum, nesting_state, error) + CheckSpacing(filename, clean_lines, linenum, nesting_state, error) + CheckOperatorSpacing(filename, clean_lines, linenum, error) + CheckParenthesisSpacing(filename, clean_lines, linenum, error) + CheckCommaSpacing(filename, clean_lines, linenum, error) + CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error) + CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) + CheckCheck(filename, clean_lines, linenum, error) + CheckAltTokens(filename, clean_lines, linenum, error) + classinfo = nesting_state.InnermostClass() + if classinfo: + CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) + + +_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') +# Matches the first component of a filename delimited by -s and _s. That is: +# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' +# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' +_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') + + +def _DropCommonSuffixes(filename): + """Drops common suffixes like _test.cc or -inl.h from filename. + + For example: + >>> _DropCommonSuffixes('foo/foo-inl.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/bar/foo.cc') + 'foo/bar/foo' + >>> _DropCommonSuffixes('foo/foo_internal.h') + 'foo/foo' + >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') + 'foo/foo_unusualinternal' + + Args: + filename: The input filename. + + Returns: + The filename with the common suffix removed. + """ + for suffix in itertools.chain( + ('%s.%s' % (test_suffix.lstrip('_'), ext) + for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())), + ('%s.%s' % (suffix, ext) + for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))): + if (filename.endswith(suffix) and len(filename) > len(suffix) and + filename[-len(suffix) - 1] in ('-', '_')): + return filename[:-len(suffix) - 1] + return os.path.splitext(filename)[0] + + +def _ClassifyInclude(fileinfo, include, is_system): + """Figures out what kind of header 'include' is. + + Args: + fileinfo: The current file cpplint is running over. A FileInfo instance. + include: The path to a #included file. + is_system: True if the #include used <> rather than "". + + Returns: + One of the _XXX_HEADER constants. + + For example: + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) + _C_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) + _CPP_SYS_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) + _LIKELY_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), + ... 'bar/foo_other_ext.h', False) + _POSSIBLE_MY_HEADER + >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) + _OTHER_HEADER + """ + # This is a list of all standard c++ header files, except + # those already checked for above. + is_cpp_h = include in _CPP_HEADERS + + # Headers with C++ extensions shouldn't be considered C system headers + if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']: + is_system = False + + if is_system: + if is_cpp_h: + return _CPP_SYS_HEADER + else: + return _C_SYS_HEADER + + # If the target file and the include we're checking share a + # basename when we drop common extensions, and the include + # lives in . , then it's likely to be owned by the target file. + target_dir, target_base = ( + os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) + include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) + target_dir_pub = os.path.normpath(target_dir + '/../public') + target_dir_pub = target_dir_pub.replace('\\', '/') + if target_base == include_base and ( + include_dir == target_dir or + include_dir == target_dir_pub): + return _LIKELY_MY_HEADER + + # If the target and include share some initial basename + # component, it's possible the target is implementing the + # include, so it's allowed to be first, but we'll never + # complain if it's not there. + target_first_component = _RE_FIRST_COMPONENT.match(target_base) + include_first_component = _RE_FIRST_COMPONENT.match(include_base) + if (target_first_component and include_first_component and + target_first_component.group(0) == + include_first_component.group(0)): + return _POSSIBLE_MY_HEADER + + return _OTHER_HEADER + + + +def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): + """Check rules that are applicable to #include lines. + + Strings on #include lines are NOT removed from elided line, to make + certain tasks easier. However, to prevent false positives, checks + applicable to #include lines in CheckLanguage must be put here. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + include_state: An _IncludeState instance in which the headers are inserted. + error: The function to call with any errors found. + """ + fileinfo = FileInfo(filename) + line = clean_lines.lines[linenum] + + # "include" should use the new style "foo/bar.h" instead of just "bar.h" + # Only do this check if the included header follows google naming + # conventions. If not, assume that it's a 3rd party API that + # requires special include conventions. + # + # We also make an exception for Lua headers, which follow google + # naming convention but not the include convention. + match = Match(r'#include\s*"([^/]+\.h)"', line) + if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): + error(filename, linenum, 'build/include_subdir', 4, + 'Include the directory when naming .h files') + + # we shouldn't include a file more than once. actually, there are a + # handful of instances where doing so is okay, but in general it's + # not. + match = _RE_PATTERN_INCLUDE.search(line) + if match: + include = match.group(2) + is_system = (match.group(1) == '<') + duplicate_line = include_state.FindHeader(include) + if duplicate_line >= 0: + error(filename, linenum, 'build/include', 4, + '"%s" already included at %s:%s' % + (include, filename, duplicate_line)) + return + + for extension in GetNonHeaderExtensions(): + if (include.endswith('.' + extension) and + os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): + error(filename, linenum, 'build/include', 4, + 'Do not include .' + extension + ' files from other packages') + return + + if not _THIRD_PARTY_HEADERS_PATTERN.match(include): + include_state.include_list[-1].append((include, linenum)) + + # We want to ensure that headers appear in the right order: + # 1) for foo.cc, foo.h (preferred location) + # 2) c system files + # 3) cpp system files + # 4) for foo.cc, foo.h (deprecated location) + # 5) other google headers + # + # We classify each include statement as one of those 5 types + # using a number of techniques. The include_state object keeps + # track of the highest type seen, and complains if we see a + # lower type after that. + error_message = include_state.CheckNextIncludeOrder( + _ClassifyInclude(fileinfo, include, is_system)) + if error_message: + error(filename, linenum, 'build/include_order', 4, + '%s. Should be: %s.h, c system, c++ system, other.' % + (error_message, fileinfo.BaseName())) + canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) + if not include_state.IsInAlphabeticalOrder( + clean_lines, linenum, canonical_include): + error(filename, linenum, 'build/include_alpha', 4, + 'Include "%s" not in alphabetical order' % include) + include_state.SetLastHeader(canonical_include) + + + +def _GetTextInside(text, start_pattern): + r"""Retrieves all the text between matching open and close parentheses. + + Given a string of lines and a regular expression string, retrieve all the text + following the expression and between opening punctuation symbols like + (, [, or {, and the matching close-punctuation symbol. This properly nested + occurrences of the punctuations, so for the text like + printf(a(), b(c())); + a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. + start_pattern must match string having an open punctuation symbol at the end. + + Args: + text: The lines to extract text. Its comments and strings must be elided. + It can be single line and can span multiple lines. + start_pattern: The regexp string indicating where to start extracting + the text. + Returns: + The extracted text. + None if either the opening string or ending punctuation could not be found. + """ + # TODO(unknown): Audit cpplint.py to see what places could be profitably + # rewritten to use _GetTextInside (and use inferior regexp matching today). + + # Give opening punctuations to get the matching close-punctuations. + matching_punctuation = {'(': ')', '{': '}', '[': ']'} + closing_punctuation = set(itervalues(matching_punctuation)) + + # Find the position to start extracting text. + match = re.search(start_pattern, text, re.M) + if not match: # start_pattern not found in text. + return None + start_position = match.end(0) + + assert start_position > 0, ( + 'start_pattern must ends with an opening punctuation.') + assert text[start_position - 1] in matching_punctuation, ( + 'start_pattern must ends with an opening punctuation.') + # Stack of closing punctuations we expect to have in text after position. + punctuation_stack = [matching_punctuation[text[start_position - 1]]] + position = start_position + while punctuation_stack and position < len(text): + if text[position] == punctuation_stack[-1]: + punctuation_stack.pop() + elif text[position] in closing_punctuation: + # A closing punctuation without matching opening punctuations. + return None + elif text[position] in matching_punctuation: + punctuation_stack.append(matching_punctuation[text[position]]) + position += 1 + if punctuation_stack: + # Opening punctuations left without matching close-punctuations. + return None + # punctuations match. + return text[start_position:position - 1] + + +# Patterns for matching call-by-reference parameters. +# +# Supports nested templates up to 2 levels deep using this messy pattern: +# < (?: < (?: < [^<>]* +# > +# | [^<>] )* +# > +# | [^<>] )* +# > +_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* +_RE_PATTERN_TYPE = ( + r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' + r'(?:\w|' + r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' + r'::)+') +# A call-by-reference parameter ends with '& identifier'. +_RE_PATTERN_REF_PARAM = re.compile( + r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' + r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') +# A call-by-const-reference parameter either ends with 'const& identifier' +# or looks like 'const type& identifier' when 'type' is atomic. +_RE_PATTERN_CONST_REF_PARAM = ( + r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') +# Stream types. +_RE_PATTERN_REF_STREAM_PARAM = ( + r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')') + + +def CheckLanguage(filename, clean_lines, linenum, file_extension, + include_state, nesting_state, error): + """Checks rules from the 'C++ language rules' section of cppguide.html. + + Some of these rules are hard to test (function overloading, using + uint32 inappropriately), but we do the best we can. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + file_extension: The extension (without the dot) of the filename. + include_state: An _IncludeState instance in which the headers are inserted. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + # If the line is empty or consists of entirely a comment, no need to + # check it. + line = clean_lines.elided[linenum] + if not line: + return + + match = _RE_PATTERN_INCLUDE.search(line) + if match: + CheckIncludeLine(filename, clean_lines, linenum, include_state, error) + return + + # Reset include state across preprocessor directives. This is meant + # to silence warnings for conditional includes. + match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) + if match: + include_state.ResetSection(match.group(1)) + + + # Perform other checks now that we are sure that this is not an include line + CheckCasts(filename, clean_lines, linenum, error) + CheckGlobalStatic(filename, clean_lines, linenum, error) + CheckPrintf(filename, clean_lines, linenum, error) + + if file_extension in GetHeaderExtensions(): + # TODO(unknown): check that 1-arg constructors are explicit. + # How to tell it's a constructor? + # (handled in CheckForNonStandardConstructs for now) + # TODO(unknown): check that classes declare or disable copy/assign + # (level 1 error) + pass + + # Check if people are using the verboten C basic types. The only exception + # we regularly allow is "unsigned short port" for port. + if Search(r'\bshort port\b', line): + if not Search(r'\bunsigned short port\b', line): + error(filename, linenum, 'runtime/int', 4, + 'Use "unsigned short" for ports, not "short"') + else: + match = Search(r'\b(short|long(?! +double)|long long)\b', line) + if match: + error(filename, linenum, 'runtime/int', 4, + 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) + + # Check if some verboten operator overloading is going on + # TODO(unknown): catch out-of-line unary operator&: + # class X {}; + # int operator&(const X& x) { return 42; } // unary operator& + # The trick is it's hard to tell apart from binary operator&: + # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& + if Search(r'\boperator\s*&\s*\(\s*\)', line): + error(filename, linenum, 'runtime/operator', 4, + 'Unary operator& is dangerous. Do not use it.') + + # Check for suspicious usage of "if" like + # } if (a == b) { + if Search(r'\}\s*if\s*\(', line): + error(filename, linenum, 'readability/braces', 4, + 'Did you mean "else if"? If not, start a new line for "if".') + + # Check for potential format string bugs like printf(foo). + # We constrain the pattern not to pick things like DocidForPrintf(foo). + # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) + # TODO(unknown): Catch the following case. Need to change the calling + # convention of the whole function to process multiple line to handle it. + # printf( + # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); + printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') + if printf_args: + match = Match(r'([\w.\->()]+)$', printf_args) + if match and match.group(1) != '__VA_ARGS__': + function_name = re.search(r'\b((?:string)?printf)\s*\(', + line, re.I).group(1) + error(filename, linenum, 'runtime/printf', 4, + 'Potential format string bug. Do %s("%%s", %s) instead.' + % (function_name, match.group(1))) + + # Check for potential memset bugs like memset(buf, sizeof(buf), 0). + match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) + if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): + error(filename, linenum, 'runtime/memset', 4, + 'Did you mean "memset(%s, 0, %s)"?' + % (match.group(1), match.group(2))) + + if Search(r'\busing namespace\b', line): + if Search(r'\bliterals\b', line): + error(filename, linenum, 'build/namespaces_literals', 5, + 'Do not use namespace using-directives. ' + 'Use using-declarations instead.') + else: + error(filename, linenum, 'build/namespaces', 5, + 'Do not use namespace using-directives. ' + 'Use using-declarations instead.') + + # Detect variable-length arrays. + match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) + if (match and match.group(2) != 'return' and match.group(2) != 'delete' and + match.group(3).find(']') == -1): + # Split the size using space and arithmetic operators as delimiters. + # If any of the resulting tokens are not compile time constants then + # report the error. + tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) + is_const = True + skip_next = False + for tok in tokens: + if skip_next: + skip_next = False + continue + + if Search(r'sizeof\(.+\)', tok): continue + if Search(r'arraysize\(\w+\)', tok): continue + + tok = tok.lstrip('(') + tok = tok.rstrip(')') + if not tok: continue + if Match(r'\d+', tok): continue + if Match(r'0[xX][0-9a-fA-F]+', tok): continue + if Match(r'k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue + if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue + # A catch all for tricky sizeof cases, including 'sizeof expression', + # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' + # requires skipping the next token because we split on ' ' and '*'. + if tok.startswith('sizeof'): + skip_next = True + continue + is_const = False + break + if not is_const: + error(filename, linenum, 'runtime/arrays', 1, + 'Do not use variable-length arrays. Use an appropriately named ' + "('k' followed by CamelCase) compile-time constant for the size.") + + # Check for use of unnamed namespaces in header files. Registration + # macros are typically OK, so we allow use of "namespace {" on lines + # that end with backslashes. + if (file_extension in GetHeaderExtensions() + and Search(r'\bnamespace\s*{', line) + and line[-1] != '\\'): + error(filename, linenum, 'build/namespaces', 4, + 'Do not use unnamed namespaces in header files. See ' + 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' + ' for more information.') + + +def CheckGlobalStatic(filename, clean_lines, linenum, error): + """Check for unsafe global or static objects. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Match two lines at a time to support multiline declarations + if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): + line += clean_lines.elided[linenum + 1].strip() + + # Check for people declaring static/global STL strings at the top level. + # This is dangerous because the C++ language does not guarantee that + # globals with constructors are initialized before the first access, and + # also because globals can be destroyed when some threads are still running. + # TODO(unknown): Generalize this to also find static unique_ptr instances. + # TODO(unknown): File bugs for clang-tidy to find these. + match = Match( + r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +' + r'([a-zA-Z0-9_:]+)\b(.*)', + line) + + # Remove false positives: + # - String pointers (as opposed to values). + # string *pointer + # const string *pointer + # string const *pointer + # string *const pointer + # + # - Functions and template specializations. + # string Function(... + # string Class::Method(... + # + # - Operators. These are matched separately because operator names + # cross non-word boundaries, and trying to match both operators + # and functions at the same time would decrease accuracy of + # matching identifiers. + # string Class::operator*() + if (match and + not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and + not Search(r'\boperator\W', line) and + not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))): + if Search(r'\bconst\b', line): + error(filename, linenum, 'runtime/string', 4, + 'For a static/global string constant, use a C style string ' + 'instead: "%schar%s %s[]".' % + (match.group(1), match.group(2) or '', match.group(3))) + else: + error(filename, linenum, 'runtime/string', 4, + 'Static/global string variables are not permitted.') + + if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or + Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)): + error(filename, linenum, 'runtime/init', 4, + 'You seem to be initializing a member variable with itself.') + + +def CheckPrintf(filename, clean_lines, linenum, error): + """Check for printf related issues. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # When snprintf is used, the second argument shouldn't be a literal. + match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) + if match and match.group(2) != '0': + # If 2nd arg is zero, snprintf is used to calculate size. + error(filename, linenum, 'runtime/printf', 3, + 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' + 'to snprintf.' % (match.group(1), match.group(2))) + + # Check if some verboten C functions are being used. + if Search(r'\bsprintf\s*\(', line): + error(filename, linenum, 'runtime/printf', 5, + 'Never use sprintf. Use snprintf instead.') + match = Search(r'\b(strcpy|strcat)\s*\(', line) + if match: + error(filename, linenum, 'runtime/printf', 4, + 'Almost always, snprintf is better than %s' % match.group(1)) + + +def IsDerivedFunction(clean_lines, linenum): + """Check if current line contains an inherited function. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line contains a function with "override" + virt-specifier. + """ + # Scan back a few lines for start of current function + for i in xrange(linenum, max(-1, linenum - 10), -1): + match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) + if match: + # Look for "override" after the matching closing parenthesis + line, _, closing_paren = CloseExpression( + clean_lines, i, len(match.group(1))) + return (closing_paren >= 0 and + Search(r'\boverride\b', line[closing_paren:])) + return False + + +def IsOutOfLineMethodDefinition(clean_lines, linenum): + """Check if current line contains an out-of-line method definition. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line contains an out-of-line method definition. + """ + # Scan back a few lines for start of current function + for i in xrange(linenum, max(-1, linenum - 10), -1): + if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): + return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None + return False + + +def IsInitializerList(clean_lines, linenum): + """Check if current line is inside constructor initializer list. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + Returns: + True if current line appears to be inside constructor initializer + list, False otherwise. + """ + for i in xrange(linenum, 1, -1): + line = clean_lines.elided[i] + if i == linenum: + remove_function_body = Match(r'^(.*)\{\s*$', line) + if remove_function_body: + line = remove_function_body.group(1) + + if Search(r'\s:\s*\w+[({]', line): + # A lone colon tend to indicate the start of a constructor + # initializer list. It could also be a ternary operator, which + # also tend to appear in constructor initializer lists as + # opposed to parameter lists. + return True + if Search(r'\}\s*,\s*$', line): + # A closing brace followed by a comma is probably the end of a + # brace-initialized member in constructor initializer list. + return True + if Search(r'[{};]\s*$', line): + # Found one of the following: + # - A closing brace or semicolon, probably the end of the previous + # function. + # - An opening brace, probably the start of current class or namespace. + # + # Current line is probably not inside an initializer list since + # we saw one of those things without seeing the starting colon. + return False + + # Got to the beginning of the file without seeing the start of + # constructor initializer list. + return False + + +def CheckForNonConstReference(filename, clean_lines, linenum, + nesting_state, error): + """Check for non-const references. + + Separate from CheckLanguage since it scans backwards from current + line, instead of scanning forward. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: The function to call with any errors found. + """ + # Do nothing if there is no '&' on current line. + line = clean_lines.elided[linenum] + if '&' not in line: + return + + # If a function is inherited, current function doesn't have much of + # a choice, so any non-const references should not be blamed on + # derived function. + if IsDerivedFunction(clean_lines, linenum): + return + + # Don't warn on out-of-line method definitions, as we would warn on the + # in-line declaration, if it isn't marked with 'override'. + if IsOutOfLineMethodDefinition(clean_lines, linenum): + return + + # Long type names may be broken across multiple lines, usually in one + # of these forms: + # LongType + # ::LongTypeContinued &identifier + # LongType:: + # LongTypeContinued &identifier + # LongType< + # ...>::LongTypeContinued &identifier + # + # If we detected a type split across two lines, join the previous + # line to current line so that we can match const references + # accordingly. + # + # Note that this only scans back one line, since scanning back + # arbitrary number of lines would be expensive. If you have a type + # that spans more than 2 lines, please use a typedef. + if linenum > 1: + previous = None + if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): + # previous_line\n + ::current_line + previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', + clean_lines.elided[linenum - 1]) + elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): + # previous_line::\n + current_line + previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', + clean_lines.elided[linenum - 1]) + if previous: + line = previous.group(1) + line.lstrip() + else: + # Check for templated parameter that is split across multiple lines + endpos = line.rfind('>') + if endpos > -1: + (_, startline, startpos) = ReverseCloseExpression( + clean_lines, linenum, endpos) + if startpos > -1 and startline < linenum: + # Found the matching < on an earlier line, collect all + # pieces up to current line. + line = '' + for i in xrange(startline, linenum + 1): + line += clean_lines.elided[i].strip() + + # Check for non-const references in function parameters. A single '&' may + # found in the following places: + # inside expression: binary & for bitwise AND + # inside expression: unary & for taking the address of something + # inside declarators: reference parameter + # We will exclude the first two cases by checking that we are not inside a + # function body, including one that was just introduced by a trailing '{'. + # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. + if (nesting_state.previous_stack_top and + not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or + isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): + # Not at toplevel, not within a class, and not within a namespace + return + + # Avoid initializer lists. We only need to scan back from the + # current line for something that starts with ':'. + # + # We don't need to check the current line, since the '&' would + # appear inside the second set of parentheses on the current line as + # opposed to the first set. + if linenum > 0: + for i in xrange(linenum - 1, max(0, linenum - 10), -1): + previous_line = clean_lines.elided[i] + if not Search(r'[),]\s*$', previous_line): + break + if Match(r'^\s*:\s+\S', previous_line): + return + + # Avoid preprocessors + if Search(r'\\\s*$', line): + return + + # Avoid constructor initializer lists + if IsInitializerList(clean_lines, linenum): + return + + # We allow non-const references in a few standard places, like functions + # called "swap()" or iostream operators like "<<" or ">>". Do not check + # those function parameters. + # + # We also accept & in static_assert, which looks like a function but + # it's actually a declaration expression. + whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' + r'operator\s*[<>][<>]|' + r'static_assert|COMPILE_ASSERT' + r')\s*\(') + if Search(whitelisted_functions, line): + return + elif not Search(r'\S+\([^)]*$', line): + # Don't see a whitelisted function on this line. Actually we + # didn't see any function name on this line, so this is likely a + # multi-line parameter list. Try a bit harder to catch this case. + for i in xrange(2): + if (linenum > i and + Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): + return + + decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body + for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): + if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and + not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): + error(filename, linenum, 'runtime/references', 2, + 'Is this a non-const reference? ' + 'If so, make const or use a pointer: ' + + ReplaceAll(' *<', '<', parameter)) + + +def CheckCasts(filename, clean_lines, linenum, error): + """Various cast related checks. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + # Check to see if they're using an conversion function cast. + # I just try to capture the most common basic types, though there are more. + # Parameterless conversion functions, such as bool(), are allowed as they are + # probably a member operator declaration or default constructor. + match = Search( + r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' + r'(int|float|double|bool|char|int32|uint32|int64|uint64)' + r'(\([^)].*)', line) + expecting_function = ExpectingFunctionArgs(clean_lines, linenum) + if match and not expecting_function: + matched_type = match.group(2) + + # matched_new_or_template is used to silence two false positives: + # - New operators + # - Template arguments with function types + # + # For template arguments, we match on types immediately following + # an opening bracket without any spaces. This is a fast way to + # silence the common case where the function type is the first + # template argument. False negative with less-than comparison is + # avoided because those operators are usually followed by a space. + # + # function // bracket + no space = false positive + # value < double(42) // bracket + space = true positive + matched_new_or_template = match.group(1) + + # Avoid arrays by looking for brackets that come after the closing + # parenthesis. + if Match(r'\([^()]+\)\s*\[', match.group(3)): + return + + # Other things to ignore: + # - Function pointers + # - Casts to pointer types + # - Placement new + # - Alias declarations + matched_funcptr = match.group(3) + if (matched_new_or_template is None and + not (matched_funcptr and + (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', + matched_funcptr) or + matched_funcptr.startswith('(*)'))) and + not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and + not Search(r'new\(\S+\)\s*' + matched_type, line)): + error(filename, linenum, 'readability/casting', 4, + 'Using deprecated casting style. ' + 'Use static_cast<%s>(...) instead' % + matched_type) + + if not expecting_function: + CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', + r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) + + # This doesn't catch all cases. Consider (const char * const)"hello". + # + # (char *) "foo" should always be a const_cast (reinterpret_cast won't + # compile). + if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', + r'\((char\s?\*+\s?)\)\s*"', error): + pass + else: + # Check pointer casts for other than string constants + CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', + r'\((\w+\s?\*+\s?)\)', error) + + # In addition, we look for people taking the address of a cast. This + # is dangerous -- casts can assign to temporaries, so the pointer doesn't + # point where you think. + # + # Some non-identifier character is required before the '&' for the + # expression to be recognized as a cast. These are casts: + # expression = &static_cast(temporary()); + # function(&(int*)(temporary())); + # + # This is not a cast: + # reference_type&(int* function_param); + match = Search( + r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' + r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) + if match: + # Try a better error message when the & is bound to something + # dereferenced by the casted pointer, as opposed to the casted + # pointer itself. + parenthesis_error = False + match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) + if match: + _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) + if x1 >= 0 and clean_lines.elided[y1][x1] == '(': + _, y2, x2 = CloseExpression(clean_lines, y1, x1) + if x2 >= 0: + extended_line = clean_lines.elided[y2][x2:] + if y2 < clean_lines.NumLines() - 1: + extended_line += clean_lines.elided[y2 + 1] + if Match(r'\s*(?:->|\[)', extended_line): + parenthesis_error = True + + if parenthesis_error: + error(filename, linenum, 'readability/casting', 4, + ('Are you taking an address of something dereferenced ' + 'from a cast? Wrapping the dereferenced expression in ' + 'parentheses will make the binding more obvious')) + else: + error(filename, linenum, 'runtime/casting', 4, + ('Are you taking an address of a cast? ' + 'This is dangerous: could be a temp var. ' + 'Take the address before doing the cast, rather than after')) + + +def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): + """Checks for a C-style cast by looking for the pattern. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + cast_type: The string for the C++ cast to recommend. This is either + reinterpret_cast, static_cast, or const_cast, depending. + pattern: The regular expression used to find C-style casts. + error: The function to call with any errors found. + + Returns: + True if an error was emitted. + False otherwise. + """ + line = clean_lines.elided[linenum] + match = Search(pattern, line) + if not match: + return False + + # Exclude lines with keywords that tend to look like casts + context = line[0:match.start(1) - 1] + if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): + return False + + # Try expanding current context to see if we one level of + # parentheses inside a macro. + if linenum > 0: + for i in xrange(linenum - 1, max(0, linenum - 5), -1): + context = clean_lines.elided[i] + context + if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): + return False + + # operator++(int) and operator--(int) + if context.endswith(' operator++') or context.endswith(' operator--'): + return False + + # A single unnamed argument for a function tends to look like old style cast. + # If we see those, don't issue warnings for deprecated casts. + remainder = line[match.end(0):] + if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', + remainder): + return False + + # At this point, all that should be left is actual casts. + error(filename, linenum, 'readability/casting', 4, + 'Using C-style cast. Use %s<%s>(...) instead' % + (cast_type, match.group(1))) + + return True + + +def ExpectingFunctionArgs(clean_lines, linenum): + """Checks whether where function type arguments are expected. + + Args: + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + + Returns: + True if the line at 'linenum' is inside something that expects arguments + of function types. + """ + line = clean_lines.elided[linenum] + return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or + (linenum >= 2 and + (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', + clean_lines.elided[linenum - 1]) or + Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', + clean_lines.elided[linenum - 2]) or + Search(r'\bstd::m?function\s*\<\s*$', + clean_lines.elided[linenum - 1])))) + + +_HEADERS_CONTAINING_TEMPLATES = ( + ('', ('deque',)), + ('', ('unary_function', 'binary_function', + 'plus', 'minus', 'multiplies', 'divides', 'modulus', + 'negate', + 'equal_to', 'not_equal_to', 'greater', 'less', + 'greater_equal', 'less_equal', + 'logical_and', 'logical_or', 'logical_not', + 'unary_negate', 'not1', 'binary_negate', 'not2', + 'bind1st', 'bind2nd', + 'pointer_to_unary_function', + 'pointer_to_binary_function', + 'ptr_fun', + 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', + 'mem_fun_ref_t', + 'const_mem_fun_t', 'const_mem_fun1_t', + 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', + 'mem_fun_ref', + )), + ('', ('numeric_limits',)), + ('', ('list',)), + ('', ('map', 'multimap',)), + ('', ('allocator',)), + ('', ('queue', 'priority_queue',)), + ('', ('set', 'multiset',)), + ('', ('stack',)), + ('', ('char_traits', 'basic_string',)), + ('', ('tuple',)), + ('', ('pair',)), + ('', ('vector',)), + + # gcc extensions. + # Note: std::hash is their hash, ::hash is our hash + ('', ('hash_map', 'hash_multimap',)), + ('', ('hash_set', 'hash_multiset',)), + ('', ('slist',)), + ) + +_HEADERS_MAYBE_TEMPLATES = ( + ('', ('copy', 'max', 'min', 'min_element', 'sort', + 'transform', + )), + ('', ('swap',)), + ) + +_RE_PATTERN_STRING = re.compile(r'\bstring\b') + +_re_pattern_headers_maybe_templates = [] +for _header, _templates in _HEADERS_MAYBE_TEMPLATES: + for _template in _templates: + # Match max(..., ...), max(..., ...), but not foo->max, foo.max or + # type::max(). + _re_pattern_headers_maybe_templates.append( + (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), + _template, + _header)) + +# Other scripts may reach in and modify this pattern. +_re_pattern_templates = [] +for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: + for _template in _templates: + _re_pattern_templates.append( + (re.compile(r'(\<|\b)' + _template + r'\s*\<'), + _template + '<>', + _header)) + + +def FilesBelongToSameModule(filename_cc, filename_h): + """Check if these two filenames belong to the same module. + + The concept of a 'module' here is a as follows: + foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the + same 'module' if they are in the same directory. + some/path/public/xyzzy and some/path/internal/xyzzy are also considered + to belong to the same module here. + + If the filename_cc contains a longer path than the filename_h, for example, + '/absolute/path/to/base/sysinfo.cc', and this file would include + 'base/sysinfo.h', this function also produces the prefix needed to open the + header. This is used by the caller of this function to more robustly open the + header file. We don't have access to the real include paths in this context, + so we need this guesswork here. + + Known bugs: tools/base/bar.cc and base/bar.h belong to the same module + according to this implementation. Because of this, this function gives + some false positives. This should be sufficiently rare in practice. + + Args: + filename_cc: is the path for the source (e.g. .cc) file + filename_h: is the path for the header path + + Returns: + Tuple with a bool and a string: + bool: True if filename_cc and filename_h belong to the same module. + string: the additional prefix needed to open the header file. + """ + fileinfo_cc = FileInfo(filename_cc) + if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): + return (False, '') + + fileinfo_h = FileInfo(filename_h) + if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions(): + return (False, '') + + filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] + matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) + if matched_test_suffix: + filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] + + filename_cc = filename_cc.replace('/public/', '/') + filename_cc = filename_cc.replace('/internal/', '/') + + filename_h = filename_h[:-(len(fileinfo_h.Extension()))] + if filename_h.endswith('-inl'): + filename_h = filename_h[:-len('-inl')] + filename_h = filename_h.replace('/public/', '/') + filename_h = filename_h.replace('/internal/', '/') + + files_belong_to_same_module = filename_cc.endswith(filename_h) + common_path = '' + if files_belong_to_same_module: + common_path = filename_cc[:-len(filename_h)] + return files_belong_to_same_module, common_path + + +def UpdateIncludeState(filename, include_dict, io=codecs): + """Fill up the include_dict with new includes found from the file. + + Args: + filename: the name of the header to read. + include_dict: a dictionary in which the headers are inserted. + io: The io factory to use to read the file. Provided for testability. + + Returns: + True if a header was successfully added. False otherwise. + """ + headerfile = None + try: + headerfile = io.open(filename, 'r', 'utf8', 'replace') + except IOError: + return False + linenum = 0 + for line in headerfile: + linenum += 1 + clean_line = CleanseComments(line) + match = _RE_PATTERN_INCLUDE.search(clean_line) + if match: + include = match.group(2) + include_dict.setdefault(include, linenum) + return True + + +def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, + io=codecs): + """Reports for missing stl includes. + + This function will output warnings to make sure you are including the headers + necessary for the stl containers and functions that you use. We only give one + reason to include a header. For example, if you use both equal_to<> and + less<> in a .h file, only one (the latter in the file) of these will be + reported as a reason to include the . + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + include_state: An _IncludeState instance. + error: The function to call with any errors found. + io: The IO factory to use to read the header file. Provided for unittest + injection. + """ + required = {} # A map of header name to linenumber and the template entity. + # Example of required: { '': (1219, 'less<>') } + + for linenum in range(clean_lines.NumLines()): + line = clean_lines.elided[linenum] + if not line or line[0] == '#': + continue + + # String is special -- it is a non-templatized type in STL. + matched = _RE_PATTERN_STRING.search(line) + if matched: + # Don't warn about strings in non-STL namespaces: + # (We check only the first match per line; good enough.) + prefix = line[:matched.start()] + if prefix.endswith('std::') or not prefix.endswith('::'): + required[''] = (linenum, 'string') + + for pattern, template, header in _re_pattern_headers_maybe_templates: + if pattern.search(line): + required[header] = (linenum, template) + + # The following function is just a speed up, no semantics are changed. + if not '<' in line: # Reduces the cpu time usage by skipping lines. + continue + + for pattern, template, header in _re_pattern_templates: + if pattern.search(line): + required[header] = (linenum, template) + + # The policy is that if you #include something in foo.h you don't need to + # include it again in foo.cc. Here, we will look at possible includes. + # Let's flatten the include_state include_list and copy it into a dictionary. + include_dict = dict([item for sublist in include_state.include_list + for item in sublist]) + + # Did we find the header for this file (if any) and successfully load it? + header_found = False + + # Use the absolute path so that matching works properly. + abs_filename = FileInfo(filename).FullName() + + # For Emacs's flymake. + # If cpplint is invoked from Emacs's flymake, a temporary file is generated + # by flymake and that file name might end with '_flymake.cc'. In that case, + # restore original file name here so that the corresponding header file can be + # found. + # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' + # instead of 'foo_flymake.h' + abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) + + # include_dict is modified during iteration, so we iterate over a copy of + # the keys. + header_keys = list(include_dict.keys()) + for header in header_keys: + (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) + fullpath = common_path + header + if same_module and UpdateIncludeState(fullpath, include_dict, io): + header_found = True + + # If we can't find the header file for a .cc, assume it's because we don't + # know where to look. In that case we'll give up as we're not sure they + # didn't include it in the .h file. + # TODO(unknown): Do a better job of finding .h files so we are confident that + # not having the .h file means there isn't one. + if not header_found: + for extension in GetNonHeaderExtensions(): + if filename.endswith('.' + extension): + return + + # All the lines have been processed, report the errors found. + for required_header_unstripped in sorted(required, key=required.__getitem__): + template = required[required_header_unstripped][1] + if required_header_unstripped.strip('<>"') not in include_dict: + error(filename, required[required_header_unstripped][0], + 'build/include_what_you_use', 4, + 'Add #include ' + required_header_unstripped + ' for ' + template) + + +_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') + + +def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): + """Check that make_pair's template arguments are deduced. + + G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are + specified explicitly, and such use isn't intended in any case. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) + if match: + error(filename, linenum, 'build/explicit_make_pair', + 4, # 4 = high confidence + 'For C++11-compatibility, omit template arguments from make_pair' + ' OR use pair directly OR if appropriate, construct a pair directly') + + +def CheckRedundantVirtual(filename, clean_lines, linenum, error): + """Check if line contains a redundant "virtual" function-specifier. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Look for "virtual" on current line. + line = clean_lines.elided[linenum] + virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) + if not virtual: return + + # Ignore "virtual" keywords that are near access-specifiers. These + # are only used in class base-specifier and do not apply to member + # functions. + if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or + Match(r'^\s+(public|protected|private)\b', virtual.group(3))): + return + + # Ignore the "virtual" keyword from virtual base classes. Usually + # there is a column on the same line in these cases (virtual base + # classes are rare in google3 because multiple inheritance is rare). + if Match(r'^.*[^:]:[^:].*$', line): return + + # Look for the next opening parenthesis. This is the start of the + # parameter list (possibly on the next line shortly after virtual). + # TODO(unknown): doesn't work if there are virtual functions with + # decltype() or other things that use parentheses, but csearch suggests + # that this is rare. + end_col = -1 + end_line = -1 + start_col = len(virtual.group(2)) + for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): + line = clean_lines.elided[start_line][start_col:] + parameter_list = Match(r'^([^(]*)\(', line) + if parameter_list: + # Match parentheses to find the end of the parameter list + (_, end_line, end_col) = CloseExpression( + clean_lines, start_line, start_col + len(parameter_list.group(1))) + break + start_col = 0 + + if end_col < 0: + return # Couldn't find end of parameter list, give up + + # Look for "override" or "final" after the parameter list + # (possibly on the next few lines). + for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): + line = clean_lines.elided[i][end_col:] + match = Search(r'\b(override|final)\b', line) + if match: + error(filename, linenum, 'readability/inheritance', 4, + ('"virtual" is redundant since function is ' + 'already declared as "%s"' % match.group(1))) + + # Set end_col to check whole lines after we are done with the + # first line. + end_col = 0 + if Search(r'[^\w]\s*$', line): + break + + +def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): + """Check if line contains a redundant "override" or "final" virt-specifier. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + # Look for closing parenthesis nearby. We need one to confirm where + # the declarator ends and where the virt-specifier starts to avoid + # false positives. + line = clean_lines.elided[linenum] + declarator_end = line.rfind(')') + if declarator_end >= 0: + fragment = line[declarator_end:] + else: + if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: + fragment = line + else: + return + + # Check that at most one of "override" or "final" is present, not both + if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): + error(filename, linenum, 'readability/inheritance', 4, + ('"override" is redundant since function is ' + 'already declared as "final"')) + + + + +# Returns true if we are at a new block, and it is directly +# inside of a namespace. +def IsBlockInNameSpace(nesting_state, is_forward_declaration): + """Checks that the new block is directly in a namespace. + + Args: + nesting_state: The _NestingState object that contains info about our state. + is_forward_declaration: If the class is a forward declared class. + Returns: + Whether or not the new block is directly in a namespace. + """ + if is_forward_declaration: + return len(nesting_state.stack) >= 1 and ( + isinstance(nesting_state.stack[-1], _NamespaceInfo)) + + + return (len(nesting_state.stack) > 1 and + nesting_state.stack[-1].check_namespace_indentation and + isinstance(nesting_state.stack[-2], _NamespaceInfo)) + + +def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, + raw_lines_no_comments, linenum): + """This method determines if we should apply our namespace indentation check. + + Args: + nesting_state: The current nesting state. + is_namespace_indent_item: If we just put a new class on the stack, True. + If the top of the stack is not a class, or we did not recently + add the class, False. + raw_lines_no_comments: The lines without the comments. + linenum: The current line number we are processing. + + Returns: + True if we should apply our namespace indentation check. Currently, it + only works for classes and namespaces inside of a namespace. + """ + + is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, + linenum) + + if not (is_namespace_indent_item or is_forward_declaration): + return False + + # If we are in a macro, we do not want to check the namespace indentation. + if IsMacroDefinition(raw_lines_no_comments, linenum): + return False + + return IsBlockInNameSpace(nesting_state, is_forward_declaration) + + +# Call this method if the line is directly inside of a namespace. +# If the line above is blank (excluding comments) or the start of +# an inner namespace, it cannot be indented. +def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, + error): + line = raw_lines_no_comments[linenum] + if Match(r'^\s+', line): + error(filename, linenum, 'runtime/indentation_namespace', 4, + 'Do not indent within a namespace') + + +def ProcessLine(filename, file_extension, clean_lines, line, + include_state, function_state, nesting_state, error, + extra_check_functions=None): + """Processes a single line in the file. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + clean_lines: An array of strings, each representing a line of the file, + with comments stripped. + line: Number of line being processed. + include_state: An _IncludeState instance in which the headers are inserted. + function_state: A _FunctionState instance which counts function lines, etc. + nesting_state: A NestingState instance which maintains information about + the current stack of nested blocks being parsed. + error: A callable to which errors are reported, which takes 4 arguments: + filename, line number, error level, and message + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + raw_lines = clean_lines.raw_lines + ParseNolintSuppressions(filename, raw_lines[line], line, error) + nesting_state.Update(filename, clean_lines, line, error) + CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, + error) + if nesting_state.InAsmBlock(): return + CheckForFunctionLengths(filename, clean_lines, line, function_state, error) + CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) + CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) + CheckLanguage(filename, clean_lines, line, file_extension, include_state, + nesting_state, error) + CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) + CheckForNonStandardConstructs(filename, clean_lines, line, + nesting_state, error) + CheckVlogArguments(filename, clean_lines, line, error) + CheckPosixThreading(filename, clean_lines, line, error) + CheckInvalidIncrement(filename, clean_lines, line, error) + CheckMakePairUsesDeduction(filename, clean_lines, line, error) + CheckRedundantVirtual(filename, clean_lines, line, error) + CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) + if extra_check_functions: + for check_fn in extra_check_functions: + check_fn(filename, clean_lines, line, error) + +def FlagCxx11Features(filename, clean_lines, linenum, error): + """Flag those c++11 features that we only allow in certain places. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) + + # Flag unapproved C++ TR1 headers. + if include and include.group(1).startswith('tr1/'): + error(filename, linenum, 'build/c++tr1', 5, + ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1)) + + # Flag unapproved C++11 headers. + if include and include.group(1) in ('cfenv', + 'condition_variable', + 'fenv.h', + 'future', + 'mutex', + 'thread', + 'chrono', + 'ratio', + 'regex', + 'system_error', + ): + error(filename, linenum, 'build/c++11', 5, + ('<%s> is an unapproved C++11 header.') % include.group(1)) + + # The only place where we need to worry about C++11 keywords and library + # features in preprocessor directives is in macro definitions. + if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return + + # These are classes and free functions. The classes are always + # mentioned as std::*, but we only catch the free functions if + # they're not found by ADL. They're alphabetical by header. + for top_name in ( + # type_traits + 'alignment_of', + 'aligned_union', + ): + if Search(r'\bstd::%s\b' % top_name, line): + error(filename, linenum, 'build/c++11', 5, + ('std::%s is an unapproved C++11 class or function. Send c-style ' + 'an example of where it would make your code more readable, and ' + 'they may let you use it.') % top_name) + + +def FlagCxx14Features(filename, clean_lines, linenum, error): + """Flag those C++14 features that we restrict. + + Args: + filename: The name of the current file. + clean_lines: A CleansedLines instance containing the file. + linenum: The number of the line to check. + error: The function to call with any errors found. + """ + line = clean_lines.elided[linenum] + + include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) + + # Flag unapproved C++14 headers. + if include and include.group(1) in ('scoped_allocator', 'shared_mutex'): + error(filename, linenum, 'build/c++14', 5, + ('<%s> is an unapproved C++14 header.') % include.group(1)) + + +def ProcessFileData(filename, file_extension, lines, error, + extra_check_functions=None): + """Performs lint checks and reports any errors to the given error function. + + Args: + filename: Filename of the file that is being processed. + file_extension: The extension (dot not included) of the file. + lines: An array of strings, each representing a line of the file, with the + last element being empty if the file is terminated with a newline. + error: A callable to which errors are reported, which takes 4 arguments: + filename, line number, error level, and message + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + lines = (['// marker so line numbers and indices both start at 1'] + lines + + ['// marker so line numbers end in a known way']) + + include_state = _IncludeState() + function_state = _FunctionState() + nesting_state = NestingState() + + ResetNolintSuppressions() + + CheckForCopyright(filename, lines, error) + ProcessGlobalSuppresions(lines) + RemoveMultiLineComments(filename, lines, error) + clean_lines = CleansedLines(lines) + + if file_extension in GetHeaderExtensions(): + CheckForHeaderGuard(filename, clean_lines, error) + + for line in range(clean_lines.NumLines()): + ProcessLine(filename, file_extension, clean_lines, line, + include_state, function_state, nesting_state, error, + extra_check_functions) + FlagCxx11Features(filename, clean_lines, line, error) + nesting_state.CheckCompletedBlocks(filename, error) + + CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) + + # Check that the .cc file has included its header if it exists. + if _IsSourceExtension(file_extension): + CheckHeaderFileIncluded(filename, include_state, error) + + # We check here rather than inside ProcessLine so that we see raw + # lines rather than "cleaned" lines. + CheckForBadCharacters(filename, lines, error) + + CheckForNewlineAtEOF(filename, lines, error) + +def ProcessConfigOverrides(filename): + """ Loads the configuration files and processes the config overrides. + + Args: + filename: The name of the file being processed by the linter. + + Returns: + False if the current |filename| should not be processed further. + """ + + abs_filename = os.path.abspath(filename) + cfg_filters = [] + keep_looking = True + while keep_looking: + abs_path, base_name = os.path.split(abs_filename) + if not base_name: + break # Reached the root directory. + + cfg_file = os.path.join(abs_path, "CPPLINT.cfg") + abs_filename = abs_path + if not os.path.isfile(cfg_file): + continue + + try: + with open(cfg_file) as file_handle: + for line in file_handle: + line, _, _ = line.partition('#') # Remove comments. + if not line.strip(): + continue + + name, _, val = line.partition('=') + name = name.strip() + val = val.strip() + if name == 'set noparent': + keep_looking = False + elif name == 'filter': + cfg_filters.append(val) + elif name == 'exclude_files': + # When matching exclude_files pattern, use the base_name of + # the current file name or the directory name we are processing. + # For example, if we are checking for lint errors in /foo/bar/baz.cc + # and we found the .cfg file at /foo/CPPLINT.cfg, then the config + # file's "exclude_files" filter is meant to be checked against "bar" + # and not "baz" nor "bar/baz.cc". + if base_name: + pattern = re.compile(val) + if pattern.match(base_name): + _cpplint_state.PrintInfo('Ignoring "%s": file excluded by ' + '"%s". File path component "%s" matches pattern "%s"\n' % + (filename, cfg_file, base_name, val)) + return False + elif name == 'linelength': + global _line_length + try: + _line_length = int(val) + except ValueError: + _cpplint_state.PrintError('Line length must be numeric.') + elif name == 'extensions': + global _valid_extensions + try: + extensions = [ext.strip() for ext in val.split(',')] + _valid_extensions = set(extensions) + except ValueError: + sys.stderr.write('Extensions should be a comma-separated list of values;' + 'for example: extensions=hpp,cpp\n' + 'This could not be parsed: "%s"' % (val,)) + elif name == 'headers': + global _header_extensions + try: + extensions = [ext.strip() for ext in val.split(',')] + _header_extensions = set(extensions) + except ValueError: + sys.stderr.write('Extensions should be a comma-separated list of values;' + 'for example: extensions=hpp,cpp\n' + 'This could not be parsed: "%s"' % (val,)) + elif name == 'root': + global _root + _root = val + else: + _cpplint_state.PrintError( + 'Invalid configuration option (%s) in file %s\n' % + (name, cfg_file)) + + except IOError: + _cpplint_state.PrintError( + "Skipping config file '%s': Can't open for reading\n" % cfg_file) + keep_looking = False + + # Apply all the accumulated filters in reverse order (top-level directory + # config options having the least priority). + for cfg_filter in reversed(cfg_filters): + _AddFilters(cfg_filter) + + return True + + +def ProcessFile(filename, vlevel, extra_check_functions=None): + """Does google-lint on a single file. + + Args: + filename: The name of the file to parse. + + vlevel: The level of errors to report. Every error of confidence + >= verbose_level will be reported. 0 is a good default. + + extra_check_functions: An array of additional check functions that will be + run on each source line. Each function takes 4 + arguments: filename, clean_lines, line, error + """ + + _SetVerboseLevel(vlevel) + _BackupFilters() + + if not ProcessConfigOverrides(filename): + _RestoreFilters() + return + + lf_lines = [] + crlf_lines = [] + try: + # Support the UNIX convention of using "-" for stdin. Note that + # we are not opening the file with universal newline support + # (which codecs doesn't support anyway), so the resulting lines do + # contain trailing '\r' characters if we are reading a file that + # has CRLF endings. + # If after the split a trailing '\r' is present, it is removed + # below. + if filename == '-': + lines = codecs.StreamReaderWriter(sys.stdin, + codecs.getreader('utf8'), + codecs.getwriter('utf8'), + 'replace').read().split('\n') + else: + lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') + + # Remove trailing '\r'. + # The -1 accounts for the extra trailing blank line we get from split() + for linenum in range(len(lines) - 1): + if lines[linenum].endswith('\r'): + lines[linenum] = lines[linenum].rstrip('\r') + crlf_lines.append(linenum + 1) + else: + lf_lines.append(linenum + 1) + + except IOError: + _cpplint_state.PrintError( + "Skipping input '%s': Can't open for reading\n" % filename) + _RestoreFilters() + return + + # Note, if no dot is found, this will give the entire filename as the ext. + file_extension = filename[filename.rfind('.') + 1:] + + # When reading from stdin, the extension is unknown, so no cpplint tests + # should rely on the extension. + if filename != '-' and file_extension not in GetAllExtensions(): + _cpplint_state.PrintError('Ignoring %s; not a valid file name ' + '(%s)\n' % (filename, ', '.join(GetAllExtensions()))) + else: + ProcessFileData(filename, file_extension, lines, Error, + extra_check_functions) + + # If end-of-line sequences are a mix of LF and CR-LF, issue + # warnings on the lines with CR. + # + # Don't issue any warnings if all lines are uniformly LF or CR-LF, + # since critique can handle these just fine, and the style guide + # doesn't dictate a particular end of line sequence. + # + # We can't depend on os.linesep to determine what the desired + # end-of-line sequence should be, since that will return the + # server-side end-of-line sequence. + if lf_lines and crlf_lines: + # Warn on every line with CR. An alternative approach might be to + # check whether the file is mostly CRLF or just LF, and warn on the + # minority, we bias toward LF here since most tools prefer LF. + for linenum in crlf_lines: + Error(filename, linenum, 'whitespace/newline', 1, + 'Unexpected \\r (^M) found; better to use only \\n') + + _cpplint_state.PrintInfo('Done processing %s\n' % filename) + _RestoreFilters() + + +def PrintUsage(message): + """Prints a brief usage string and exits, optionally with an error message. + + Args: + message: The optional error message. + """ + sys.stderr.write(_USAGE) + + if message: + sys.exit('\nFATAL ERROR: ' + message) + else: + sys.exit(0) + + +def PrintCategories(): + """Prints a list of all the error-categories used by error messages. + + These are the categories used to filter messages via --filter. + """ + sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) + sys.exit(0) + + +def ParseArguments(args): + """Parses the command line arguments. + + This may set the output format and verbosity level as side-effects. + + Args: + args: The command line arguments: + + Returns: + The list of filenames to lint. + """ + try: + (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', + 'counting=', + 'filter=', + 'root=', + 'repository=', + 'linelength=', + 'extensions=', + 'exclude=', + 'headers=', + 'quiet', + 'recursive']) + except getopt.GetoptError: + PrintUsage('Invalid arguments.') + + verbosity = _VerboseLevel() + output_format = _OutputFormat() + filters = '' + counting_style = '' + recursive = False + + for (opt, val) in opts: + if opt == '--help': + PrintUsage(None) + elif opt == '--output': + if val not in ('emacs', 'vs7', 'eclipse', 'junit'): + PrintUsage('The only allowed output formats are emacs, vs7, eclipse ' + 'and junit.') + output_format = val + elif opt == '--verbose': + verbosity = int(val) + elif opt == '--filter': + filters = val + if not filters: + PrintCategories() + elif opt == '--counting': + if val not in ('total', 'toplevel', 'detailed'): + PrintUsage('Valid counting options are total, toplevel, and detailed') + counting_style = val + elif opt == '--root': + global _root + _root = val + elif opt == '--repository': + global _repository + _repository = val + elif opt == '--linelength': + global _line_length + try: + _line_length = int(val) + except ValueError: + PrintUsage('Line length must be digits.') + elif opt == '--exclude': + global _excludes + if not _excludes: + _excludes = set() + _excludes.update(glob.glob(val)) + elif opt == '--extensions': + global _valid_extensions + try: + _valid_extensions = set(val.split(',')) + except ValueError: + PrintUsage('Extensions must be comma seperated list.') + elif opt == '--headers': + global _header_extensions + try: + _header_extensions = set(val.split(',')) + except ValueError: + PrintUsage('Extensions must be comma seperated list.') + elif opt == '--recursive': + recursive = True + elif opt == '--quiet': + global _quiet + _quiet = True + + if not filenames: + PrintUsage('No files were specified.') + + if recursive: + filenames = _ExpandDirectories(filenames) + + if _excludes: + filenames = _FilterExcludedFiles(filenames) + + _SetOutputFormat(output_format) + _SetVerboseLevel(verbosity) + _SetFilters(filters) + _SetCountingStyle(counting_style) + + return filenames + +def _ExpandDirectories(filenames): + """Searches a list of filenames and replaces directories in the list with + all files descending from those directories. Files with extensions not in + the valid extensions list are excluded. + + Args: + filenames: A list of files or directories + + Returns: + A list of all files that are members of filenames or descended from a + directory in filenames + """ + expanded = set() + for filename in filenames: + if not os.path.isdir(filename): + expanded.add(filename) + continue + + for root, _, files in os.walk(filename): + for loopfile in files: + fullname = os.path.join(root, loopfile) + if fullname.startswith('.' + os.path.sep): + fullname = fullname[len('.' + os.path.sep):] + expanded.add(fullname) + + filtered = [] + for filename in expanded: + if os.path.splitext(filename)[1][1:] in GetAllExtensions(): + filtered.append(filename) + + return filtered + +def _FilterExcludedFiles(filenames): + """Filters out files listed in the --exclude command line switch. File paths + in the switch are evaluated relative to the current working directory + """ + exclude_paths = [os.path.abspath(f) for f in _excludes] + return [f for f in filenames if os.path.abspath(f) not in exclude_paths] + +def main(): + filenames = ParseArguments(sys.argv[1:]) + backup_err = sys.stderr + try: + # Change stderr to write with replacement characters so we don't die + # if we try to print something containing non-ASCII characters. + sys.stderr = codecs.StreamReader(sys.stderr, 'replace') + + _cpplint_state.ResetErrorCounts() + for filename in filenames: + ProcessFile(filename, _cpplint_state.verbose_level) + _cpplint_state.PrintErrorCounts() + + if _cpplint_state.output_format == 'junit': + sys.stderr.write(_cpplint_state.FormatJUnitXML()) + + finally: + sys.stderr = backup_err + + sys.exit(_cpplint_state.error_count > 0) + + +if __name__ == '__main__': + main() diff --git a/language_bindings/python/CMakeLists.txt b/language_bindings/python/CMakeLists.txt index c6c4e3b..3a06cd1 100644 --- a/language_bindings/python/CMakeLists.txt +++ b/language_bindings/python/CMakeLists.txt @@ -1,93 +1,98 @@ #============================================================================== # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief configuration for python binding using pybind11 # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= # FIXME! The user should have a choice to configure this path. execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-m" "site" "--user-site" RESULT_VARIABLE _PYTHON_SUCCESS OUTPUT_VARIABLE PYTHON_USER_SITE ERROR_VARIABLE _PYTHON_ERROR_VALUE) if(NOT _PYTHON_SUCCESS MATCHES 0) message(FATAL_ERROR "Python config failure:\n${_PYTHON_ERROR_VALUE}") endif() string(REGEX REPLACE "\n" "" PYTHON_USER_SITE ${PYTHON_USER_SITE}) set (PY_BINDING_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_module.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_common.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_cell.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic1.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic2.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic3.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic4.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_crystal_plasticity_finite.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_hyper_elasto_plastic1.cc + ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic_generic.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_solvers.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_fftengine.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_projections.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_field_collection.cc ) if (${USE_FFTWMPI}) add_definitions(-DWITH_FFTWMPI) endif(${USE_FFTWMPI}) if (${USE_PFFT}) add_definitions(-DWITH_PFFT) endif(${USE_PFFT}) find_package(PythonLibsNew ${MUSPECTRE_PYTHON_MAJOR_VERSION} MODULE REQUIRED) # On OS X, add -Wno-deprecated-declarations IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") add_compile_options(-Wno-deprecated-declarations) ENDIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") pybind11_add_module(pyMuSpectreLib ${PY_BINDING_SRCS}) target_link_libraries(pyMuSpectreLib PRIVATE muSpectre) # Want to rename the output, so that the python module is called muSpectre set_target_properties(pyMuSpectreLib PROPERTIES OUTPUT_NAME _muSpectre) target_include_directories(pyMuSpectreLib PUBLIC ${PYTHON_INCLUDE_DIRS}) -add_custom_target(pyMuSpectre ALL SOURCES muSpectre/__init__.py muSpectre/fft.py) +add_custom_target(pyMuSpectre ALL SOURCES + muSpectre/__init__.py + muSpectre/fft.py) add_custom_command(TARGET pyMuSpectre POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory - ${CMAKE_SOURCE_DIR}/language_bindings/python/muSpectre $/muSpectre) + ${CMAKE_SOURCE_DIR}/language_bindings/python/muSpectre + $/muSpectre) install(TARGETS pyMuSpectreLib LIBRARY DESTINATION ${PYTHON_USER_SITE}) -install(FILES muSpectre/__init__.py muSpectre/fft.py DESTINATION ${PYTHON_USER_SITE}/muSpectre) +install(FILES muSpectre/__init__.py muSpectre/fft.py DESTINATION + ${PYTHON_USER_SITE}/muSpectre) diff --git a/language_bindings/python/bind_py_cell.cc b/language_bindings/python/bind_py_cell.cc index 965b7eb..9fbc090 100644 --- a/language_bindings/python/bind_py_cell.cc +++ b/language_bindings/python/bind_py_cell.cc @@ -1,255 +1,262 @@ /** * @file bind_py_cell.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief Python bindings for the cell factory function * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/common.hh" #include "common/ccoord_operations.hh" #include "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 #include "pybind11/eigen.h" #include #include -using namespace muSpectre; // NOLINT // TODO(junge): figure this out +using muSpectre::Ccoord_t; +using muSpectre::Dim_t; +using muSpectre::Formulation; +using muSpectre::Rcoord_t; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage /** * 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) { +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.), + "resolutions"_a, + "lengths"_a = muSpectre::CcoordOps::get_cube(1.), "formulation"_a = Formulation::finite_strain); #ifdef WITH_FFTWMPI add_parallel_cell_factory_helper>( mod, "FFTWMPICellFactory"); #endif #ifdef WITH_PFFT add_parallel_cell_factory_helper>(mod, "PFFTCellFactory"); #endif } void add_cell_factory(py::module & mod) { - add_cell_factory_helper(mod); - add_cell_factory_helper(mod); + add_cell_factory_helper(mod); + add_cell_factory_helper(mod); } /** * CellBase for which the material and spatial dimension are identical */ -template void add_cell_base_helper(py::module & mod) { +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()) + using sys_t = muSpectre::CellBase; + py::class_(mod, name.c_str()) .def("__len__", &sys_t::size) .def("__iter__", [](sys_t & s) { return py::make_iterator(s.begin(), s.end()); }) .def("initialise", &sys_t::initialise, - "flags"_a = FFT_PlanFlags::estimate) + "flags"_a = muSpectre::FFT_PlanFlags::estimate) .def( "directional_stiffness", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } if (!cell.is_initialised()) { cell.initialise(); } const std::string out_name{"temp output for directional stiffness"}; const std::string in_name{"temp input for directional stiffness"}; constexpr bool create_tangent{true}; auto & K = cell.get_tangent(create_tangent); auto & input = cell.get_managed_T2_field(in_name); auto & output = cell.get_managed_T2_field(out_name); input.eigen() = v; cell.directional_stiffness(K, input, output); return output.eigen(); }, "δF"_a) .def("project", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } if (!cell.is_initialised()) { cell.initialise(); } const std::string in_name{"temp input for projection"}; auto & input = cell.get_managed_T2_field(in_name); input.eigen() = v; cell.project(input); return input.eigen(); }, "field"_a) .def("get_strain", [](sys_t & s) { return s.get_strain().eigen(); }, py::return_value_policy::reference_internal) .def("get_stress", [](sys_t & s) { return Eigen::ArrayXXd(s.get_stress().eigen()); }) .def_property_readonly("size", &sys_t::size) .def("evaluate_stress_tangent", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } auto & strain{cell.get_strain()}; strain.eigen() = v; auto stress_tgt{cell.evaluate_stress_tangent(strain)}; return std::tuple( std::get<0>(stress_tgt).eigen(), std::get<1>(stress_tgt).eigen()); }, "strain"_a) .def("evaluate_stress", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } auto & strain{cell.get_strain()}; strain.eigen() = v; return cell.evaluate_stress(); }, "strain"_a, py::return_value_policy::reference_internal) .def("get_projection", &sys_t::get_projection) .def("get_subdomain_resolutions", &sys_t::get_subdomain_resolutions) .def("get_subdomain_locations", &sys_t::get_subdomain_locations) .def("get_domain_resolutions", &sys_t::get_domain_resolutions) .def("get_domain_lengths", &sys_t::get_domain_resolutions) .def("set_uniform_strain", [](sys_t & cell, py::EigenDRef & v) -> void { cell.set_uniform_strain(v); }, "strain"_a) .def("save_history_variables", &sys_t::save_history_variables); } void add_cell_base(py::module & mod) { - py::class_(mod, "Cell") + py::class_(mod, "Cell") .def("get_globalised_internal_real_array", - &Cell::get_globalised_internal_real_array, "unique_name"_a, + &muSpectre::Cell::get_globalised_internal_real_array, + "unique_name"_a, "Convenience function to copy local (internal) fields of " "materials into a global field. At least one of the materials in " "the cell needs to contain an internal field named " "`unique_name`. If multiple materials contain such a field, they " "all need to be of same scalar type and same number of " "components. This does not work for split pixel cells or " "laminate pixel cells, as they can have multiple entries for the " "same pixel. Pixels for which no field named `unique_name` " "exists get an array of zeros." "\n" "Parameters:\n" "unique_name: fieldname to fill the global field with. At " "least one material must have such a field, or an " "Exception is raised.") .def("get_globalised_current_real_array", - &Cell::get_globalised_current_real_array, "unique_name"_a) + &muSpectre::Cell::get_globalised_current_real_array, "unique_name"_a) .def("get_globalised_old_real_array", - &Cell::get_globalised_old_real_array, "unique_name"_a, + &muSpectre::Cell::get_globalised_old_real_array, "unique_name"_a, "nb_steps_ago"_a = 1) - .def("get_managed_real_array", &Cell::get_managed_real_array, + .def("get_managed_real_array", &muSpectre::Cell::get_managed_real_array, "unique_name"_a, "nb_components"_a, "returns a field or nb_components real numbers per pixel"); - add_cell_base_helper(mod); - add_cell_base_helper(mod); + 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"; add_cell_base(cell); } diff --git a/language_bindings/python/bind_py_common.cc b/language_bindings/python/bind_py_common.cc index 520bf5d..4289614 100644 --- a/language_bindings/python/bind_py_common.cc +++ b/language_bindings/python/bind_py_common.cc @@ -1,151 +1,174 @@ /** * @file bind_py_common.cc * * @author Till Junge * * @date 08 Jan 2018 * * @brief Python bindings for the common part of µSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/common.hh" #include "common/ccoord_operations.hh" #include #include #include -using namespace muSpectre; // NOLINT // TODO(junge): figure this out +using muSpectre::Dim_t; +using muSpectre::Real; +using muSpectre::StressMeasure; +using muSpectre::StrainMeasure; +using muSpectre::Formulation; +using pybind11::literals::operator""_a; + namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage -template void add_get_cube_helper(py::module & mod) { +template +void add_get_cube_helper(py::module & mod) { std::stringstream name{}; name << "get_" << dim << "d_cube"; - mod.def(name.str().c_str(), &CcoordOps::get_cube, "size"_a, + mod.def(name.str().c_str(), &muSpectre::CcoordOps::get_cube, "size"_a, "return a Ccoord with the value 'size' repeated in each dimension"); } -template void add_get_hermitian_helper(py::module & mod) { - mod.def("get_hermitian_sizes", &CcoordOps::get_hermitian_sizes, - "full_sizes"_a, +template +void add_get_hermitian_helper(py::module & mod) { + mod.def("get_hermitian_sizes", + &muSpectre::CcoordOps::get_hermitian_sizes, "full_sizes"_a, "return the hermitian sizes corresponding to the true sizes"); } -template void add_get_ccoord_helper(py::module & mod) { - using Ccoord = Ccoord_t; +template +void add_get_ccoord_helper(py::module & mod) { + using Ccoord = muSpectre::Ccoord_t; mod.def( "get_domain_ccoord", [](Ccoord resolutions, Dim_t index) { - return CcoordOps::get_ccoord(resolutions, Ccoord{}, index); + return muSpectre::CcoordOps::get_ccoord(resolutions, Ccoord{}, + index); }, "resolutions"_a, "i"_a, "return the cell coordinate corresponding to the i'th cell in a grid of " "shape resolutions"); } void add_get_cube(py::module & mod) { - add_get_cube_helper(mod); - add_get_cube_helper(mod); - add_get_cube_helper(mod); - add_get_cube_helper(mod); + add_get_cube_helper(mod); + add_get_cube_helper(mod); + add_get_cube_helper(mod); + add_get_cube_helper(mod); - add_get_hermitian_helper(mod); - add_get_hermitian_helper(mod); + add_get_hermitian_helper(mod); + add_get_hermitian_helper(mod); - add_get_ccoord_helper(mod); - add_get_ccoord_helper(mod); + add_get_ccoord_helper(mod); + add_get_ccoord_helper(mod); } -template void add_get_index_helper(py::module & mod) { - using Ccoord = Ccoord_t; +template +void add_get_index_helper(py::module & mod) { + using Ccoord = muSpectre::Ccoord_t; mod.def("get_domain_index", [](Ccoord sizes, Ccoord ccoord) { - return CcoordOps::get_index(sizes, Ccoord{}, ccoord); + return muSpectre::CcoordOps::get_index(sizes, Ccoord{}, + ccoord); }, "sizes"_a, "ccoord"_a, "return the linear index corresponding to grid point 'ccoord' in a " "grid of size 'sizes'"); } void add_get_index(py::module & mod) { - add_get_index_helper(mod); - add_get_index_helper(mod); + add_get_index_helper(mod); + add_get_index_helper(mod); } -template void add_Pixels_helper(py::module & mod) { +template +void add_Pixels_helper(py::module & mod) { std::stringstream name{}; name << "Pixels" << dim << "d"; - using Ccoord = Ccoord_t; - py::class_> Pixels(mod, name.str().c_str()); + using Ccoord = muSpectre::Ccoord_t; + py::class_> Pixels(mod, name.str().c_str()); Pixels.def(py::init()); } void add_Pixels(py::module & mod) { - add_Pixels_helper(mod); - add_Pixels_helper(mod); + add_Pixels_helper(mod); + add_Pixels_helper(mod); } void add_common(py::module & mod) { py::enum_(mod, "Formulation") .value("finite_strain", Formulation::finite_strain) .value("small_strain", Formulation::small_strain); py::enum_(mod, "StressMeasure") .value("Cauchy", StressMeasure::Cauchy) .value("PK1", StressMeasure::PK1) .value("PK2", StressMeasure::PK2) .value("Kirchhoff", StressMeasure::Kirchhoff) .value("Biot", StressMeasure::Biot) .value("Mandel", StressMeasure::Mandel) .value("no_stress_", StressMeasure::no_stress_); py::enum_(mod, "StrainMeasure") .value("Gradient", StrainMeasure::Gradient) .value("Infinitesimal", StrainMeasure::Infinitesimal) .value("GreenLagrange", StrainMeasure::GreenLagrange) .value("Biot", StrainMeasure::Biot) .value("Log", StrainMeasure::Log) .value("Almansi", StrainMeasure::Almansi) .value("RCauchyGreen", StrainMeasure::RCauchyGreen) .value("LCauchyGreen", StrainMeasure::LCauchyGreen) .value("no_strain_", StrainMeasure::no_strain_); - py::enum_(mod, "FFT_PlanFlags") - .value("estimate", FFT_PlanFlags::estimate) - .value("measure", FFT_PlanFlags::measure) - .value("patient", FFT_PlanFlags::patient); - - mod.def("banner", &banner, "name"_a, "year"_a, "copyright_holder"_a); + py::enum_(mod, "FFT_PlanFlags") + .value("estimate", muSpectre::FFT_PlanFlags::estimate) + .value("measure", muSpectre::FFT_PlanFlags::measure) + .value("patient", muSpectre::FFT_PlanFlags::patient); + + py::enum_( + mod, "FiniteDiff", + "Distinguishes between different options of numerical differentiation;\n " + " 1) 'forward' finite differences: ∂f/∂x ≈ (f(x+Δx) - f(x))/Δx\n 2) " + "'backward' finite differences: ∂f/∂x ≈ (f(x) - f(x-Δx))/Δx\n 3) " + "'centred' finite differences: ∂f/∂x ≈ (f(x+Δx) - f(x-Δx))/2Δx") + .value("forward", muSpectre::FiniteDiff::forward) + .value("backward", muSpectre::FiniteDiff::backward) + .value("centred", muSpectre::FiniteDiff::centred); + + mod.def("banner", &muSpectre::banner, "name"_a, "year"_a, + "copyright_holder"_a); add_get_cube(mod); add_Pixels(mod); add_get_index(mod); } diff --git a/language_bindings/python/bind_py_fftengine.cc b/language_bindings/python/bind_py_fftengine.cc index 00044e6..56b1217 100644 --- a/language_bindings/python/bind_py_fftengine.cc +++ b/language_bindings/python/bind_py_fftengine.cc @@ -1,118 +1,122 @@ /** * @file bind_py_fftengine.cc * * @author Till Junge * * @date 17 Jan 2018 * * @brief Python bindings for the FFT engines * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/fftw_engine.hh" #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; // NOLINT // TODO(junge): figure this out +using muSpectre::Ccoord_t; +using muSpectre::Complex; +using muSpectre::Dim_t; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage template void add_engine_helper(py::module & mod, std::string name) { using Ccoord = Ccoord_t; using ArrayXXc = Eigen::Array; py::class_(mod, name.c_str()) #ifdef WITH_MPI .def(py::init([](Ccoord res, Dim_t nb_components, size_t comm) { return new Engine(res, nb_components, std::move(Communicator(MPI_Comm(comm)))); }), "resolutions"_a, "nb_components"_a, "communicator"_a = size_t(MPI_COMM_SELF)) #else .def(py::init()) #endif .def("fft", [](Engine & eng, py::EigenDRef v) { using Coll_t = typename Engine::GFieldCollection_t; using Field_t = typename Engine::Field_t; Coll_t coll{}; coll.initialise(eng.get_subdomain_resolutions(), eng.get_subdomain_locations()); - Field_t & temp{make_field("temp_field", coll, - eng.get_nb_components())}; + Field_t & temp{muSpectre::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, - eng.get_nb_components())}; + Field_t & temp{muSpectre::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) + "flags"_a = muSpectre::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, muSpectre::twoD>( + fft, "FFTW_2d"); + add_engine_helper, + muSpectre::threeD>(fft, "FFTW_3d"); #ifdef WITH_FFTWMPI 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"); #endif add_projections(fft); } diff --git a/language_bindings/python/bind_py_field_collection.cc b/language_bindings/python/bind_py_field_collection.cc index 79a8493..7d0c04d 100644 --- a/language_bindings/python/bind_py_field_collection.cc +++ b/language_bindings/python/bind_py_field_collection.cc @@ -1,269 +1,276 @@ /** * file bind_py_field_collection.cc * * @author Till Junge * * @date 05 Jul 2018 * * @brief Python bindings for µSpectre field collections * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/common.hh" #include "common/field.hh" #include "common/field_collection.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO(junge): figure this out +using muSpectre::Complex; +using muSpectre::Dim_t; +using muSpectre::Int; +using muSpectre::Real; +using muSpectre::Uint; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage + template void add_field_collection(py::module & mod) { std::stringstream name_stream{}; name_stream << "_" << (FieldCollectionDerived::Global ? "Global" : "Local") << "FieldCollection_" << Dim << 'd'; const auto name{name_stream.str()}; - using FC_t = FieldCollectionBase; + using FC_t = muSpectre::FieldCollectionBase; py::class_(mod, name.c_str()) .def("get_real_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_int_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field(unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_uint_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_complex_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_real_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_int_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_uint_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_complex_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def_property_readonly( "field_names", &FC_t::get_field_names, "returns the names of all fields in this collection") .def_property_readonly("statefield_names", &FC_t::get_statefield_names, "returns the names of all state fields in this " "collection"); } namespace internal_fill { /** * Needed for static switch when adding fillers to fields (static * switch on whether they are global). Default case is for global * fields. */ - template struct FillHelper { + template + struct FillHelper { static void add_fill(PyField & py_field) { py_field.def( "fill_from_local", [](Field & field, const typename Field::LocalField_t & local) { field.fill_from_local(local); }, "local"_a, "Fills the content of a local field into a global field " "(modifies only the pixels that are not present in the " "local field"); } }; /** * Specialisation for local fields */ template struct FillHelper { static void add_fill(PyField & py_field) { py_field.def( "fill_from_global", [](Field & field, const typename Field::GlobalField_t & global) { field.fill_from_global(global); }, "global"_a, "Fills the content of a global field into a local field."); } }; } // namespace internal_fill template void add_field(py::module & mod, std::string dtype_name) { - using Field_t = TypedField; + using Field_t = muSpectre::TypedField; std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "Field" << dtype_name << "_" << FieldCollection::spatial_dim(); std::string name{name_stream.str()}; using Ref_t = py::EigenDRef>; py::class_ py_field(mod, name.c_str()); py_field .def_property("array", [](Field_t & field) { return field.eigen(); }, [](Field_t & field, Ref_t mat) { field.eigen() = mat; }, "array of stored data") .def_property_readonly( "array", [](const Field_t & field) { return field.eigen(); }, "array of stored data") .def_property("vector", [](Field_t & field) { return field.eigenvec(); }, [](Field_t & field, Ref_t mat) { field.eigen() = mat; }, "flattened array of stored data") .def_property_readonly( "vector", [](const Field_t & field) { return field.eigenvec(); }, "flattened array of stored data"); using FillHelper_t = internal_fill::FillHelper; FillHelper_t::add_fill(py_field); } template void add_field_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "Field" << "_" << Dim; std::string name{name_stream.str()}; - using Field_t = internal::FieldBase; + using Field_t = muSpectre::internal::FieldBase; py::class_(mod, name.c_str()) .def_property_readonly("name", &Field_t::get_name, "field name") .def_property_readonly("collection", &Field_t::get_collection, "Collection containing this field") .def_property_readonly("nb_components", &Field_t::get_nb_components, "number of scalars stored per pixel in this field") .def_property_readonly("stored_type", [](const Field_t & field) { return field.get_stored_typeid().name(); }, "fundamental type of scalars stored in this field") .def_property_readonly("size", &Field_t::size, "number of pixels in this field") .def("set_zero", &Field_t::set_zero, "Set all components in the field to zero"); add_field(mod, "Real"); add_field(mod, "Int"); } template void add_statefield(py::module & mod, std::string dtype_name) { - using StateField_t = TypedStateField; + using StateField_t = muSpectre::TypedStateField; std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "StateField" << dtype_name << "_" << FieldCollection::spatial_dim(); std::string name{name_stream.str()}; py::class_(mod, name.c_str()) .def_property_readonly("current_field", &StateField_t::get_current_field, "returns the current field value") .def("get_old_field", &StateField_t::get_old_field, "nb_steps_ago"_a = 1, "returns the value this field held 'nb_steps_ago' steps ago", py::return_value_policy::reference_internal); } template void add_statefield_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "StateField" << "_" << Dim; std::string name{name_stream.str()}; - using StateField_t = StateFieldBase; + using StateField_t = muSpectre::StateFieldBase; py::class_(mod, name.c_str()) .def_property_readonly("prefix", &StateField_t::get_prefix, "state field prefix") .def_property_readonly("collection", &StateField_t::get_collection, "Collection containing this field") .def_property_readonly("nb_memory", &StateField_t::get_nb_memory, "number of old states stored") .def_property_readonly( "stored_type", [](const StateField_t & field) { return field.get_stored_typeid().name(); }, "fundamental type of scalars stored in this field"); add_statefield(mod, "Real"); add_statefield(mod, "Int"); } -template void add_field_collection_helper(py::module & mod) { - add_field_helper>(mod); - add_field_helper>(mod); +template +void add_field_collection_helper(py::module & mod) { + add_field_helper>(mod); + add_field_helper>(mod); - add_statefield_helper>(mod); - add_statefield_helper>(mod); + add_statefield_helper>(mod); + add_statefield_helper>(mod); - add_field_collection>(mod); - add_field_collection>(mod); + add_field_collection>(mod); + add_field_collection>(mod); } void add_field_collections(py::module & mod) { - add_field_collection_helper(mod); - add_field_collection_helper(mod); + add_field_collection_helper(mod); + add_field_collection_helper(mod); } diff --git a/language_bindings/python/bind_py_material.cc b/language_bindings/python/bind_py_material.cc index bea1956..c58c987 100644 --- a/language_bindings/python/bind_py_material.cc +++ b/language_bindings/python/bind_py_material.cc @@ -1,146 +1,245 @@ /** * @file bind_py_material.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief python bindings for µSpectre's materials * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/common.hh" #include "materials/material_base.hh" +#include "materials/material_evaluator.hh" + #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO(junge): figure this out +using muSpectre::Dim_t; +using muSpectre::Real; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage /* ---------------------------------------------------------------------- */ -template void add_material_linear_elastic1_helper(py::module & mod); -template void add_material_linear_elastic2_helper(py::module & mod); -template void add_material_linear_elastic3_helper(py::module & mod); -template void add_material_linear_elastic4_helper(py::module & mod); +template +void add_material_linear_elastic_generic1_helper(py::module & mod); +/* ---------------------------------------------------------------------- */ +template +void add_material_linear_elastic_generic2_helper(py::module & mod); + +/** + * python binding for the optionally objective form of Hooke's law + */ +template +void add_material_linear_elastic1_helper(py::module & mod); +template +void add_material_linear_elastic2_helper(py::module & mod); +template +void add_material_linear_elastic3_helper(py::module & mod); +template +void add_material_linear_elastic4_helper(py::module & mod); template void add_material_hyper_elasto_plastic1_helper(py::module & mod); template void add_material_crystal_plasticity_finite1_helper(py::module & mod); /* ---------------------------------------------------------------------- */ -template class PyMaterialBase : public MaterialBase { +template +class PyMaterialBase : public muSpectre::MaterialBase { public: /* Inherit the constructors */ - using Parent = MaterialBase; + using Parent = muSpectre::MaterialBase; using Parent::Parent; /* Trampoline (need one for each virtual function) */ void save_history_variables() override { - PYBIND11_OVERLOAD_PURE(void, /* Return type */ - Parent, /* Parent class */ + PYBIND11_OVERLOAD_PURE(void, // Return type + Parent, // Parent class save_history_variables); // Name of function in C++ // (must match Python name) } /* Trampoline (need one for each virtual function) */ void initialise() override { PYBIND11_OVERLOAD_PURE( void, // Return type Parent, // Parent class initialise); // Name of function in C++ (must match Python name) } void compute_stresses(const typename Parent::StrainField_t & F, typename Parent::StressField_t & P, - Formulation form) override { + muSpectre::Formulation form) override { PYBIND11_OVERLOAD_PURE( - void, /* Return type */ - Parent, /* Parent class */ - compute_stresses, /* Name of function in C++ (must match Python name) */ + void, // Return type + Parent, // Parent class + compute_stresses, // Name of function in C++ (must match Python name) F, P, form); } void compute_stresses_tangent(const typename Parent::StrainField_t & F, typename Parent::StressField_t & P, typename Parent::TangentField_t & K, - Formulation form) override { + muSpectre::Formulation form) override { PYBIND11_OVERLOAD_PURE( void, /* Return type */ Parent, /* Parent class */ compute_stresses, /* Name of function in C++ (must match Python name) */ F, P, K, form); } }; -template void add_material_helper(py::module & mod) { +template +void add_material_evaluator(py::module & mod) { + std::stringstream name_stream{}; + name_stream << "MaterialEvaluator_" << Dim << "d"; + std::string name{name_stream.str()}; + + using MatEval_t = muSpectre::MaterialEvaluator; + py::class_(mod, name.c_str()) + .def(py::init>>()) + .def("save_history_variables", &MatEval_t::save_history_variables, + "for materials with state variables") + .def("evaluate_stress", + [](MatEval_t & mateval, py::EigenDRef & grad, + muSpectre::Formulation form) { + if ((grad.cols() != Dim) or (grad.rows() != Dim)) { + std::stringstream err{}; + err << "need matrix of shape (" << Dim << "×" << Dim + << ") but got (" << grad.rows() << "×" + << grad.cols() << ")."; + throw std::runtime_error(err.str()); + } + return mateval.evaluate_stress(grad, form); + }, + "strain"_a, "formulation"_a, + "Evaluates stress for a given strain and formulation " + "(Piola-Kirchhoff 1 stress as a function of the placement gradient " + "P = P(F) for formulation=Formulation.finite_strain and Cauchy " + "stress as a function of the infinitesimal strain tensor σ = σ(ε) " + "for formulation=Formulation.small_strain)") + .def("evaluate_stress_tangent", + [](MatEval_t & mateval, py::EigenDRef & grad, + muSpectre::Formulation form) { + if ((grad.cols() != Dim) or (grad.rows() != Dim)) { + std::stringstream err{}; + err << "need matrix of shape (" << Dim << "×" << Dim + << ") but got (" << grad.rows() << "×" + << grad.cols() << ")."; + throw std::runtime_error(err.str()); + } + return mateval.evaluate_stress_tangent(grad, form); + }, + "strain"_a, "formulation"_a, + "Evaluates stress and tangent moduli for a given strain and " + "formulation (Piola-Kirchhoff 1 stress as a function of the " + "placement gradient P = P(F) for " + "formulation=Formulation.finite_strain and Cauchy stress as a " + "function of the infinitesimal strain tensor σ = σ(ε) for " + "formulation=Formulation.small_strain). The tangent moduli are K = " + "∂P/∂F for formulation=Formulation.finite_strain and C = ∂σ/∂ε for " + "formulation=Formulation.small_strain.") + .def("estimate_tangent", + [](MatEval_t & evaluator, py::EigenDRef & grad, + muSpectre::Formulation form, const Real step, + const muSpectre::FiniteDiff diff_type) { + if ((grad.cols() != Dim) or (grad.rows() != Dim)) { + std::stringstream err{}; + err << "need matrix of shape (" << Dim << "×" << Dim + << ") but got (" << grad.rows() << "×" + << grad.cols() << ")."; + throw std::runtime_error(err.str()); + } + return evaluator.estimate_tangent(grad, form, step, diff_type); + }, + "strain"_a, "formulation"_a, "Delta_x"_a, + "difference_type"_a = muSpectre::FiniteDiff::centred, + "Numerical estimate of the tangent modulus using finite " + "differences. The finite difference scheme as well as the finite " + "step size can be chosen. If there are no special circumstances, " + "the default scheme of centred finite differences yields the most " + "accurate results at an increased computational cost."); +} + +template +void add_material_helper(py::module & mod) { std::stringstream name_stream{}; - name_stream << "MaterialBase_" << dim << "d"; + name_stream << "MaterialBase_" << Dim << "d"; std::string name{name_stream.str()}; - using Material = MaterialBase; - using MaterialTrampoline = PyMaterialBase; - using FC_t = LocalFieldCollection; - using FCBase_t = FieldCollectionBase; + using Material = muSpectre::MaterialBase; + using MaterialTrampoline = PyMaterialBase; + using FC_t = muSpectre::LocalFieldCollection; + using FCBase_t = muSpectre::FieldCollectionBase; - py::class_(mod, + py::class_>(mod, name.c_str()) .def(py::init()) .def("save_history_variables", &Material::save_history_variables) .def("list_fields", &Material::list_fields) .def("get_real_field", &Material::get_real_field, "field_name"_a, py::return_value_policy::reference_internal) .def("size", &Material::size) .def("add_pixel", - [](Material & mat, Ccoord_t pix) { mat.add_pixel(pix); }, + [](Material & mat, muSpectre::Ccoord_t pix) { + mat.add_pixel(pix); + }, "pixel"_a) .def_property_readonly("collection", [](Material & material) -> FCBase_t & { return material.get_collection(); }, "returns the field collection containing internal " "fields of this material"); - add_material_linear_elastic1_helper(mod); - add_material_linear_elastic2_helper(mod); - add_material_linear_elastic3_helper(mod); - add_material_linear_elastic4_helper(mod); - add_material_hyper_elasto_plastic1_helper(mod); + add_material_linear_elastic1_helper(mod); + add_material_linear_elastic2_helper(mod); + add_material_linear_elastic3_helper(mod); + add_material_linear_elastic4_helper(mod); + add_material_hyper_elasto_plastic1_helper(mod); + add_material_linear_elastic_generic1_helper(mod); + add_material_linear_elastic_generic2_helper(mod); + + add_material_evaluator(mod); } void add_material(py::module & mod) { auto material{mod.def_submodule("material")}; material.doc() = "bindings for constitutive laws"; - add_material_helper(material); - add_material_helper(material); - add_material_crystal_plasticity_finite1_helper(material); - add_material_crystal_plasticity_finite1_helper(material); - add_material_crystal_plasticity_finite1_helper(material); + add_material_helper(material); + add_material_helper(material); + + add_material_crystal_plasticity_finite1_helper(material); + add_material_crystal_plasticity_finite1_helper(material); + add_material_crystal_plasticity_finite1_helper( + material); } diff --git a/language_bindings/python/bind_py_material_crystal_plasticity_finite.cc b/language_bindings/python/bind_py_material_crystal_plasticity_finite.cc index 640c7f6..4d16445 100644 --- a/language_bindings/python/bind_py_material_crystal_plasticity_finite.cc +++ b/language_bindings/python/bind_py_material_crystal_plasticity_finite.cc @@ -1,116 +1,117 @@ /** * @file bind_py_material_crystal_plasticity_finite.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python binding for MaterialCrystalPlasticityFinite * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/stress_transformations_PK2.hh" #include "materials/material_crystal_plasticity_finite.hh" #include "cell/cell_base.hh" #include #include #include #include #include using namespace muSpectre; // NOLINT // TODO: junge namespace py = pybind11; using namespace pybind11::literals; // NOLINT recommended usage /** * python binding for the standard crystal plasticity model of Francesco */ template void add_material_crystal_plasticity_finite1_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialCrystalPlasticityFinite_" << dim << "d_" << NbSlip << "slip"; const auto name{name_stream.str()}; using Mat_t = MaterialCrystalPlasticityFinite; using Sys_t = CellBase; - py::class_>(mod, name.c_str()) + py::class_, std::shared_ptr>( + mod, name.c_str()) .def_static("make", [](Sys_t & sys, std::string n, Real bulk_modulus, Real shear_modulus, Real gamma_dot_0, Real m, Real tau_y0, Real h0, Real delta_tau_y_max, Real a, Real q_n, py::EigenDRef slip, py::EigenDRef normals, Real delta_t, Real tolerance, Int maxiter) -> Mat_t & { auto check = [](auto && mat, auto && name) { if (not((mat.rows() == NbSlip) and (mat.cols() == dim))) { std::stringstream err{}; err << "The " << name << " need to be given in the form of a " << NbSlip << "×" << dim << " matrix, but you gave a " << mat.rows() << "×" << mat.cols() << " matrix."; throw std::runtime_error(err.str()); } }; check(slip, "slip directions"); check(normals, "normals to slip planes"); Eigen::Matrix real_slip{slip}; Eigen::Matrix real_normals{normals}; return Mat_t::make( sys, n, bulk_modulus, shear_modulus, gamma_dot_0, m, tau_y0, h0, delta_tau_y_max, a, q_n, real_slip, real_normals, delta_t, tolerance, maxiter); }, "cell"_a, "name"_a, "bulk_modulus"_a, "shear_modulus"_a, "dγ/dt₀"_a, "m_exonent"_a, "tau_y₀"_a, "h₀"_a, "Δτ_y_max"_a, "a_exponent"_a, "qₙ"_a, "slip_directions"_a, "normals"_a, "Δt"_a, "tolerance"_a = 1.e-4, "max_iter"_a = 20, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", [](Mat_t & mat, Ccoord_t pix, py::EigenDRef euler) { auto check = [](auto && mat, auto && name) { if (not((mat.rows() == NbSlip) and (mat.cols() == 1))) { std::stringstream err{}; err << "The " << name << " need to be given in the form of a " << Mat_t::NbEuler << "×" << 1 << " matrix, but you gave a " << mat.rows() << "×" << mat.cols() << " matrix."; throw std::runtime_error(err.str()); } }; check(euler, "euler angles"); Eigen::Matrix real_euler{euler}; mat.add_pixel(pix, real_euler); }, "pixel"_a, "euler_angles"_a); } template void add_material_crystal_plasticity_finite1_helper(py::module &); template void add_material_crystal_plasticity_finite1_helper(py::module &); template void add_material_crystal_plasticity_finite1_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc b/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc index a5c3529..6f022e0 100644 --- a/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc +++ b/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc @@ -1,69 +1,78 @@ /** * @file bind_py_material_hyper_elasto_plastic1.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python binding for MaterialHyperElastoPlastic1 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/stress_transformations_Kirchhoff.hh" #include "materials/material_hyper_elasto_plastic1.hh" #include "cell/cell_base.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO: junge +using muSpectre::Dim_t; +using muSpectre::Real; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended usage /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_hyper_elasto_plastic1_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialHyperElastoPlastic1_" << Dim << "d"; const auto name{name_stream.str()}; - using Mat_t = MaterialHyperElastoPlastic1; - using Cell_t = CellBase; + using Mat_t = muSpectre::MaterialHyperElastoPlastic1; + using Cell_t = muSpectre::CellBase; - py::class_>(mod, name.c_str()) + py::class_, std::shared_ptr>( + mod, name.c_str()) .def_static("make", [](Cell_t & cell, std::string name, Real Young, Real Poisson, Real tau_y0, Real h) -> Mat_t & { return Mat_t::make(cell, name, Young, Poisson, tau_y0, h); }, "cell"_a, "name"_a, "YoungModulus"_a, "PoissonRatio"_a, "τ_y₀"_a, "h"_a, py::return_value_policy::reference, - py::keep_alive<1, 0>()); + py::keep_alive<1, 0>()) + .def_static("make_evaluator", + [](Real Young, Real Poisson, Real tau_y0, Real h) { + return Mat_t::make_evaluator(Young, Poisson, tau_y0, h); + }, + "YoungModulus"_a, "PoissonRatio"_a, "τ_y₀"_a, "h"_a); } -template void add_material_hyper_elasto_plastic1_helper(py::module &); -template void add_material_hyper_elasto_plastic1_helper(py::module &); +template void +add_material_hyper_elasto_plastic1_helper(py::module &); +template void +add_material_hyper_elasto_plastic1_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic1.cc b/language_bindings/python/bind_py_material_linear_elastic1.cc index 10b334f..7a6996b 100644 --- a/language_bindings/python/bind_py_material_linear_elastic1.cc +++ b/language_bindings/python/bind_py_material_linear_elastic1.cc @@ -1,64 +1,74 @@ /** * @file bind_py_material_linear_elastic1.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic1 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/material_linear_elastic1.hh" #include "cell/cell_base.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO: junge +using muSpectre::Dim_t; +using muSpectre::Real; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended usage + /** * python binding for the optionally objective form of Hooke's law */ template void add_material_linear_elastic1_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic1_" << dim << 'd'; const auto name{name_stream.str()}; - using Mat_t = MaterialLinearElastic1; - using Sys_t = CellBase; - py::class_>(mod, name.c_str()) + using Mat_t = muSpectre::MaterialLinearElastic1; + using Sys_t = muSpectre::CellBase; + py::class_, std::shared_ptr>( + mod, name.c_str()) .def_static("make", [](Sys_t & sys, std::string n, Real e, Real p) -> Mat_t & { return Mat_t::make(sys, n, e, p); }, "cell"_a, "name"_a, "Young"_a, "Poisson"_a, - py::return_value_policy::reference, py::keep_alive<1, 0>()); + py::return_value_policy::reference, py::keep_alive<1, 0>()) + .def_static("make_evaluator", + [](Real e, Real p) { + return Mat_t::make_evaluator(e, p); + }, + "Young"_a, "Poisson"_a); } -template void add_material_linear_elastic1_helper(py::module &); -template void add_material_linear_elastic1_helper(py::module &); +template void +add_material_linear_elastic1_helper(py::module &); +template void +add_material_linear_elastic1_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic2.cc b/language_bindings/python/bind_py_material_linear_elastic2.cc index 3db1c35..a1fb000 100644 --- a/language_bindings/python/bind_py_material_linear_elastic2.cc +++ b/language_bindings/python/bind_py_material_linear_elastic2.cc @@ -1,73 +1,83 @@ /** * @file bind_py_material_linear_elastic2.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic2 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/material_linear_elastic2.hh" #include "cell/cell_base.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO: junge +using muSpectre::Dim_t; +using muSpectre::Real; + namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended usage +using pybind11::literals::operator""_a; /** * python binding for the optionally objective form of Hooke's law * with a per pixel eigenstrain */ template void add_material_linear_elastic2_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic2_" << dim << 'd'; const auto name{name_stream.str()}; - using Mat_t = MaterialLinearElastic2; - using Sys_t = CellBase; + using Mat_t = muSpectre::MaterialLinearElastic2; + using Sys_t = muSpectre::CellBase; - py::class_>(mod, name.c_str()) + py::class_, std::shared_ptr>( + mod, name.c_str()) .def_static("make", [](Sys_t & sys, std::string n, Real e, Real p) -> Mat_t & { return Mat_t::make(sys, n, e, p); }, "cell"_a, "name"_a, "Young"_a, "Poisson"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", - [](Mat_t & mat, Ccoord_t pix, + [](Mat_t & mat, muSpectre::Ccoord_t pix, py::EigenDRef & eig) { Eigen::Matrix eig_strain{eig}; mat.add_pixel(pix, eig_strain); }, - "pixel"_a, "eigenstrain"_a); + "pixel"_a, "eigenstrain"_a) + .def_static("make_evaluator", + [](Real e, Real p) { + return Mat_t::make_evaluator(e, p); + }, + "Young"_a, "Poisson"_a); } -template void add_material_linear_elastic2_helper(py::module &); -template void add_material_linear_elastic2_helper(py::module &); +template void +add_material_linear_elastic2_helper(py::module &); +template void +add_material_linear_elastic2_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic3.cc b/language_bindings/python/bind_py_material_linear_elastic3.cc index ecd758c..d11346b 100644 --- a/language_bindings/python/bind_py_material_linear_elastic3.cc +++ b/language_bindings/python/bind_py_material_linear_elastic3.cc @@ -1,72 +1,77 @@ /** * @file bind_py_material_linear_elastic3.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic3 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/material_linear_elastic3.hh" #include "cell/cell_base.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO: junge +using muSpectre::Dim_t; +using muSpectre::Real; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended usage /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_linear_elastic3_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic3_" << dim << 'd'; const auto name{name_stream.str()}; - using Mat_t = MaterialLinearElastic3; - using Sys_t = CellBase; + using Mat_t = muSpectre::MaterialLinearElastic3; + using Sys_t = muSpectre::CellBase; - py::class_>(mod, name.c_str()) + py::class_, std::shared_ptr>( + mod, name.c_str()) .def(py::init(), "name"_a) .def_static("make", [](Sys_t & sys, std::string n) -> Mat_t & { return Mat_t::make(sys, n); }, "cell"_a, "name"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", - [](Mat_t & mat, Ccoord_t pix, Real Young, Real Poisson) { - mat.add_pixel(pix, Young, Poisson); - }, - "pixel"_a, "Young"_a, "Poisson"_a); + [](Mat_t & mat, muSpectre::Ccoord_t pix, Real Young, + Real Poisson) { mat.add_pixel(pix, Young, Poisson); }, + "pixel"_a, "Young"_a, "Poisson"_a) + .def_static("make_evaluator", + []() { return Mat_t::make_evaluator(); }); } -template void add_material_linear_elastic3_helper(py::module &); -template void add_material_linear_elastic3_helper(py::module &); +template void +add_material_linear_elastic3_helper(py::module &); +template void +add_material_linear_elastic3_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic4.cc b/language_bindings/python/bind_py_material_linear_elastic4.cc index 50550ac..6134460 100644 --- a/language_bindings/python/bind_py_material_linear_elastic4.cc +++ b/language_bindings/python/bind_py_material_linear_elastic4.cc @@ -1,72 +1,77 @@ /** * @file bind_py_material_linear_elastic4.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python binding for MaterialLinearElastic4 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "materials/material_linear_elastic4.hh" #include "cell/cell_base.hh" #include #include #include #include #include -using namespace muSpectre; // NOLINT // TODO: junge +using muSpectre::Dim_t; +using muSpectre::Real; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended usage /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_linear_elastic4_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic4_" << dim << 'd'; const auto name{name_stream.str()}; - using Mat_t = MaterialLinearElastic4; - using Sys_t = CellBase; + using Mat_t = muSpectre::MaterialLinearElastic4; + using Sys_t = muSpectre::CellBase; - py::class_>(mod, name.c_str()) + py::class_, std::shared_ptr>( + mod, name.c_str()) .def(py::init(), "name"_a) .def_static("make", [](Sys_t & sys, std::string n) -> Mat_t & { return Mat_t::make(sys, n); }, "cell"_a, "name"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", - [](Mat_t & mat, Ccoord_t pix, Real Young, Real Poisson) { - mat.add_pixel(pix, Young, Poisson); - }, - "pixel"_a, "Young"_a, "Poisson"_a); + [](Mat_t & mat, muSpectre::Ccoord_t pix, Real Young, + Real Poisson) { mat.add_pixel(pix, Young, Poisson); }, + "pixel"_a, "Young"_a, "Poisson"_a) + .def_static("make_evaluator", + []() { return Mat_t::make_evaluator(); }); } -template void add_material_linear_elastic4_helper(py::module &); -template void add_material_linear_elastic4_helper(py::module &); +template void +add_material_linear_elastic4_helper(py::module &); +template void +add_material_linear_elastic4_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic_generic.cc b/language_bindings/python/bind_py_material_linear_elastic_generic.cc new file mode 100644 index 0000000..9ca6771 --- /dev/null +++ b/language_bindings/python/bind_py_material_linear_elastic_generic.cc @@ -0,0 +1,150 @@ +/** + * @file bind_py_material_linear_elastic_generic.cc + * + * @author Till Junge + * + * @date 20 Dec 2018 + * + * @brief bindings for the generic linear elastic law defined by its stiffness + * tensor + * + * Copyright © 2018 Till Junge + * + * µSpectre is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µSpectre is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µSpectre; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#include "materials/material_linear_elastic_generic1.hh" +#include "materials/material_linear_elastic_generic2.hh" +#include "cell/cell_base.hh" + +#include +#include +#include + +#include +#include + +using namespace muSpectre; // NOLINT // TODO(junge): figure this out +namespace py = pybind11; +using namespace pybind11::literals; // NOLINT: recommended usage + +/** + * python binding for the generic linear elastic material + */ +template +void add_material_linear_elastic_generic1_helper(py::module & mod) { + std::stringstream name_stream{}; + name_stream << "MaterialLinearElasticGeneric1_" << Dim << "d"; + const auto name{name_stream.str()}; + + using Mat_t = MaterialLinearElasticGeneric1; + using Cell_t = CellBase; + + py::class_, std::shared_ptr>( + mod, name.c_str()) + .def_static( + "make", + [](Cell_t & cell, std::string name, + const py::EigenDRef< + Eigen::Matrix> & + elastic_tensor) -> Mat_t & { + return Mat_t::make(cell, name, elastic_tensor); + }, + "cell"_a, "name"_a, "elastic_tensor"_a, + py::return_value_policy::reference, py::keep_alive<1, 0>(), + "Factory function returning a MaterialLinearElastic instance. " + "The elastic tensor has to be specified in Voigt notation.") + .def("add_pixel", + [](Mat_t & mat, Ccoord_t pix) { mat.add_pixel(pix); }, + "pixel"_a, + "Register a new pixel to this material. subsequent evaluations of " + "the " + "stress and tangent in the cell will use this constitutive law for " + "this " + "particular pixel") + .def("size", &Mat_t::size) + .def_static("make_evaluator", + [](const py::EigenDRef< + Eigen::Matrix> & + elastic_tensor) { + return Mat_t::make_evaluator(elastic_tensor); + }, + "elastic_tensor"_a); +} + +/** + * python binding for the generic linear elastic material with eigenstcain + */ +template +void add_material_linear_elastic_generic2_helper(py::module & mod) { + std::stringstream name_stream{}; + name_stream << "MaterialLinearElasticGeneric2_" << Dim << "d"; + const auto name{name_stream.str()}; + + using Mat_t = MaterialLinearElasticGeneric2; + using Cell_t = CellBase; + + py::class_, std::shared_ptr>( + mod, name.c_str()) + .def_static( + "make", + [](Cell_t & cell, std::string name, + const py::EigenDRef< + Eigen::Matrix> & + elastic_tensor) -> Mat_t & { + return Mat_t::make(cell, name, elastic_tensor); + }, + "cell"_a, "name"_a, "elastic_tensor"_a, + py::return_value_policy::reference, py::keep_alive<1, 0>(), + "Factory function returning a MaterialLinearElastic instance. " + "The elastic tensor has to be specified in Voigt notation.") + .def("add_pixel", + [](Mat_t & mat, Ccoord_t pix) { mat.add_pixel(pix); }, + "pixel"_a, + "Register a new pixel to this material. Subsequent evaluations of " + "the stress and tangent in the cell will use this constitutive law " + "for this particular pixel") + .def("add_pixel", + [](Mat_t & mat, Ccoord_t pix, + py::EigenDRef & eig) { + Eigen::Matrix eig_strain{eig}; + mat.add_pixel(pix, eig_strain); + }, + "pixel"_a, "eigenstrain"_a, + "Register a new pixel to this material and assign the eigenstrain. " + "Subsequent Evaluations of the stress and tangent in the cell will " + "use this constitutive law for this particular pixel") + .def("size", &Mat_t::size) + .def_static("make_evaluator", + [](const py::EigenDRef< + Eigen::Matrix> & + elastic_tensor) { + return Mat_t::make_evaluator(elastic_tensor); + }, + "elastic_tensor"_a); +} + +template void add_material_linear_elastic_generic1_helper(py::module &); +template void add_material_linear_elastic_generic1_helper(py::module &); +template void add_material_linear_elastic_generic2_helper(py::module &); +template void add_material_linear_elastic_generic2_helper(py::module &); diff --git a/language_bindings/python/bind_py_module.cc b/language_bindings/python/bind_py_module.cc index e0bf9e7..1530281 100644 --- a/language_bindings/python/bind_py_module.cc +++ b/language_bindings/python/bind_py_module.cc @@ -1,51 +1,48 @@ /** * @file bind_py_module.cc * * @author Till Junge * * @date 12 Jan 2018 * * @brief Python bindings for µSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "bind_py_declarations.hh" #include -using namespace pybind11::literals; // NOLINT: recommended use -namespace py = pybind11; - PYBIND11_MODULE(_muSpectre, mod) { mod.doc() = "Python bindings to the µSpectre library"; add_common(mod); add_cell(mod); add_material(mod); add_solvers(mod); add_fft_engines(mod); add_field_collections(mod); } diff --git a/language_bindings/python/bind_py_projections.cc b/language_bindings/python/bind_py_projections.cc index 36d0268..ec82f6b 100644 --- a/language_bindings/python/bind_py_projections.cc +++ b/language_bindings/python/bind_py_projections.cc @@ -1,183 +1,191 @@ /** * @file bind_py_projections.cc * * @author Till Junge * * @date 18 Jan 2018 * * @brief Python bindings for the Projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/projection_small_strain.hh" #include "fft/projection_finite_strain.hh" #include "fft/projection_finite_strain_fast.hh" #include "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; // NOLINT // TODO(junge): figure this out +using muSpectre::Dim_t; +using muSpectre::ProjectionBase; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage /** * "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 Ccoord = muSpectre::Ccoord_t; + using Rcoord = muSpectre::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, 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>( + 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, 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, 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, + .def("initialise", &Proj::initialise, + "flags"_a = muSpectre::FFT_PlanFlags::estimate, "initialises the fft engine (plan the transform)") .def("apply_projection", [](Proj & proj, py::EigenDRef v) { - typename FFTEngineBase::GFieldCollection_t coll{}; - Eigen::Index subdomain_size = - CcoordOps::get_size(proj.get_subdomain_resolutions()); + typename muSpectre::FFTEngineBase::GFieldCollection_t coll{}; + Eigen::Index subdomain_size = muSpectre::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, - proj.get_nb_components())}; + Field_t & temp{muSpectre::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, twoD>( - mod, "ProjectionSmallStrain"); - add_proj_helper, threeD>( - mod, "ProjectionSmallStrain"); - - add_proj_helper, twoD>( - mod, "ProjectionFiniteStrain"); - add_proj_helper, threeD>( - mod, "ProjectionFiniteStrain"); - - add_proj_helper, twoD>( - mod, "ProjectionFiniteStrainFast"); - add_proj_helper, threeD>( - mod, "ProjectionFiniteStrainFast"); + add_proj_helper< + muSpectre::ProjectionSmallStrain, + muSpectre::twoD>(mod, "ProjectionSmallStrain"); + add_proj_helper< + muSpectre::ProjectionSmallStrain, + muSpectre::threeD>(mod, "ProjectionSmallStrain"); + + add_proj_helper< + muSpectre::ProjectionFiniteStrain, + muSpectre::twoD>(mod, "ProjectionFiniteStrain"); + add_proj_helper< + muSpectre::ProjectionFiniteStrain, + muSpectre::threeD>(mod, "ProjectionFiniteStrain"); + + add_proj_helper< + muSpectre::ProjectionFiniteStrainFast, + muSpectre::twoD>(mod, "ProjectionFiniteStrainFast"); + add_proj_helper, + muSpectre::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 2dddd31..40be085 100644 --- a/language_bindings/python/bind_py_solvers.cc +++ b/language_bindings/python/bind_py_solvers.cc @@ -1,139 +1,147 @@ /** * @file bind_py_solver.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief python bindings for the muSpectre solvers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/common.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" #include "solver/solver_eigen.hh" #include #include #include -using namespace muSpectre; // NOLINT // TODO(junge): figure this out +using muSpectre::Dim_t; +using muSpectre::OptimizeResult; +using muSpectre::Real; +using muSpectre::Uint; +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT: recommended usage /** * Solvers instanciated for cells with equal spatial and material dimension */ template void add_iterative_solver_helper(py::module & mod, std::string name) { py::class_(mod, name.c_str()) - .def(py::init(), "cell"_a, "tol"_a, "maxiter"_a, - "verbose"_a = false) + .def(py::init(), "cell"_a, "tol"_a, + "maxiter"_a, "verbose"_a = false) .def("name", &Solver::get_name); } void add_iterative_solver(py::module & mod) { std::stringstream name{}; name << "SolverBase"; - py::class_(mod, name.str().c_str()); - add_iterative_solver_helper(mod, "SolverCG"); - add_iterative_solver_helper(mod, "SolverCGEigen"); - add_iterative_solver_helper(mod, "SolverGMRESEigen"); - add_iterative_solver_helper(mod, "SolverBiCGSTABEigen"); - add_iterative_solver_helper(mod, "SolverDGMRESEigen"); - add_iterative_solver_helper(mod, "SolverMINRESEigen"); + py::class_(mod, name.str().c_str()); + add_iterative_solver_helper(mod, "SolverCG"); + add_iterative_solver_helper(mod, "SolverCGEigen"); + add_iterative_solver_helper(mod, + "SolverGMRESEigen"); + add_iterative_solver_helper( + mod, "SolverBiCGSTABEigen"); + add_iterative_solver_helper( + mod, "SolverDGMRESEigen"); + add_iterative_solver_helper( + mod, "SolverMINRESEigen"); } void add_newton_cg_helper(py::module & mod) { const char name[]{"newton_cg"}; - using solver = SolverBase; + using solver = muSpectre::SolverBase; using grad = py::EigenDRef; - using grad_vec = LoadSteps_t; + using grad_vec = muSpectre::LoadSteps_t; mod.def(name, - [](Cell & s, const grad & g, solver & so, Real nt, Real eqt, - Dim_t verb) -> OptimizeResult { + [](muSpectre::Cell & s, const grad & g, solver & so, Real nt, + Real eqt, Dim_t verb) -> OptimizeResult { Eigen::MatrixXd tmp{g}; return newton_cg(s, tmp, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equil_tol"_a, "verbose"_a = 0); mod.def(name, - [](Cell & s, const grad_vec & g, solver & so, Real nt, Real eqt, - Dim_t verb) -> std::vector { + [](muSpectre::Cell & s, const grad_vec & g, solver & so, Real nt, + Real eqt, Dim_t verb) -> std::vector { return newton_cg(s, g, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); } void add_de_geus_helper(py::module & mod) { const char name[]{"de_geus"}; - using solver = SolverBase; + using solver = muSpectre::SolverBase; using grad = py::EigenDRef; - using grad_vec = LoadSteps_t; + using grad_vec = muSpectre::LoadSteps_t; mod.def(name, - [](Cell & s, const grad & g, solver & so, Real nt, Real eqt, - Dim_t verb) -> OptimizeResult { + [](muSpectre::Cell & s, const grad & g, solver & so, Real nt, + Real eqt, Dim_t verb) -> OptimizeResult { Eigen::MatrixXd tmp{g}; return de_geus(s, tmp, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); mod.def(name, - [](Cell & s, const grad_vec & g, solver & so, Real nt, Real eqt, - Dim_t verb) -> std::vector { + [](muSpectre::Cell & s, const grad_vec & g, solver & so, Real nt, + Real eqt, Dim_t verb) -> std::vector { return de_geus(s, g, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); } void add_solver_helper(py::module & mod) { add_newton_cg_helper(mod); add_de_geus_helper(mod); } void add_solvers(py::module & mod) { auto solvers{mod.def_submodule("solvers")}; solvers.doc() = "bindings for solvers"; py::class_(mod, "OptimizeResult") .def_readwrite("grad", &OptimizeResult::grad) .def_readwrite("stress", &OptimizeResult::stress) .def_readwrite("success", &OptimizeResult::success) .def_readwrite("status", &OptimizeResult::status) .def_readwrite("message", &OptimizeResult::message) .def_readwrite("nb_it", &OptimizeResult::nb_it) - .def_readwrite("nb_fev", &OptimizeResult::nb_fev); + .def_readwrite("nb_fev", &OptimizeResult::nb_fev) + .def_readwrite("formulation", &OptimizeResult::formulation); add_iterative_solver(solvers); add_solver_helper(solvers); } diff --git a/language_bindings/python/muSpectre/__init__.py b/language_bindings/python/muSpectre/__init__.py index cf0c580..b778d54 100644 --- a/language_bindings/python/muSpectre/__init__.py +++ b/language_bindings/python/muSpectre/__init__.py @@ -1,103 +1,105 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file __init__.py @author Lars Pastewka @date 21 Mar 2018 @brief Main entry point for muSpectre Python module Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU General Lesser Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ try: from mpi4py import MPI except ImportError: MPI = None import _muSpectre from _muSpectre import (Formulation, get_domain_ccoord, get_domain_index, - get_hermitian_sizes, material, solvers) + get_hermitian_sizes, material, solvers, + FFT_PlanFlags, FiniteDiff) import muSpectre.fft +import muSpectre.gradient_integration _factories = {'fftw': ('CellFactory', False), 'fftwmpi': ('FFTWMPICellFactory', True), 'pfft': ('PFFTCellFactory', True), 'p3dfft': ('P3DFFTCellFactory', True)} def Cell(resolutions, lengths, formulation=Formulation.finite_strain, fft='fftw', communicator=None): """ Instantiate a muSpectre Cell class. Parameters ---------- resolutions: list Grid resolutions in the Cartesian directions. lengths: list Physical size of the cell in the Cartesian directions. formulation: Formulation Formulation for strains and stresses used by the solver. Options are `Formulation.finite_strain` and `Formulation.small_strain`. Finite strain formulation is the default. 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, is_parallel = _factories[fft] except KeyError: raise KeyError("Unknown FFT engine '{}'.".format(fft)) try: factory = _muSpectre.__dict__[factory_name] except KeyError: raise KeyError("FFT engine '{}' has not been compiled into the " "muSpectre library.".format(fft)) 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, lengths, formulation, MPI._handleof(communicator)) else: if communicator is not None: raise ValueError("FFT engine '{}' does not support parallel " "execution.".format(fft)) return factory(resolutions, lengths, formulation) diff --git a/language_bindings/python/muSpectre/gradient_integration.py b/language_bindings/python/muSpectre/gradient_integration.py new file mode 100644 index 0000000..e12a0ea --- /dev/null +++ b/language_bindings/python/muSpectre/gradient_integration.py @@ -0,0 +1,366 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file gradient_integration.py + +@author Till Junge + +@date 22 Nov 2018 + +@brief Functions for the integration of periodic first- and second-rank + tensor fields on an n-dimensional rectangular grid + +Copyright © 2018 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + +import numpy as np +import sys +from . import Formulation + +def compute_wave_vectors(lengths, resolutions): + """Computes the wave vectors for a dim-dimensional rectangular or + cubic (or hypercubic) grid as a function of the edge lengths and + resolutions. + + Note: the norm of the wave vectors corresponds to the angular + velocity, not the frequency. + + Keyword Arguments: + lengths -- np.ndarray of length dim with the edge lengths in each + spatial dimension (dtype = float) + resolutions -- np.ndarray of length dim with the resolutions in each + spatial dimension (dtype = int) + + Returns: + np.ndarary of shape resolutions + [dim]. The wave vector for a + given pixel/voxel is given in the last dimension + + """ + return np.moveaxis(np.meshgrid( + *[2*np.pi*np.fft.fftfreq(r, l/r) for l,r in zip(lengths, resolutions)], + indexing="ij"), 0, -1) + +def compute_grid(lengths, resolutions): + """For a dim-dimensional pixel/voxel grid, computes the pixel/voxel + centre and corner positions as a function of the grid's edge + lengths and resolutions + + Keyword Arguments: + lengths -- np.ndarray of length dim with the edge lengths in each + spatial dimension (dtype = float) + resolutions -- np.ndarray of length dim with the resolutions in each + spatial dimension (dtype = int) + Returns: + tuple((x_n, x_c)) two ndarrays with nodal/corner positions and + centre positions respectively. x_n has one more entry in every + direction than the resolution of the grid (added points correspond + to the periodic repetitions) + + """ + x_n = np.moveaxis(np.meshgrid( + *[np.linspace(0, l, r+1) for l,r in zip(lengths, resolutions)], + indexing="ij"), 0 ,-1) + dx = lengths/resolutions + + x_c = np.moveaxis(np.meshgrid( + *[np.linspace(0, l, r, endpoint=False) for l,r in + zip(lengths, resolutions)], + indexing="ij"), 0, -1) + .5*dx + + return x_n, x_c + +def reshape_gradient(F, resolutions): + """reshapes a flattened second-rank tensor into a multidimensional array of + shape resolutions + [dim, dim]. + + Note: this reshape entails a copy, because of the column-major to + row-major transposition between Eigen and numpy + + Keyword Arguments: + F -- flattenen array of gradients as in OptimizeResult + resolutions -- np.ndarray of length dim with the resolutions in each + spatial dimension (dtype = int) + + Returns: + np.ndarray + """ + + dim = len(resolutions) + if not isinstance(resolutions, list): + raise Exception("resolutions needs to be in list form, "+ + "for concatenation") + expected_input_shape = [np.prod(resolutions) * dim**2] + output_shape = resolutions + [dim, dim] + if not ((F.shape[0] == expected_input_shape[0]) and + (F.size == expected_input_shape[0])): + raise Exception("expected gradient of shape {}, got {}".format( + expected_input_shape, F.shape)) + + order = list(range(dim+2)) + order[-2:] = reversed(order[-2:]) + return F.reshape(output_shape).transpose(*order) + +def complement_periodically(array, dim): + """Takes an arbitrary multidimensional array of at least dimension dim + and returns an augmented copy with periodic copies of the + left/lower entries in the added right/upper boundaries + + Keyword Arguments: + array -- arbitrary np.ndarray of at least dim dimensions + dim -- nb of dimension to complement periodically + + """ + shape = list(array.shape) + shape[:dim] = [d+1 for d in shape[:dim]] + out_arr = np.empty(shape, dtype = array.dtype) + sl = tuple([slice(0, s) for s in array.shape]) + out_arr[sl] = array + + for i in range(dim): + lower_slice = tuple([slice(0,s) if (d != i) else 0 for (d,s) in + enumerate(shape)]) + upper_slice = tuple([slice(0,s) if (d != i) else -1 for (d,s) in + enumerate(shape)]) + out_arr[upper_slice] = out_arr[lower_slice] + + return out_arr + + +def get_integrator(x, freqs, order=0): + """returns the discrete Fourier-space integration operator as a + function of the position grid (used to determine the spatial + dimension and resolution), the wave vectors, and the integration + order + + Keyword Arguments: + x -- np.ndarray of pixel/voxel centre positons in shape + resolution + [dim] + freqs -- wave vectors as computed by compute_wave_vectors + order -- (default 0) integration order. 0 stands for exact integration + + Returns: + (dim, shape, integrator) + """ + dim = x.shape[-1] + shape = x.shape[:-1] + delta_x = x[tuple([1]*dim)] - x[tuple([0]*dim)] + def correct_denom(denom): + """Corrects the denominator to avoid division by zero + for freqs = 0 and on even grids for freqs*delta_x=pi.""" + denom[tuple([0]*dim)] = 1. + for i, n in enumerate(shape): + if n%2 == 0: + denom[tuple([np.s_[:]]*i + [n//2] + [np.s_[:]]*(dim-1-i))] = 1. + return denom[..., np.newaxis] + if order == 0: + freqs_norm_square = np.einsum("...i, ...i -> ...", freqs, freqs) + freqs_norm_square.reshape(-1)[0] = 1. + integrator = 1j * freqs/freqs_norm_square[...,np.newaxis] + # Higher order corrections after: + # A. Vidyasagar et al., Computer Methods in Applied Mechanics and + # Engineering 106 (2017) 133-151, sec. 3.4 and Appendix C. + # and + # P. Eisenlohr et al., International Journal of Plasticity 46 (2013) + # 37-53, Appendix B, eq. 23. + elif order == 1: + sin_1 = np.sin(freqs*delta_x) + denom = correct_denom((sin_1**2).sum(axis=-1)) + integrator = 1j*delta_x*sin_1 / denom + elif order == 2: + sin_1, sin_2 = 8*np.sin(freqs*delta_x), np.sin(2*freqs*delta_x) + denom = correct_denom((sin_1**2).sum(axis=-1) - (sin_2**2).sum(axis=-1)) + integrator = 1j*6*delta_x*(sin_1+sin_2) / denom + else: + raise Exception("order '{}' is not implemented".format(order)) + return dim, shape, integrator + + +def integrate_tensor_2(grad, x, freqs, staggered_grid=False, order=0): + """Integrates a second-rank tensor gradient field to a chosen order as + a function of the given field, the grid positions, and wave + vectors. Optionally, the integration can be performed on the + pixel/voxel corners (staggered grid). + + Keyword Arguments: + grad -- np.ndarray of shape resolution + [dim, dim] containing the + second-rank gradient to be integrated + x -- np.ndarray of shape resolution + [dim] (or augmented + resolution + [dim]) containing the pixel/voxel centre + positions (for un-staggered grid integration) or the pixel + /voxel corner positions (for staggered grid integration) + freqs -- wave vectors as computed by compute_wave_vectors + staggered_grid -- (default False) if set to True, the integration is + performed on the pixel/voxel corners, rather than the + centres. This leads to a different integration scheme + order -- (default 0) integration order. + 0 stands for exact integration + + Returns: + np.ndarray contaning the integrated field + """ + + dim, shape, integrator = get_integrator(x, freqs, order) + + axes = range(dim) + grad_k = np.fft.fftn(grad, axes=axes) + f_k = np.einsum("...j, ...ij -> ...i", integrator, grad_k) + normalisation = np.prod(grad.shape[:dim]) + grad_k_0 = grad_k[tuple((0 for _ in range(dim)))].real/normalisation + homogeneous = np.einsum("ij, ...j -> ...i", + grad_k_0, x) + if not staggered_grid: + fluctuation = -np.fft.ifftn(f_k, axes=axes).real + else: + del_x = (x[tuple((1 for _ in range(dim)))] - + x[tuple((0 for _ in range(dim)))]) + k_del_x = np.einsum("...i, i ->...", freqs, del_x)[...,np.newaxis] + if order == 0: + shift = np.exp(-1j * k_del_x/2) + elif order == 1: + shift = (np.exp(-1j * k_del_x) + 1) / 2 + elif order == 2: + shift = np.exp(-1j*k_del_x/2) * np.cos(k_del_x/2) *\ + (np.cos(k_del_x) - 4) / (np.cos(k_del_x/2) - 4) + fluctuation = complement_periodically( + -np.fft.ifftn(shift*f_k, axes=axes).real, dim) + + return fluctuation + homogeneous + + +def integrate_vector(df, x, freqs, staggered_grid=False, order=0): + """Integrates a first-rank tensor gradient field to a chosen order as + a function of the given field, the grid positions, and wave + vectors. Optionally, the integration can be performed on the + pixel/voxel corners (staggered_grid) + + Keyword Arguments: + df -- np.ndarray of shape resolution + [dim] containing the + first-rank tensor gradient to be integrated + x -- np.ndarray of shape resolution + [dim] (or augmented + resolution + [dim]) containing the pixel/voxel centre + positions (for un-staggered grid integration) or the pixel + /voxel corner positions (for staggered grid integration) + freqs -- wave vectors as computed by compute_wave_vectors + staggered_grid -- (default False) if set to True, the integration is + performed on the pixel/voxel corners, rather than the + centres. This leads to a different integration scheme... + order -- (default 0) integration order. + 0 stands for exact integration + + Returns: + np.ndarray contaning the integrated field + """ + dim, shape, integrator = get_integrator(x, freqs, order) + + axes = range(dim) + df_k = np.fft.fftn(df, axes=axes) + f_k = np.einsum("...i, ...i -> ...", df_k, integrator) + df_k_0 = df_k[tuple((0 for _ in range(dim)))].real + homogeneous = np.einsum("i, ...i -> ...", df_k_0, x/np.prod(shape)) + + if not staggered_grid: + fluctuation = -np.fft.ifftn(f_k, axes=axes).real + else: + del_x = x[tuple((1 for _ in range(dim)))] \ + - x[tuple((0 for _ in range(dim)))] + k_del_x = np.einsum("...i, i ->...", freqs, del_x) + if order == 0: + shift = np.exp(-1j * k_del_x/2) + elif order == 1: + shift = (np.exp(-1j * k_del_x) + 1) / 2 + elif order == 2: + shift = np.exp(-1j*k_del_x/2) * np.cos(k_del_x/2) *\ + (np.cos(k_del_x) - 4) / (np.cos(k_del_x/2) - 4) + fluctuation = complement_periodically( + -np.fft.ifftn(shift*f_k, axes=axes).real, dim) + + return fluctuation + homogeneous + + +def compute_placement(result, lengths, resolutions, order=0, formulation=None): + """computes the placement (the sum of original position and + displacement) as a function of a OptimizeResult, domain edge + lengths, domain discretisation resolutions, the chosen + integration order and the continuum mechanics description(small or finite + strain description) + + Keyword Arguments: + result -- OptimiseResult, or just the grad field of an OptimizeResult + lengths -- np.ndarray of length dim with the edge lengths in each + spatial dimension (dtype = float) + resolutions -- np.ndarray of length dim with the resolutions in each + spatial dimension (dtype = int) + order -- (default 0) integration order. 0 stands for exact integration + formulation -- (default None) the formulation is derived from the + OptimiseResult argument. If this is not possible you have to + fix the formulation to either Formulation.small_strain or + Formulation.finite_strain. + Returns: + (placement, x_n) tuple of ndarrays containing the placement and the + corresponding original positions + + """ + + lengths = np.array(lengths) + resolutions = np.array(resolutions) + + #Check whether result is a np.array or an OptimiseResult object + if isinstance(result, np.ndarray): + if formulation == None: + #exit the program, if the formulation is unknown! + raise ValueError('\n' + 'You have to specify your continuum mechanics description.\n' + 'Either you use a formulation="small_strain" or ' + '"finite_strain" description.\n' + 'Otherwise you can give a result=OptimiseResult object, which ' + 'tells me the formulation.') + form = formulation + grad = reshape_gradient(result, resolutions.tolist()) + else: + form = result.formulation + if form != formulation and formulation != None: + #exit the program, if the formulation is ambiguous! + raise ValueError('\nThe given formulation "{}" differs from the ' + 'one saved in your result "{}"!' + .format(formulation, form)) + grad = reshape_gradient(result.grad, resolutions.tolist()) + + #reshape the gradient depending on the formulation + if form == Formulation.small_strain: + raise NotImplementedError('\nIntegration of small strains' + 'is not implemented yet!') + elif form == Formulation.finite_strain: + grad = grad + else: + raise ValueError('\nThe formulation: "{}" is unknown!' + .format(formulation)) + + #compute the placement by integrating + x_n, x_c = compute_grid(lengths, resolutions) + freqs = compute_wave_vectors(lengths, resolutions) + placement = integrate_tensor_2(grad, x_n, freqs, + staggered_grid=True, order=order) + + return placement, x_n diff --git a/language_bindings/python/muSpectre/vtk_export.py b/language_bindings/python/muSpectre/vtk_export.py new file mode 100644 index 0000000..c771fdf --- /dev/null +++ b/language_bindings/python/muSpectre/vtk_export.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file vtk_export.py + +@author Till Junge + +@date 22 Nov 2018 + +@brief function for export of vtk files + +Copyright © 2018 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + +import numpy as np +from tvtk.api import tvtk, write_data + +def vtk_export(fpath, x_n, placement, point_data=None, cell_data=None, + legacy_ascii=False): + """write a vtr (vtk for rectilinear grids) file for visualisation of + µSpectre results. Optionally, a legacy ascii file can be written + (useful for debugging) + + Keyword Arguments: + fpath -- file name for output path *WITHOUT EXTENSION* + x_n -- nodal positions, as computed by + gradient_integration.compute_grid + placement -- nodal deformed placement as computed by + gradient_integration.compute_placement + point_data -- (default None) dictionary of point data. These must have + either of the following shapes: + a) tuple(x_n.shape[:dim]) + interpreted as scalar field, + b) tuple(x_n.shape[:dim] + [dim]) + interpreted as vector field, or + c) tuple(x_n.shape[:dim] + [dim, dim]) + interpreted as second-rank tensor field + cell_data -- (default None) dictionary of cell data. These must have + either of the following shapes: + a) tuple(x_c.shape[:dim]) + interpreted as scalar field, + b) tuple(x_c.shape[:dim] + [dim]) + interpreted as vector field, or + c) tuple(x_c.shape[:dim] + [dim, dim]) + interpreted as second-rank tensor field + where x_c is the array of pixel/voxel positions as computed + by gradient_integration.compute_grid + legacy_ascii -- (default False) If set to True, a human-readable, but larger + ascii file is written + + """ + dim = len(x_n.shape[:-1]) + if dim not in (2, 3): + raise Exception( + ("should be two- or three-dimensional, got positions for a {}-" + "dimensional problem").format(dim)) + res_n = list(x_n.shape[:-1]) + vtk_res = res_n if dim == 3 else res_n + [1] + res_c = [max(1, r-1) for r in res_n] + + # setting up the geometric grid + vtk_obj = tvtk.RectilinearGrid() + vtk_obj.dimensions = vtk_res + vtk_obj.x_coordinates = x_n[:,0,0] if dim == 2 else x_n[:,0,0,0] + vtk_obj.y_coordinates = x_n[0,:,1] if dim == 2 else x_n[0,:,0,1] + vtk_obj.z_coordinates = np.zeros_like( + vtk_obj.x_coordinates) if dim == 2 else x_n[0,0,:,2] + + # displacements are mandatory, so they get added independently of + # any additional point data + disp = np.zeros([np.prod(vtk_res), 3]) + disp[:,:dim] = (placement - x_n).reshape(-1, dim, order="F") + vtk_obj.point_data.vectors = disp + vtk_obj.point_data.vectors.name = "displacement" + + # check name clashes: + if point_data is None: + point_data = dict() + if cell_data is None: + cell_data = dict() + if "displacement" in point_data.keys(): + raise Exception("Name 'displacement' is reserved") + if "displacement" in cell_data.keys(): + raise Exception("Name 'displacement' is reserved") + #clash_set = set(point_data.keys()) & set(cell_data.keys()) + #if clash_set: + # clash_names = ["'{}'".format(name) for name in clash_set] + # clash_names_fmt = ", ".join(clash_names) + # raise Exception( + # ("Only unique names are allowed, but the names {} appear in both " + # "point- and cell data").format(clash_names_fmt)) + #Note: is this necessary -> only same name in same dictionary doesn't make sense. + # I think it's ok to have e.g. the material phase as cell and point data? + #Richard: I think the same, so I commented the check and would throw it away + + # helper functions to add data + def add_data(value, name, point=True): + data = vtk_obj.point_data if point else vtk_obj.cell_data + data.add_array(value) + data.get_array(data._get_number_of_arrays()-1).name = name + return + + def add_scalar(value, name, point=True): + add_data(value.reshape(-1, order="F"), name, point) + return + + def add_vector(value, name, point=True): + res = vtk_res if point else res_c + vec = np.zeros([np.prod(res), 3]) + vec[:,:dim] = value.reshape(-1, dim, order="F") + add_data(vec, name, point) + return + + def add_tensor(value, name, point=True): + res = vtk_res if point else res_c + tens = np.zeros([np.prod(res), 3, 3]) + tens[:,:dim, :dim] = value.reshape(-1, dim, dim, order="F") + add_data(tens.reshape(-1, 3*3), name, point) + return + + adders = {() : add_scalar, + (dim,) : add_vector, + (dim, dim): add_tensor} + + def shape_checker(value, reference): + """ + checks whether values have the right shape and determines the + appropriate function to add them to the output file + """ + res = value.shape[:dim] + shape = value.shape[dim:] + if not res == tuple(reference[:dim]): + raise Exception( + ("the first dim dimensions of dataset '{}' have the wrong size," + " should be {}, but got {}").format( + key, reference[:dim], res)) + if not shape in (adders.keys()): + raise Exception( + ("Can only handle scalar, vectorial, and tensorial fields, but " + "got a field of shape {}").format(shape)) + return res, shape, adders[shape] + + # add point data + for key, value in point_data.items(): + res, shape, adder = shape_checker(value, res_n) + adder(value, key, point=True) + + # add cell data + for key, value in cell_data.items(): + res, shape, adder = shape_checker(value, res_c) + adder(value, key, point=False) + + path = fpath + (".vtk" if legacy_ascii else "") + + write_data(vtk_obj, path) + return vtk_obj diff --git a/src/cell/cell_base.hh b/src/cell/cell_base.hh index 77770a8..465d26e 100644 --- a/src/cell/cell_base.hh +++ b/src/cell/cell_base.hh @@ -1,672 +1,676 @@ /** * @file cell_base.hh * * @author Till Junge * * @date 01 Nov 2017 * * @brief Base class representing a unit cell cell with single * projection operator * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_CELL_CELL_BASE_HH_ #define SRC_CELL_CELL_BASE_HH_ #include "common/common.hh" #include "common/ccoord_operations.hh" #include "common/field.hh" #include "common/utilities.hh" #include "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; //! dynamic generic array type for interaction with numpy, i/o, etc template using Array_t = Eigen::Array; //! ref to dynamic generic array template using Array_ref = Eigen::Map>; //! ref to constant vector using ConstVector_ref = Eigen::Map; //! output vector reference for solvers using Vector_ref = Eigen::Map; //! Default constructor Cell() = default; //! Copy constructor Cell(const Cell & other) = default; //! Move constructor Cell(Cell && other) = default; //! Destructor virtual ~Cell() = default; //! Copy assignment operator Cell & operator=(const Cell & other) = default; //! Move assignment operator Cell & operator=(Cell && other) = default; //! for handling double initialisations right bool is_initialised() const { return this->initialised; } //! returns the number of degrees of freedom in the cell virtual Dim_t get_nb_dof() const = 0; //! number of pixels in the cell virtual size_t size() const = 0; //! return the communicator object virtual const Communicator & get_communicator() const = 0; /** * formulation is hard set by the choice of the projection class */ virtual const Formulation & get_formulation() const = 0; /** * returns the material dimension of the problem */ virtual Dim_t get_material_dim() const = 0; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ virtual std::array get_strain_shape() const = 0; /** * returns a writable map onto the strain field of this cell. This * corresponds to the unknowns in a typical solve cycle. */ virtual Vector_ref get_strain_vector() = 0; /** * returns a read-only map onto the stress field of this * cell. This corresponds to the intermediate (and finally, total) * solution in a typical solve cycle */ virtual ConstVector_ref get_stress_vector() const = 0; /** * evaluates and returns the stress for the currently set strain */ virtual ConstVector_ref evaluate_stress() = 0; /** * evaluates and returns the stress and stiffness for the currently set * strain */ virtual std::array evaluate_stress_tangent() = 0; /** * applies the projection operator in-place on the input vector */ virtual void apply_projection(Eigen::Ref vec) = 0; /** * evaluates the projection of the input field (this corresponds - * do G:P in de Geus 2017, + * to G:P in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). The first time, * this allocates the memory for the return value, and reuses it * on subsequent calls */ virtual Vector_ref evaluate_projection(Eigen::Ref P) = 0; /** * freezes all the history variables of the materials */ virtual void save_history_variables() = 0; /** * evaluates the directional and projected stiffness (this * corresponds to G:K:δF in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). It seems that * this operation needs to be implemented with a copy in oder to * be compatible with scipy and EigenCG etc (At the very least, * the copy is only made once) */ virtual Vector_ref evaluate_projected_directional_stiffness( Eigen::Ref delF) = 0; /** * returns a ref to a field named 'unique_name" of real values * managed by the cell. If the field does not yet exist, it is * created. * * @param unique_name name of the field. If the field already * exists, an array ref mapped onto it is returned. Else, a new * field with that name is created and returned- * * @param nb_components number of components to be stored *per * pixel*. For new fields any positive number can be chosen. When * accessing an existing field, this must correspond to the * existing field size, and a `std::runtime_error` is thrown if * this is not satisfied */ virtual Array_ref get_managed_real_array(std::string unique_name, size_t nb_components) = 0; /** * Convenience function to copy local (internal) fields of * materials into a global field. At least one of the materials in * the cell needs to contain an internal field named * `unique_name`. If multiple materials contain such a field, they * all need to be of same scalar type and same number of * components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * * @param unique_name fieldname to fill the global field with. At * least one material must have such a field, or a * `std::runtime_error` is thrown */ virtual Array_ref get_globalised_internal_real_array(const std::string & unique_name) = 0; /** * Convenience function to copy local (internal) state fields * (current state) of materials into a global field. At least one * of the materials in the cell needs to contain an internal field * named `unique_name`. If multiple materials contain such a * field, they all need to be of same scalar type and same number * of components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * * @param unique_name fieldname to fill the global field with. At * least one material must have such a field, or a * `std::runtime_error` is thrown */ virtual Array_ref get_globalised_current_real_array(const std::string & unique_name) = 0; /** * Convenience function to copy local (internal) state fields * (old state) of materials into a global field. At least one * of the materials in the cell needs to contain an internal field * named `unique_name`. If multiple materials contain such a * field, they all need to be of same scalar type and same number * of components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * - * @param unique_name fieldname to fill the global field with. At - * least one material must have such a field, or a - * `std::runtime_error` is thrown + * @param unique_name fieldname to fill the global field with. At least one + * material must have such a field, or a `std::runtime_error` is thrown + * @param nb_steps_ago for history variables which remember more than a + * single previous value, `nb_steps_ago` can be used to specify which old + * value to access. */ virtual Array_ref get_globalised_old_real_array(const std::string & unique_name, int nb_steps_ago = 1) = 0; /** * set uniform strain (typically used to initialise problems */ virtual void set_uniform_strain(const Eigen::Ref &) = 0; //! get a sparse matrix view on the cell virtual Adaptor get_adaptor() = 0; protected: bool initialised{false}; //!< to handle double initialisation right private: }; //! DimS spatial dimension (dimension of problem //! DimM material_dimension (dimension of constitutive law) - template class CellBase : public Cell { + template + class CellBase : public Cell { public: using Parent = Cell; using Ccoord = Ccoord_t; //!< cell coordinates type using Rcoord = Rcoord_t; //!< physical coordinates type //! global field collection using FieldCollection_t = GlobalFieldCollection; //! the collection is handled in a `std::unique_ptr` using Collection_ptr = std::unique_ptr; //! polymorphic base material type using Material_t = MaterialBase; //! materials handled through `std::unique_ptr`s using Material_ptr = std::unique_ptr; //! polymorphic base projection type using Projection_t = ProjectionBase; //! projections handled through `std::unique_ptr`s using Projection_ptr = std::unique_ptr; //! dynamic global fields template using Field_t = TypedField; //! 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; //! dynamic vector type for interactions with numpy/scipy/solvers etc. using Vector_t = typename Parent::Vector_t; //! ref to constant vector using ConstVector_ref = typename Parent::ConstVector_ref; //! output vector reference for solvers using Vector_ref = typename Parent::Vector_ref; //! dynamic array type for interactions with numpy/scipy/solvers, etc. template using Array_t = typename Parent::Array_t; //! dynamic array type for interactions with numpy/scipy/solvers, etc. template using Array_ref = typename Parent::Array_ref; //! sparse matrix emulation using Adaptor = Parent::Adaptor; //! Default constructor CellBase() = delete; //! constructor using sizes and resolution explicit CellBase(Projection_ptr projection); //! Copy constructor CellBase(const CellBase & other) = delete; //! Move constructor CellBase(CellBase && other); //! Destructor virtual ~CellBase() = default; //! Copy assignment operator CellBase & operator=(const CellBase & other) = delete; //! Move assignment operator CellBase & operator=(CellBase && other) = default; /** * Materials can only be moved. This is to assure exclusive * ownership of any material by this cell */ Material_t & add_material(Material_ptr mat); /** * returns a writable map onto the strain field of this cell. This * corresponds to the unknowns in a typical solve cycle. */ Vector_ref get_strain_vector() override; /** * returns a read-only map onto the stress field of this * cell. This corresponds to the intermediate (and finally, total) * solution in a typical solve cycle */ ConstVector_ref get_stress_vector() const override; /** * evaluates and returns the stress for the currently set strain */ ConstVector_ref evaluate_stress() override; /** * evaluates and returns the stress and stiffness for the currently set * strain */ std::array evaluate_stress_tangent() override; /** * evaluates the projection of the input field (this corresponds * do G:P in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). The first time, * this allocates the memory for the return value, and reuses it * on subsequent calls */ - Vector_ref evaluate_projection(Eigen::Ref P) override; + Vector_ref + evaluate_projection(Eigen::Ref P) override; /** * evaluates the directional and projected stiffness (this * corresponds to G:K:δF in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). It seems that * this operation needs to be implemented with a copy in oder to * be compatible with scipy and EigenCG etc. (At the very least, * the copy is only made once) */ Vector_ref evaluate_projected_directional_stiffness( Eigen::Ref delF) override; //! return the template param DimM (required for polymorphic use of `Cell` Dim_t get_material_dim() const final { return DimM; } /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; /** * applies the projection operator in-place on the input vector */ void apply_projection(Eigen::Ref vec) final; /** * 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 */ Vector_ref directional_stiffness_vec(const Eigen::Ref & delF); /** * Evaluate directional stiffness into a temporary array and * return a copy. This is a costly and wasteful interface to * directional_stiffness and should only be used for debugging or * in the python interface */ Eigen::ArrayXXd directional_stiffness_with_copy(Eigen::Ref delF); /** * Convenience function circumventing the neeed to use the * underlying projection */ StressField_t & project(StressField_t & field); //! returns a ref to the cell's strain field StrainField_t & get_strain(); //! returns a ref to the cell's stress field const StressField_t & get_stress() const; //! returns a ref to the cell's tangent stiffness field const TangentField_t & get_tangent(bool create = false); //! returns a ref to a temporary field managed by the cell StrainField_t & get_managed_T2_field(std::string unique_name); //! returns a ref to a temporary field of real values managed by the cell Field_t & get_managed_real_field(std::string unique_name, size_t nb_components); /** * returns a Array ref to a temporary field of real values managed by the * cell */ Array_ref get_managed_real_array(std::string unique_name, size_t nb_components) final; /** - * returns a global field filled from local (internal) statefields of - * the materials. see `Cell::get_globalised_current_real_array` for + * returns a global field filled from local (internal) fields of + * the materials. see `Cell::get_globalised_internal_real_array` for * details. */ Field_t & get_globalised_internal_real_field(const std::string & unique_name); /** * returns a global field filled from local (internal) statefields of * the materials. see `Cell::get_globalised_current_real_array` for * details. */ Field_t & get_globalised_current_real_field(const std::string & unique_name); /** * returns a global field filled from local (internal) statefields of * the materials. see `Cell::get_globalised_old_real_array` for * details. */ Field_t & get_globalised_old_real_field(const std::string & unique_name, int nb_steps_ago = 1); //! see `Cell::get_globalised_internal_real_array` for details - Array_ref - get_globalised_internal_real_array(const std::string & unique_name) final; + Array_ref get_globalised_internal_real_array( + const std::string & unique_name) final; //! see `Cell::get_globalised_current_reald_array` for details - Array_ref - get_globalised_current_real_array(const std::string & unique_name) final; + Array_ref get_globalised_current_real_array( + const std::string & unique_name) final; //! see `Cell::get_globalised_old_real_array` for details Array_ref get_globalised_old_real_array(const std::string & unique_name, int nb_steps_ago = 1) final; /** * general initialisation; initialises the projection and * fft_engine (i.e. infrastructure) but not the materials. These * need to be initialised separately */ void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate); /** * for materials with state variables, these typically need to be * saved/updated an the end of each load increment, this function * calls this update for each material in the cell */ void save_history_variables() final; iterator begin(); //!< iterator to the first pixel iterator end(); //!< iterator past the last pixel //! number of pixels in the cell size_t size() const final { return pixels.size(); } //! return the subdomain resolutions of the cell const Ccoord & get_subdomain_resolutions() const { return this->subdomain_resolutions; } //! return the subdomain locations of the cell const Ccoord & get_subdomain_locations() const { return this->subdomain_locations; } //! return the domain resolutions of the cell const Ccoord & get_domain_resolutions() const { return this->domain_resolutions; } //! return the sizes of the cell const Rcoord & get_domain_lengths() const { return this->domain_lengths; } /** * formulation is hard set by the choice of the projection class */ const Formulation & get_formulation() const final { return this->projection->get_formulation(); } /** * get a reference to the projection object. should only be * required for debugging */ Eigen::Map get_projection() { return this->projection->get_operator(); } //! returns the spatial size constexpr static Dim_t get_sdim() { return DimS; } //! return a sparse matrix adaptor to the cell Adaptor get_adaptor() override; //! returns the number of degrees of freedom in the cell Dim_t get_nb_dof() const override { return this->size() * ipow(DimS, 2); }; //! return the communicator object const Communicator & get_communicator() const override { return this->projection->get_communicator(); } protected: template Field_t & globalised_field_helper(const std::string & unique_name, int nb_steps_ago); //! make sure that every pixel is assigned to one and only one material 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 private: }; /** * lightweight resource handle wrapping a `muSpectre::Cell` or * a subclass thereof into `Eigen::EigenBase`, so it can be * interpreted as a sparse matrix by Eigen solvers */ template class CellAdaptor : public Eigen::EigenBase> { public: using Scalar = double; //!< sparse matrix traits using RealScalar = double; //!< sparse matrix traits using StorageIndex = int; //!< sparse matrix traits enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic, RowsAtCompileTime = Eigen::Dynamic, MaxRowsAtCompileTime = Eigen::Dynamic, IsRowMajor = false }; //! constructor explicit CellAdaptor(Cell & cell) : cell{cell} {} //! returns the number of logical rows Eigen::Index rows() const { return this->cell.get_nb_dof(); } //! returns the number of logical columns Eigen::Index cols() const { return this->rows(); } //! implementation of the evaluation template Eigen::Product operator*(const Eigen::MatrixBase & x) const { return Eigen::Product( *this, x.derived()); } Cell & cell; //!< ref to the cell }; } // namespace muSpectre namespace Eigen { namespace internal { //! Implementation of `muSpectre::CellAdaptor` * `Eigen::DenseVector` //! through a specialization of `Eigen::internal::generic_product_impl`: - template + template // GEMV stands for matrix-vector struct generic_product_impl // GEMV stands for matrix-vector + GemvProduct> : generic_product_impl_base> { //! undocumented typedef typename Product::Scalar Scalar; //! undocumented template static void scaleAndAddTo(Dest & dst, const CellAdaptor & lhs, const Rhs & rhs, const Scalar & /*alpha*/) { // This method should implement "dst += alpha * lhs * rhs" inplace, // however, for iterative solvers, alpha is always equal to 1, so // let's not bother about it. // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs, dst.noalias() += const_cast(lhs) .cell.evaluate_projected_directional_stiffness(rhs); } }; } // namespace internal } // namespace Eigen #endif // SRC_CELL_CELL_BASE_HH_ diff --git a/src/common/T4_map_proxy.hh b/src/common/T4_map_proxy.hh index 94b4a83..b9c378c 100644 --- a/src/common/T4_map_proxy.hh +++ b/src/common/T4_map_proxy.hh @@ -1,104 +1,106 @@ /** * @file T4_map_proxy.hh * * @author Till Junge * * @date 19 Nov 2017 * * @brief Map type to allow fourth-order tensor-like maps on 2D matrices * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_T4_MAP_PROXY_HH_ #define SRC_COMMON_T4_MAP_PROXY_HH_ #include "common/eigen_tools.hh" #include #include #include namespace muSpectre { /** * simple adapter function to create a matrix that can be mapped as a tensor */ template using T4Mat = Eigen::Matrix; /** * Map onto `muSpectre::T4Mat` */ template using T4MatMap = std::conditional_t>, Eigen::Map>>; - template struct DimCounter {}; + template + struct DimCounter {}; - template struct DimCounter> { + template + struct DimCounter> { private: using Type = Eigen::MatrixBase; constexpr static Dim_t Rows{Type::RowsAtCompileTime}; public: static_assert(Rows != Eigen::Dynamic, "matrix type not statically sized"); static_assert(Rows == Type::ColsAtCompileTime, "matrix type not square"); constexpr static Dim_t value{ct_sqrt(Rows)}; static_assert(value * value == Rows, "Only integer numbers of dimensions allowed"); }; /** * provides index-based access to fourth-order Tensors represented * by square matrices */ template inline auto get(const Eigen::MatrixBase & t4, Dim_t i, Dim_t j, Dim_t k, Dim_t l) -> decltype(auto) { constexpr Dim_t Dim{DimCounter>::value}; const auto myColStride{(t4.colStride() == 1) ? t4.colStride() : t4.colStride() / Dim}; const auto myRowStride{(t4.rowStride() == 1) ? t4.rowStride() : t4.rowStride() / Dim}; return t4(i * myRowStride + j * myColStride, k * myRowStride + l * myColStride); } template inline auto get(Eigen::MatrixBase & t4, Dim_t i, Dim_t j, Dim_t k, Dim_t l) -> decltype(t4.coeffRef(i, j)) { constexpr Dim_t Dim{DimCounter>::value}; const auto myColStride{(t4.colStride() == 1) ? t4.colStride() : t4.colStride() / Dim}; const auto myRowStride{(t4.rowStride() == 1) ? t4.rowStride() : t4.rowStride() / Dim}; return t4.coeffRef(i * myRowStride + j * myColStride, k * myRowStride + l * myColStride); } } // namespace muSpectre #endif // SRC_COMMON_T4_MAP_PROXY_HH_ diff --git a/src/common/ccoord_operations.hh b/src/common/ccoord_operations.hh index f4d7ec4..231b549 100644 --- a/src/common/ccoord_operations.hh +++ b/src/common/ccoord_operations.hh @@ -1,331 +1,333 @@ /** * @file ccoord_operations.hh * * @author Till Junge * * @date 29 Sep 2017 * * @brief common operations on pixel addressing * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include #include #include "common/common.hh" #include "common/iterators.hh" #ifndef SRC_COMMON_CCOORD_OPERATIONS_HH_ #define SRC_COMMON_CCOORD_OPERATIONS_HH_ namespace muSpectre { namespace CcoordOps { namespace internal { //! simple helper returning the first argument and ignoring the second - template constexpr T ret(T val, size_t /*dummy*/) { + template + constexpr T ret(T val, size_t /*dummy*/) { return val; } //! helper to build cubes template constexpr std::array cube_fun(T val, std::index_sequence) { return std::array{ret(val, I)...}; } //! computes hermitian size according to FFTW template constexpr Ccoord_t herm(const Ccoord_t & full_sizes, std::index_sequence) { return Ccoord_t{full_sizes[I]..., full_sizes.back() / 2 + 1}; } //! compute the stride in a direction of a row-major grid template constexpr Dim_t stride(const Ccoord_t & sizes, const size_t index) { static_assert(Dim > 0, "only for positive numbers of dimensions"); auto const diff{Dim - 1 - Dim_t(index)}; Dim_t ret_val{1}; for (Dim_t i{0}; i < diff; ++i) { ret_val *= sizes[Dim - 1 - i]; } return ret_val; } //! get all strides from a row-major grid (helper function) template constexpr Ccoord_t compute_strides(const Ccoord_t & sizes, std::index_sequence) { return Ccoord_t{stride(sizes, I)...}; } } // namespace internal //-----------------------------------------------------------------------// //! returns a grid of equal resolutions in each direction template constexpr std::array get_cube(T size) { return internal::cube_fun(size, std::make_index_sequence{}); } /* ---------------------------------------------------------------------- */ //! returns the hermition grid to correcsponding to a full grid template constexpr Ccoord_t get_hermitian_sizes(Ccoord_t full_sizes) { return internal::herm(full_sizes, std::make_index_sequence{}); } //! return physical vector of a cell of cubic pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, Real pix_size = 1.) { Eigen::Matrix retval; for (size_t i = 0; i < dim; ++i) { retval[i] = pix_size * ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! return physical vector of a cell of general pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, Eigen::Matrix pix_size) { Eigen::Matrix retval = pix_size; for (size_t i = 0; i < dim; ++i) { retval[i] *= ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! return physical vector of a cell of general pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, const std::array & pix_size) { Eigen::Matrix retval{}; for (size_t i = 0; i < dim; ++i) { retval[i] = pix_size[i] * ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! get all strides from a row-major grid template constexpr Ccoord_t get_default_strides(const Ccoord_t & sizes) { return internal::compute_strides(sizes, std::make_index_sequence{}); } //----------------------------------------------------------------------------// //! get the i-th pixel in a grid of size sizes template constexpr Ccoord_t get_ccoord(const Ccoord_t & resolutions, const Ccoord_t & locations, Dim_t index) { Ccoord_t retval{{0}}; Dim_t factor{1}; for (Dim_t i = dim - 1; i >= 0; --i) { retval[i] = index / factor % resolutions[i] + locations[i]; if (i != 0) { factor *= resolutions[i]; } } return retval; } //----------------------------------------------------------------------------// //! get the i-th pixel in a grid of size sizes template constexpr Ccoord_t get_ccoord(const Ccoord_t & resolutions, const Ccoord_t & locations, Dim_t index, std::index_sequence) { Ccoord_t ccoord{get_ccoord(resolutions, locations, index)}; return Ccoord_t({ccoord[I]...}); } //-----------------------------------------------------------------------// //! get the linear index of a pixel in a given grid template constexpr Dim_t get_index(const Ccoord_t & sizes, const Ccoord_t & locations, const Ccoord_t & ccoord) { Dim_t retval{0}; Dim_t factor{1}; for (Dim_t i = dim - 1; i >= 0; --i) { retval += (ccoord[i] - locations[i]) * factor; if (i != 0) { factor *= sizes[i]; } } return retval; } //-----------------------------------------------------------------------// //! get the linear index of a pixel given a set of strides template constexpr Dim_t get_index_from_strides(const Ccoord_t & strides, const Ccoord_t & ccoord) { Dim_t retval{0}; for (const auto & tup : akantu::zip(strides, ccoord)) { const auto & stride = std::get<0>(tup); const auto & ccord_ = std::get<1>(tup); retval += stride * ccord_; } return retval; } //-----------------------------------------------------------------------// //! get the number of pixels in a grid template constexpr size_t get_size(const Ccoord_t & sizes) { Dim_t retval{1}; for (size_t i = 0; i < dim; ++i) { retval *= sizes[i]; } return retval; } //-----------------------------------------------------------------------// //! get the number of pixels in a grid given its strides template constexpr size_t get_size_from_strides(const Ccoord_t & sizes, const Ccoord_t & strides) { return sizes[0] * strides[0]; } /* ---------------------------------------------------------------------- */ /** * centralises iterating over square (or cubic) discretisation * grids. The optional parameter pack `dmap` can be used to * specify the order of the axes in which to iterate over the * dimensions (i.e., dmap = 0, 1, 2 is rowmajor, and 0, 2, 1 would * be a custom order in which the second and third dimension are * transposed */ - template class Pixels { + template + class Pixels { public: //! constructor Pixels(const Ccoord_t & resolutions = Ccoord_t{}, const Ccoord_t & locations = Ccoord_t{}) : resolutions{resolutions}, locations{locations} {}; //! copy constructor Pixels(const Pixels & other) = default; //! assignment operator Pixels & operator=(const Pixels & other) = default; virtual ~Pixels() = default; /** * iterators over `Pixels` dereferences to cell coordinates */ class iterator { public: using value_type = Ccoord_t; //!< stl conformance using const_value_type = const value_type; //!< stl conformance using pointer = value_type *; //!< stl conformance using difference_type = std::ptrdiff_t; //!< stl conformance using iterator_category = std::forward_iterator_tag; //!< stl //!< conformance using reference = value_type; //!< stl conformance //! constructor explicit iterator(const Pixels & pixels, bool begin = true); virtual ~iterator() = default; //! dereferencing inline value_type operator*() const; //! pre-increment inline iterator & operator++(); //! inequality inline bool operator!=(const iterator & other) const; //! equality inline bool operator==(const iterator & other) const; protected: const Pixels & pixels; //!< ref to pixels in cell size_t index; //!< index of currect pointed-to pixel }; //! stl conformance inline iterator begin() const { return iterator(*this); } //! stl conformance inline iterator end() const { return iterator(*this, false); } //! stl conformance inline size_t size() const { return get_size(this->resolutions); } protected: Ccoord_t resolutions; //!< resolutions of this domain Ccoord_t locations; //!< locations of this domain }; /* ---------------------------------------------------------------------- */ template Pixels::iterator::iterator(const Pixels & pixels, bool begin) : pixels{pixels}, index{begin ? 0 : get_size(pixels.resolutions)} {} /* ---------------------------------------------------------------------- */ template typename Pixels::iterator::value_type Pixels::iterator::operator*() const { return get_ccoord(pixels.resolutions, pixels.locations, this->index, std::conditional_t, std::index_sequence>{}); } /* ---------------------------------------------------------------------- */ template bool Pixels::iterator:: operator!=(const iterator & other) const { return (this->index != other.index) || (&this->pixels != &other.pixels); } /* ---------------------------------------------------------------------- */ template bool Pixels::iterator:: operator==(const iterator & other) const { return !(*this != other); } /* ---------------------------------------------------------------------- */ template typename Pixels::iterator & Pixels::iterator:: operator++() { ++this->index; return *this; } } // namespace CcoordOps } // namespace muSpectre #endif // SRC_COMMON_CCOORD_OPERATIONS_HH_ diff --git a/src/common/common.hh b/src/common/common.hh index b062dbc..bfd5dc7 100644 --- a/src/common/common.hh +++ b/src/common/common.hh @@ -1,318 +1,322 @@ /** * @file common.hh * * @author Till Junge * * @date 01 May 2017 * * @brief Small definitions of commonly used types throughout µSpectre * * @section LICENSE * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include #include #include #ifndef SRC_COMMON_COMMON_HH_ #define SRC_COMMON_COMMON_HH_ namespace muSpectre { /** * Eigen uses signed integers for dimensions. For consistency, µSpectre uses them througout the code. needs to represent -1 for eigen */ using Dim_t = int; 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; + template + using Ccoord_t = std::array; //! Real space coordinates - template using Rcoord_t = std::array; + 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) { + 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 σ(ε) small_strain_sym //!< symmetric storage as vector ε }; //! finite differences flags enum class FiniteDiff { forward, //!< ∂f/∂x ≈ (f(x+Δx) - f(x))/Δx backward, //!< ∂f/∂x ≈ (f(x) - f(x-Δx))/Δx centred //!< ∂f/∂x ≈ (f(x+Δx) - f(x-Δx))/2Δx }; /** * compile time computation of voigt vector */ - template constexpr Dim_t vsize(Dim_t dim) { + 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; } } } // namespace muSpectre #ifndef EXPLICITLY_TURNED_ON_CXX17 #include "common/utilities.hh" #endif #endif // SRC_COMMON_COMMON_HH_ diff --git a/src/common/communicator.hh b/src/common/communicator.hh index 585c664..db396e6 100644 --- a/src/common/communicator.hh +++ b/src/common/communicator.hh @@ -1,132 +1,156 @@ + /** * @file communicator.hh * * @author Lars Pastewka * * @date 07 Mar 2018 * * @brief abstraction layer for the distributed memory communicator object * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_COMMUNICATOR_HH_ #define SRC_COMMON_COMMUNICATOR_HH_ #ifdef WITH_MPI #include #endif namespace muSpectre { #ifdef WITH_MPI - template decltype(auto) mpi_type() {} - template <> inline decltype(auto) mpi_type() { return MPI_CHAR; } - template <> inline decltype(auto) mpi_type() { // NOLINT + template + decltype(auto) mpi_type() {} + template <> + inline decltype(auto) mpi_type() { + return MPI_CHAR; + } + template <> + inline decltype(auto) mpi_type() { // NOLINT return MPI_SHORT; } - template <> inline decltype(auto) mpi_type() { return MPI_INT; } - template <> inline decltype(auto) mpi_type() { // NOLINT + template <> + inline decltype(auto) mpi_type() { + return MPI_INT; + } + template <> + inline decltype(auto) mpi_type() { // NOLINT return MPI_LONG; } - template <> inline decltype(auto) mpi_type() { + template <> + inline decltype(auto) mpi_type() { return MPI_UNSIGNED_CHAR; } - template <> inline decltype(auto) mpi_type() { // NOLINT + template <> + inline decltype(auto) mpi_type() { // NOLINT return MPI_UNSIGNED_SHORT; } - template <> inline decltype(auto) mpi_type() { + template <> + inline decltype(auto) mpi_type() { return MPI_UNSIGNED; } - template <> inline decltype(auto) mpi_type() { // NOLINT + template <> + inline decltype(auto) mpi_type() { // NOLINT return MPI_UNSIGNED_LONG; } - template <> inline decltype(auto) mpi_type() { return MPI_FLOAT; } - template <> inline decltype(auto) mpi_type() { return MPI_DOUBLE; } + template <> + inline decltype(auto) mpi_type() { + return MPI_FLOAT; + } + template <> + inline decltype(auto) mpi_type() { + return MPI_DOUBLE; + } //! lightweight abstraction for the MPI communicator object class Communicator { public: using MPI_Comm_ref = std::remove_pointer_t &; explicit Communicator(MPI_Comm comm = MPI_COMM_NULL) : comm{*comm} {}; ~Communicator() {} //! get rank of present process int rank() const { if (&comm == MPI_COMM_NULL) return 0; int res; MPI_Comm_rank(&this->comm, &res); return res; } //! get total number of processes int size() const { if (&comm == MPI_COMM_NULL) return 1; int res; MPI_Comm_size(&this->comm, &res); return res; } //! sum reduction on scalar types - template T sum(const T & arg) const { + template + T sum(const T & arg) const { if (&comm == MPI_COMM_NULL) return arg; T res; MPI_Allreduce(&arg, &res, 1, mpi_type(), MPI_SUM, &this->comm); return res; } MPI_Comm get_mpi_comm() { return &this->comm; } private: MPI_Comm_ref comm; }; #else /* WITH_MPI */ //! stub communicator object that doesn't communicate anything class Communicator { public: Communicator() {} ~Communicator() {} //! get rank of present process int rank() const { return 0; } //! get total number of processes int size() const { return 1; } //! sum reduction on scalar types - template T sum(const T & arg) const { return arg; } + template + T sum(const T & arg) const { + return arg; + } }; #endif } // namespace muSpectre #endif // SRC_COMMON_COMMUNICATOR_HH_ diff --git a/src/common/eigen_tools.hh b/src/common/eigen_tools.hh index fabd7cb..da757d8 100644 --- a/src/common/eigen_tools.hh +++ b/src/common/eigen_tools.hh @@ -1,433 +1,450 @@ /** * @file eigen_tools.hh * * @author Till Junge * * @date 20 Sep 2017 * * @brief small tools to be used with Eigen * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_EIGEN_TOOLS_HH_ #define SRC_COMMON_EIGEN_TOOLS_HH_ #include "common/common.hh" #include #include #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ namespace internal { //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim - template struct SizesByOrderHelper { + template + struct SizesByOrderHelper { //! type to use using Sizes = typename SizesByOrderHelper::Sizes; }; //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim template struct SizesByOrderHelper<0, dim, dims...> { //! type to use using Sizes = Eigen::Sizes; }; } // namespace internal //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim - template struct SizesByOrder { + template + struct SizesByOrder { static_assert(order > 0, "works only for order greater than zero"); //! `Eigen::Sizes` using Sizes = typename internal::SizesByOrderHelper::Sizes; }; /* ---------------------------------------------------------------------- */ namespace internal { /* ---------------------------------------------------------------------- */ //! Call a passed lambda with the unpacked sizes as arguments template struct CallSizesHelper { //! applies the call static decltype(auto) call(Fun_t && fun) { static_assert(order > 0, "can't handle empty sizes b)"); return CallSizesHelper::call(fun); } }; /* ---------------------------------------------------------------------- */ template //! Call a passed lambda with the unpacked sizes as arguments struct CallSizesHelper<0, Fun_t, dim, args...> { //! applies the call static decltype(auto) call(Fun_t && fun) { return fun(args...); } }; } // namespace internal /** * takes a lambda and calls it with the proper `Eigen::Sizes` * unpacked as arguments. Is used to call constructors of a * `Eigen::Tensor` or map thereof in a context where the spatial * dimension is templated */ template inline decltype(auto) call_sizes(Fun_t && fun) { static_assert(order > 1, "can't handle empty sizes"); return internal::CallSizesHelper::call( std::forward(fun)); } // compile-time square root static constexpr Dim_t ct_sqrt(Dim_t res, Dim_t l, Dim_t r) { if (l == r) { return r; } else { const auto mid = (r + l) / 2; if (mid * mid >= res) { return ct_sqrt(res, l, mid); } else { return ct_sqrt(res, mid + 1, r); } } } static constexpr Dim_t ct_sqrt(Dim_t res) { return ct_sqrt(res, 1, res); } namespace EigenCheck { /** * Structure to determine whether an expression can be evaluated * into a `Eigen::Matrix`, `Eigen::Array`, etc. and which helps * determine compile-time size */ - template struct is_matrix { + template + struct is_matrix { //! raw type for testing using T = std::remove_reference_t; //! evaluated test constexpr static bool value{ std::is_same::XprKind, Eigen::MatrixXpr>::value}; }; /** * Helper class to check whether an `Eigen::Array` or * `Eigen::Matrix` is statically sized */ - template struct is_fixed { + template + struct is_fixed { //! raw type for testing using T = std::remove_reference_t; //! evaluated test constexpr static bool value{T::SizeAtCompileTime != Eigen::Dynamic}; }; /** * Helper class to check whether an `Eigen::Array` or `Eigen::Matrix` is a * static-size and square. */ - template struct is_square { + template + struct is_square { //! raw type for testing using T = std::remove_reference_t; //! true if the object is square and statically sized constexpr static bool value{ (T::RowsAtCompileTime == T::ColsAtCompileTime) && is_fixed::value}; }; /** * computes the dimension from a second order tensor represented * square matrix or array */ - template struct tensor_dim { + template + struct tensor_dim { //! raw type for testing using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static_assert(is_square::value, "t's matrix isn't square"); //! evaluated dimension constexpr static Dim_t value{T::RowsAtCompileTime}; }; //! computes the dimension from a fourth order tensor represented //! by a square matrix - template struct tensor_4_dim { + template + struct tensor_4_dim { //! raw type for testing using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static_assert(is_square::value, "t's matrix isn't square"); //! evaluated dimension constexpr static Dim_t value{ct_sqrt(T::RowsAtCompileTime)}; static_assert(value * value == T::RowsAtCompileTime, "This is not a fourth-order tensor mapped on a square " "matrix"); }; namespace internal { template constexpr inline Dim_t get_rank() { constexpr bool is_vec{(nb_row == dim) and (nb_col == 1)}; constexpr bool is_mat{(nb_row == dim) and (nb_col == nb_row)}; constexpr bool is_ten{(nb_row == dim * dim) and (nb_col == dim * dim)}; static_assert(is_vec or is_mat or is_ten, "can't understand the data type as a first-, second-, or " "fourth-order tensor"); if (is_vec) { return firstOrder; } else if (is_mat) { return secondOrder; } else if (is_ten) { return fourthOrder; } } } // namespace internal /** * computes the rank of a tensor given the spatial dimension */ - template struct tensor_rank { + template + struct tensor_rank { using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static constexpr Dim_t value{internal::get_rank()}; }; } // namespace EigenCheck namespace log_comp { //! Matrix type used for logarithm evaluation - template using Mat_t = Eigen::Matrix; + template + using Mat_t = Eigen::Matrix; //! Vector type used for logarithm evaluation - template using Vec_t = Eigen::Matrix; + template + using Vec_t = Eigen::Matrix; //! This is a static implementation of the explicit determination //! of log(Tensor) following Jog, C.S. J Elasticity (2008) 93: //! 141. https://doi.org/10.1007/s10659-008-9169-x /* ---------------------------------------------------------------------- */ - template struct Proj { + template + struct Proj { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()) * Proj::compute(eigs, T); } }; //! catch the case when there's nothing to do - template struct Proj { + template + struct Proj { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return Proj::compute(eigs, T); } }; //! catch the normal tail case - template struct Proj { + template + struct Proj { static constexpr Dim_t j{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()); } }; //! catch the tail case when the last dimension is i - template struct Proj { + template + struct Proj { static constexpr Dim_t i{0}; //!< short-hand static constexpr Dim_t j{1}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()); } }; //! catch the general tail case - template <> struct Proj<1, 0, 0> { + template <> + struct Proj<1, 0, 0> { static constexpr Dim_t dim{1}; //!< short-hand static constexpr Dim_t i{0}; //!< short-hand static constexpr Dim_t j{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & /*eigs*/, const Mat_t & /*T*/) { return Mat_t::Identity(); } }; //! Product term template inline decltype(auto) P(const Vec_t & eigs, const Mat_t & T) { return Proj::compute(eigs, T); } //! sum term - template struct Summand { + template + struct Summand { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { return std::log(eigs(i)) * P(eigs, T) + Summand::compute(eigs, T); } }; //! sum term - template struct Summand { + template + struct Summand { static constexpr Dim_t i{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { return std::log(eigs(i)) * P(eigs, T); } }; //! sum implementation template inline decltype(auto) Sum(const Vec_t & eigs, const Mat_t & T) { return Summand::compute(eigs, T); } } // namespace log_comp /** * computes the matrix logarithm efficiently for dim=1, 2, or 3 for * a diagonizable tensor. For larger tensors, better use the direct * eigenvalue/vector computation */ template inline decltype(auto) logm(const log_comp::Mat_t & mat) { using Mat = log_comp::Mat_t; Eigen::SelfAdjointEigenSolver Solver{}; Solver.computeDirect(mat, Eigen::EigenvaluesOnly); return Mat{log_comp::Sum(Solver.eigenvalues(), mat)}; } /** * compute the spectral decomposition */ template inline decltype(auto) spectral_decomposition(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; Eigen::SelfAdjointEigenSolver Solver{}; Solver.computeDirect(mat, Eigen::ComputeEigenvectors); return Solver; } /** * compute the matrix log. This may not be the most * efficient way to do this */ template using Decomp_t = Eigen::SelfAdjointEigenSolver>; template inline decltype(auto) logm_alt(const Decomp_t & spectral_decomp) { using Mat = log_comp::Mat_t; Mat retval{Mat::Zero()}; for (Dim_t i = 0; i < Dim; ++i) { const Real & val = spectral_decomp.eigenvalues()(i); auto & vec = spectral_decomp.eigenvectors().col(i); retval += std::log(val) * vec * vec.transpose(); } return retval; } template inline decltype(auto) logm_alt(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; using Decomp_t = Eigen::SelfAdjointEigenSolver; Decomp_t decomp{spectral_decomposition(mat)}; return logm_alt(decomp); } /** * compute the matrix exponential. This may not be the most * efficient way to do this */ template inline decltype(auto) expm(const Decomp_t & spectral_decomp) { using Mat = log_comp::Mat_t; Mat retval{Mat::Zero()}; for (Dim_t i = 0; i < Dim; ++i) { const Real & val = spectral_decomp.eigenvalues()(i); auto & vec = spectral_decomp.eigenvectors().col(i); retval += std::exp(val) * vec * vec.transpose(); } return retval; } template inline decltype(auto) expm(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t Dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; using Decomp_t = Eigen::SelfAdjointEigenSolver; Decomp_t decomp{spectral_decomposition(mat)}; return expm(decomp); } } // namespace muSpectre #endif // SRC_COMMON_EIGEN_TOOLS_HH_ diff --git a/src/common/field.hh b/src/common/field.hh index f8d35b4..2d3ca1f 100644 --- a/src/common/field.hh +++ b/src/common/field.hh @@ -1,668 +1,666 @@ /** * @file field.hh * * @author Till Junge * * @date 07 Sep 2017 * * @brief header-only implementation of a field for field collections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_HH_ #define SRC_COMMON_FIELD_HH_ #include "common/T4_map_proxy.hh" #include "common/field_typed.hh" #include #include #include #include #include #include #include #include #include namespace muSpectre { namespace internal { /* ---------------------------------------------------------------------- */ //! declaraton for friending template class FieldMap; /* ---------------------------------------------------------------------- */ /** * A `TypedSizedFieldBase` is the base class for fields that contain a * statically known number of scalars of a statically known type per pixel * in a `FieldCollection`. The actual data for all pixels is * stored in `TypedSizeFieldBase::values`. * `TypedSizedFieldBase` is the base class for `MatrixField` and * `TensorField`. */ template class TypedSizedFieldBase : public TypedField { friend class FieldMap; friend class FieldMap; public: //! for compatibility checks constexpr static auto nb_components{NbComponents}; using Parent = TypedField; //!< base class using Scalar = T; //!< for type checking using Base = typename Parent::Base; //!< root base class //! storage container using Storage_t = typename Parent::Storage_t; //! Plain type that is being mapped (Eigen lingo) using EigenRep_t = Eigen::Array; //! maps returned when iterating over field using EigenMap_t = Eigen::Map; //! maps returned when iterating over field using ConstEigenMap_t = Eigen::Map; //! constructor TypedSizedFieldBase(std::string unique_name, FieldCollection & collection); virtual ~TypedSizedFieldBase() = default; //! add a new value at the end of the field template inline void push_back(const Eigen::DenseBase & value); //! add a new scalar value at the end of the field template inline std::enable_if_t push_back(const T & value); /** * returns an upcasted reference to a field, or throws an * exception if the field is incompatible */ static TypedSizedFieldBase & check_ref(Base & other); /** * returns an upcasted reference to a field, or throws an * exception if the field is incompatible */ static const TypedSizedFieldBase & check_ref(const Base & other); //! return a map representing the entire field as a single `Eigen::Array` inline EigenMap_t eigen(); //! return a map representing the entire field as a single `Eigen::Array` inline ConstEigenMap_t eigen() const; /** * return a map representing the entire field as a single * dynamically sized `Eigen::Array` (for python bindings) */ inline typename Parent::EigenMap_t dyn_eigen() { return Parent::eigen(); } //! inner product between compatible fields template inline Real inner_product( const TypedSizedFieldBase & other) const; protected: //! returns a raw pointer to the entry, for `Eigen::Map` inline T * get_ptr_to_entry(const size_t && index); //! returns a raw pointer to the entry, for `Eigen::Map` inline const T * get_ptr_to_entry(const size_t && index) const; }; } // namespace internal /* ---------------------------------------------------------------------- */ /** * The `TensorField` is a subclass of * `muSpectre::internal::TypedSizedFieldBase` that represents tensorial * fields, i.e. arbitrary-dimensional arrays with identical number of * rows/columns (that typically correspond to the spatial cartesian * dimensions). It is defined by the stored scalar type @a T, the tensorial * order @a order (often also called degree or rank) and the number of spatial * dimensions @a dim. */ template class TensorField : public internal::TypedSizedFieldBase { public: //! base class using Parent = internal::TypedSizedFieldBase; using Base = typename Parent::Base; //!< root base class //! polymorphic base class using Field_p = typename FieldCollection::Field_p; using Scalar = typename Parent::Scalar; //!< for type checking //! Copy constructor TensorField(const TensorField & other) = delete; //! Move constructor TensorField(TensorField && other) = delete; //! Destructor virtual ~TensorField() = default; //! Copy assignment operator TensorField & operator=(const TensorField & other) = delete; //! Move assignment operator TensorField & operator=(TensorField && other) = delete; //! return the order of the stored tensor inline Dim_t get_order() const; //! return the dimension of the stored tensor inline Dim_t get_dim() const; //! factory function template friend FieldType & make_field(std::string unique_name, CollectionType & collection, Args &&... args); //! return a reference or throw an exception if `other` is incompatible static TensorField & check_ref(Base & other) { return static_cast(Parent::check_ref(other)); } //! return a reference or throw an exception if `other` is incompatible static const TensorField & check_ref(const Base & other) { return static_cast(Parent::check_ref(other)); } /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_const_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_map() const; /** * creates a `TensorField` same size and type as this, but all * entries are zero. Convenience function */ inline TensorField & get_zeros_like(std::string unique_name) const; protected: //! constructor protected! TensorField(std::string unique_name, FieldCollection & collection); private: }; /* ---------------------------------------------------------------------- */ /** * The `MatrixField` is subclass of `muSpectre::internal::TypedSizedFieldBase` * that represents matrix fields, i.e. a two dimensional arrays, defined by * the stored scalar type @a T and the number of rows @a NbRow and columns * @a NbCol of the matrix. */ template class MatrixField : public internal::TypedSizedFieldBase { public: //! base class using Parent = internal::TypedSizedFieldBase; using Base = typename Parent::Base; //!< root base class //! polymorphic base field ptr to store using Field_p = std::unique_ptr>; //! Copy constructor MatrixField(const MatrixField & other) = delete; //! Move constructor MatrixField(MatrixField && other) = delete; //! Destructor virtual ~MatrixField() = default; //! Copy assignment operator MatrixField & operator=(const MatrixField & other) = delete; //! Move assignment operator MatrixField & operator=(MatrixField && other) = delete; //! returns the number of rows inline Dim_t get_nb_row() const; //! returns the number of columns inline Dim_t get_nb_col() const; //! factory function template friend FieldType & make_field(std::string unique_name, CollectionType & collection, Args &&... args); //! returns a `MatrixField` reference if `other` is a compatible field static MatrixField & check_ref(Base & other) { return static_cast(Parent::check_ref(other)); } //! returns a `MatrixField` reference if `other` is a compatible field static const MatrixField & check_ref(const Base & other) { return static_cast(Parent::check_ref(other)); } /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_const_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_map() const; /** * creates a `MatrixField` same size and type as this, but all * entries are zero. Convenience function */ inline MatrixField & get_zeros_like(std::string unique_name) const; protected: //! constructor protected! MatrixField(std::string unique_name, FieldCollection & collection); - - private: }; /* ---------------------------------------------------------------------- */ //! convenience alias ( template using ScalarField = MatrixField; /* ---------------------------------------------------------------------- */ // Implementations /* ---------------------------------------------------------------------- */ namespace internal { /* ---------------------------------------------------------------------- */ template TypedSizedFieldBase::TypedSizedFieldBase( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection, NbComponents) { static_assert( (std::is_arithmetic::value || std::is_same::value), "Use TypedSizedFieldBase for integer, real or complex scalars for T"); static_assert(NbComponents > 0, "Only fields with more than 0 components"); } /* ---------------------------------------------------------------------- */ template TypedSizedFieldBase & TypedSizedFieldBase::check_ref( Base & other) { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a reference of type '" << typeid(T).name() << "' for field '" << other.get_name() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } // check size compatibility if (NbComponents != other.get_nb_components()) { std::stringstream err_str{}; err_str << "Cannot create a reference to a field with " << NbComponents << " components " << "for field '" << other.get_name() << "' with " << other.get_nb_components() << " components"; throw std::runtime_error{err_str.str()}; } return static_cast(other); } /* ---------------------------------------------------------------------- */ template const TypedSizedFieldBase & TypedSizedFieldBase::check_ref( const Base & other) { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a reference of type '" << typeid(T).name() << "' for field '" << other.get_name() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } // check size compatibility if (NbComponents != other.get_nb_components()) { std::stringstream err_str{}; err_str << "Cannot create a reference toy a field with " << NbComponents << " components " << "for field '" << other.get_name() << "' with " << other.get_nb_components() << " components"; throw std::runtime_error{err_str.str()}; } return static_cast(other); } /* ---------------------------------------------------------------------- */ template auto TypedSizedFieldBase::eigen() -> EigenMap_t { return EigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ template auto TypedSizedFieldBase::eigen() const -> ConstEigenMap_t { return ConstEigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ template template Real TypedSizedFieldBase::inner_product( const TypedSizedFieldBase & other) const { return (this->eigen() * other.eigen()).sum(); } /* ---------------------------------------------------------------------- */ template T * TypedSizedFieldBase::get_ptr_to_entry( const size_t && index) { return this->data_ptr + NbComponents * std::move(index); } /* ---------------------------------------------------------------------- */ template const T * TypedSizedFieldBase::get_ptr_to_entry( const size_t && index) const { return this->data_ptr + NbComponents * std::move(index); } /* ---------------------------------------------------------------------- */ template template void TypedSizedFieldBase::push_back( const Eigen::DenseBase & value) { static_assert(Derived::SizeAtCompileTime == NbComponents, "You provided an array with the wrong number of entries."); static_assert((Derived::RowsAtCompileTime == 1) or (Derived::ColsAtCompileTime == 1), "You have not provided a column or row vector."); static_assert(not FieldCollection::Global, "You can only push_back data into local field " "collections."); for (Dim_t i = 0; i < NbComponents; ++i) { this->values.push_back(value(i)); } ++this->current_size; this->data_ptr = &this->values.front(); } /* ---------------------------------------------------------------------- */ template template std::enable_if_t TypedSizedFieldBase::push_back( const T & value) { static_assert(scalar_store, "SFINAE"); this->values.push_back(value); ++this->current_size; this->data_ptr = &this->values.front(); } } // namespace internal /* ---------------------------------------------------------------------- */ template TensorField::TensorField( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection) {} /* ---------------------------------------------------------------------- */ template Dim_t TensorField::get_order() const { return order; } /* ---------------------------------------------------------------------- */ template Dim_t TensorField::get_dim() const { return dim; } /* ---------------------------------------------------------------------- */ template MatrixField::MatrixField( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection) {} /* ---------------------------------------------------------------------- */ template Dim_t MatrixField::get_nb_col() const { return NbCol; } /* ---------------------------------------------------------------------- */ template Dim_t MatrixField::get_nb_row() const { return NbRow; } } // namespace muSpectre #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; }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto TensorField::get_map() -> decltype(auto) { constexpr bool map_constness{false}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_const_map() -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_map() const -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_zeros_like( std::string unique_name) const -> TensorField & { return make_field(unique_name, this->collection); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_map() -> decltype(auto) { constexpr bool map_constness{false}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_const_map() -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_map() const -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_zeros_like( std::string unique_name) const -> MatrixField & { return make_field(unique_name, this->collection); } } // namespace muSpectre #endif // SRC_COMMON_FIELD_HH_ diff --git a/src/common/field_base.hh b/src/common/field_base.hh index f319a65..effa348 100644 --- a/src/common/field_base.hh +++ b/src/common/field_base.hh @@ -1,210 +1,209 @@ /** * file field_base.hh * * @author Till Junge * * @date 10 Apr 2018 * * @brief Virtual base class for fields * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_BASE_HH_ #define SRC_COMMON_FIELD_BASE_HH_ #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 { + template + class FieldBase { protected: //! constructor //! unique name (whithin Collection) //! number of components //! collection to which this field belongs (eg, material, cell) FieldBase(std::string unique_name, size_t nb_components, FieldCollection & collection); public: using collection_t = FieldCollection; //!< for type checks //! Copy constructor FieldBase(const FieldBase & other) = delete; //! Move constructor FieldBase(FieldBase && other) = delete; //! Destructor virtual ~FieldBase() = default; //! Copy assignment operator FieldBase & operator=(const FieldBase & other) = delete; //! Move assignment operator FieldBase & operator=(FieldBase && other) = delete; /* ---------------------------------------------------------------------- */ //! Identifying accessors //! return field name inline const std::string & get_name() const; //! return field type // inline const Field_t & get_type() const; //! return my collection (for iterating) inline const FieldCollection & get_collection() const; //! return number of components (e.g., dimensions) of this field inline const size_t & get_nb_components() const; //! return type_id of stored type virtual const std::type_info & get_stored_typeid() const = 0; //! number of pixels in the field virtual size_t size() const = 0; //! add a pad region to the end of the field buffer; required for //! using this as e.g. an FFT workspace virtual void set_pad_size(size_t pad_size_) = 0; //! pad region size virtual size_t get_pad_size() const { return this->pad_size; } //! initialise field to zero (do more complicated initialisations through //! fully typed maps) virtual void set_zero() = 0; //! give access to collections friend FieldCollection; //! give access to collection's base class using FParent_t = typename FieldCollection::Parent; friend FParent_t; protected: /* ---------------------------------------------------------------------- */ //! allocate memory etc virtual void resize(size_t size) = 0; const std::string name; //!< the field's unique name const size_t nb_components; //!< number of components per entry //! reference to the collection this field belongs to FieldCollection & collection; size_t pad_size; //!< size of padding region at end of buffer - - 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; } } // namespace internal } // namespace muSpectre #endif // SRC_COMMON_FIELD_BASE_HH_ diff --git a/src/common/field_collection_base.hh b/src/common/field_collection_base.hh index 8d5a996..6392d00 100644 --- a/src/common/field_collection_base.hh +++ b/src/common/field_collection_base.hh @@ -1,384 +1,382 @@ /** * @file field_collection_base.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief Base class for field collections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_COLLECTION_BASE_HH_ #define SRC_COMMON_FIELD_COLLECTION_BASE_HH_ #include "common/common.hh" #include "common/field.hh" #include "common/statefield.hh" #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ /** `FieldCollectionBase` is the base class for collections of fields. All * fields in a field collection have the same number of pixels. The field * collection is templated with @a DimS is the spatial dimension (i.e. * whether the simulation domain is one, two or three-dimensional). * All fields within a field collection have a unique string identifier. * A `FieldCollectionBase` is therefore comparable to a dictionary of fields * that live on the same grid. * `FieldCollectionBase` has the specialisations `GlobalFieldCollection` and * `LocalFieldCollection`. */ template class FieldCollectionBase { public: //! polymorphic base type to store using Field_t = internal::FieldBase; template using TypedField_t = TypedField; using Field_p = std::unique_ptr; //!< stored type using StateField_t = StateFieldBase; template using TypedStateField_t = TypedStateField; using StateField_p = std::unique_ptr; using Ccoord = Ccoord_t; //!< cell coordinates type //! Default constructor FieldCollectionBase(); //! Copy constructor FieldCollectionBase(const FieldCollectionBase & other) = delete; //! Move constructor FieldCollectionBase(FieldCollectionBase && other) = delete; //! Destructor virtual ~FieldCollectionBase() = default; //! Copy assignment operator FieldCollectionBase & operator=(const FieldCollectionBase & other) = delete; //! Move assignment operator FieldCollectionBase & operator=(FieldCollectionBase && other) = delete; //! Register a new field (fields need to be in heap, so I want to keep them //! as shared pointers void register_field(Field_p && field); //! Register a new field (fields need to be in heap, so I want to keep them //! as shared pointers void register_statefield(StateField_p && field); //! for return values of iterators constexpr inline static Dim_t spatial_dim(); //! for return values of iterators inline Dim_t get_spatial_dim() const; //! return names of all stored fields std::vector get_field_names() const { std::vector names{}; for (auto & tup : this->fields) { names.push_back(std::get<0>(tup)); } return names; } //! return names of all state fields std::vector get_statefield_names() const { std::vector names{}; for (auto & tup : this->statefields) { names.push_back(std::get<0>(tup)); } return names; } //! retrieve field by unique_name inline Field_t & operator[](std::string unique_name); //! retrieve field by unique_name with bounds checking inline Field_t & at(std::string unique_name); //! retrieve typed field by unique_name template inline TypedField_t & get_typed_field(std::string unique_name); //! retrieve state field by unique_prefix with bounds checking template inline TypedStateField_t & get_typed_statefield(std::string unique_prefix); //! retrieve state field by unique_prefix with bounds checking inline StateField_t & get_statefield(std::string unique_prefix) { return *(this->statefields.at(unique_prefix)); } //! retrieve state field by unique_prefix with bounds checking inline const StateField_t & get_statefield(std::string unique_prefix) const { return *(this->statefields.at(unique_prefix)); } /** * retrieve current value of typed state field by unique_prefix with * bounds checking */ template inline TypedField_t & get_current(std::string unique_prefix); /** * retrieve old value of typed state field by unique_prefix with * bounds checking */ template inline const TypedField_t & get_old(std::string unique_prefix, size_t nb_steps_ago = 1) const; //! returns size of collection, this refers to the number of pixels handled //! by the collection, not the number of fields inline size_t size() const { return this->size_; } //! check whether a field is present bool check_field_exists(const std::string & unique_name); //! check whether a field is present bool check_statefield_exists(const std::string & unique_prefix); //! check whether the collection is initialised bool initialised() const { return this->is_initialised; } /** * list the names of all fields */ std::vector list_fields() const; protected: std::map fields{}; //!< contains the field ptrs //! contains ptrs to state fields std::map statefields{}; bool is_initialised{false}; //!< to handle double initialisation correctly const Uint id; //!< unique identifier static Uint counter; //!< used to assign unique identifiers size_t size_{0}; //!< holds the number of pixels after initialisation - - private: }; /* ---------------------------------------------------------------------- */ template Uint FieldCollectionBase::counter{0}; /* ---------------------------------------------------------------------- */ template FieldCollectionBase::FieldCollectionBase() : id(counter++) {} /* ---------------------------------------------------------------------- */ template void FieldCollectionBase::register_field( Field_p && field) { if (this->check_field_exists(field->get_name())) { std::stringstream err_str; err_str << "a field named '" << field->get_name() << "' is already registered in this field collection. " << "Currently registered fields: "; std::string prelude{""}; for (const auto & name_field_pair : this->fields) { err_str << prelude << '\'' << name_field_pair.first << '\''; prelude = ", "; } throw FieldCollectionError(err_str.str()); } if (this->is_initialised) { field->resize(this->size()); } this->fields[field->get_name()] = std::move(field); } /* ---------------------------------------------------------------------- */ template void FieldCollectionBase::register_statefield( StateField_p && field) { auto && search_it = this->statefields.find(field->get_prefix()); auto && does_exist = search_it != this->statefields.end(); if (does_exist) { std::stringstream err_str; err_str << "a state field named '" << field->get_prefix() << "' is already registered in this field collection. " << "Currently registered fields: "; std::string prelude{""}; for (const auto & name_field_pair : this->statefields) { err_str << prelude << '\'' << name_field_pair.first << '\''; prelude = ", "; } throw FieldCollectionError(err_str.str()); } this->statefields[field->get_prefix()] = std::move(field); } /* ---------------------------------------------------------------------- */ template constexpr Dim_t FieldCollectionBase::spatial_dim() { return DimS; } /* ---------------------------------------------------------------------- */ template Dim_t FieldCollectionBase::get_spatial_dim() const { return DimS; } /* ---------------------------------------------------------------------- */ template auto FieldCollectionBase:: operator[](std::string unique_name) -> Field_t & { return *(this->fields[unique_name]); } /* ---------------------------------------------------------------------- */ template auto FieldCollectionBase::at(std::string unique_name) -> Field_t & { return *(this->fields.at(unique_name)); } /* ---------------------------------------------------------------------- */ template bool FieldCollectionBase::check_field_exists( const std::string & unique_name) { return this->fields.find(unique_name) != this->fields.end(); } /* ---------------------------------------------------------------------- */ template bool FieldCollectionBase::check_statefield_exists( const std::string & unique_prefix) { return this->statefields.find(unique_prefix) != this->statefields.end(); } //! retrieve typed field by unique_name template template auto FieldCollectionBase::get_typed_field( std::string unique_name) -> TypedField_t & { auto & unqualified_field{this->at(unique_name)}; if (unqualified_field.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "Field '" << unique_name << "' is of type " << unqualified_field.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } return static_cast &>(unqualified_field); } /* ---------------------------------------------------------------------- */ //! retrieve state field by unique_prefix with bounds checking template template auto FieldCollectionBase::get_typed_statefield( std::string unique_prefix) -> TypedStateField_t & { auto & unqualified_statefield{this->get_statefield(unique_prefix)}; if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "Statefield '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } return static_cast &>(unqualified_statefield); } /* ---------------------------------------------------------------------- */ template std::vector FieldCollectionBase::list_fields() const { std::vector ret_val{}; for (auto & key_val : this->fields) { ret_val.push_back(key_val.first); } return ret_val; } /* ---------------------------------------------------------------------- */ template template auto FieldCollectionBase::get_current( std::string unique_prefix) -> TypedField_t & { auto & unqualified_statefield = this->get_statefield(unique_prefix); //! check for correct underlying fundamental type if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "StateField '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } using Typed_t = TypedStateField; auto & typed_field{static_cast(unqualified_statefield)}; return typed_field.get_current_field(); } /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ template template auto FieldCollectionBase::get_old( std::string unique_prefix, size_t nb_steps_ago) const -> const TypedField_t & { auto & unqualified_statefield = this->get_statefield(unique_prefix); //! check for correct underlying fundamental type if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "StateField '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } using Typed_t = TypedStateField; auto & typed_field{static_cast(unqualified_statefield)}; return typed_field.get_old_field(nb_steps_ago); } } // namespace muSpectre #endif // SRC_COMMON_FIELD_COLLECTION_BASE_HH_ diff --git a/src/common/field_collection_global.hh b/src/common/field_collection_global.hh index d8cafc2..f209413 100644 --- a/src/common/field_collection_global.hh +++ b/src/common/field_collection_global.hh @@ -1,213 +1,216 @@ /** * @file field_collection_global.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief FieldCollection base-class for global fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ #define SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ #include "common/ccoord_operations.hh" #include "common/field_collection_base.hh" namespace muSpectre { /** * forward declaration */ - template class LocalFieldCollection; + template + class LocalFieldCollection; /** `GlobalFieldCollection` derives from `FieldCollectionBase` and stores * global fields that live throughout the whole computational domain, i.e. * are defined for each pixel. */ template class GlobalFieldCollection : public FieldCollectionBase> { public: //! for compile time check constexpr static bool Global{true}; using Parent = FieldCollectionBase>; //!< base class //! helpful for functions that fill global fields from local fields using LocalFieldCollection_t = LocalFieldCollection; //! helpful for functions that fill global fields from local fields using GlobalFieldCollection_t = GlobalFieldCollection; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Field_p = typename Parent::Field_p; //!< spatial coordinates type //! iterator over all pixels contained it the collection using iterator = typename CcoordOps::Pixels::iterator; //! Default constructor GlobalFieldCollection(); //! Copy constructor GlobalFieldCollection(const GlobalFieldCollection & other) = delete; //! Move constructor GlobalFieldCollection(GlobalFieldCollection && other) = default; //! Destructor virtual ~GlobalFieldCollection() = default; //! Copy assignment operator GlobalFieldCollection & operator=(const GlobalFieldCollection & other) = delete; //! Move assignment operator GlobalFieldCollection & operator=(GlobalFieldCollection && other) = default; /** allocate memory, etc. At this point, the collection is informed aboud the size and shape of the domain (through the sizes parameter). The job of initialise is to make sure that all fields are either of size 0, in which case they need to be allocated, or are of the same size as the product of 'sizes' (if standard strides apply) any field of a different size is wrong. TODO: check whether it makes sense to put a runtime check here **/ inline void initialise(Ccoord sizes, Ccoord locations); //! return subdomain resolutions inline const Ccoord & get_sizes() const; //! return subdomain locations inline const Ccoord & get_locations() const; //! returns the linear index corresponding to cell coordinates template inline size_t get_index(CcoordRef && ccoord) const; //! returns the cell coordinates corresponding to a linear index inline Ccoord get_ccoord(size_t index) const; inline iterator begin() const; //!< returns iterator to first pixel inline iterator end() const; //!< returns iterator past the last pixel //! return spatial dimension (template parameter) static constexpr inline Dim_t spatial_dim() { return DimS; } //! return globalness at compile time static constexpr inline bool is_global() { return Global; } protected: //! number of discretisation cells in each of the DimS spatial directions Ccoord sizes{}; + //! subdomain locations (i.e. coordinates of hind bottom left corner of this + //! subdomain) Ccoord locations{}; CcoordOps::Pixels pixels{}; //!< helper to iterate over the grid private: }; /* ---------------------------------------------------------------------- */ template GlobalFieldCollection::GlobalFieldCollection() : Parent() {} /* ---------------------------------------------------------------------- */ template void GlobalFieldCollection::initialise(Ccoord sizes, Ccoord locations) { if (this->is_initialised) { throw std::runtime_error("double initialisation"); } this->pixels = CcoordOps::Pixels(sizes, locations); this->size_ = CcoordOps::get_size(sizes); this->sizes = sizes; this->locations = locations; std::for_each( std::begin(this->fields), std::end(this->fields), [this](auto && item) { auto && field = *item.second; const auto field_size = field.size(); if (field_size == 0) { field.resize(this->size()); } else if (field_size != this->size()) { std::stringstream err_stream; err_stream << "Field '" << field.get_name() << "' contains " << field_size << " entries, but the field collection " << "has " << this->size() << " pixels"; throw FieldCollectionError(err_stream.str()); } }); this->is_initialised = true; } //----------------------------------------------------------------------------// //! return subdomain resolutions template const typename GlobalFieldCollection::Ccoord & GlobalFieldCollection::get_sizes() const { return this->sizes; } //----------------------------------------------------------------------------// //! return subdomain locations template const typename GlobalFieldCollection::Ccoord & GlobalFieldCollection::get_locations() const { return this->locations; } //----------------------------------------------------------------------------// //! returns the cell coordinates corresponding to a linear index template typename GlobalFieldCollection::Ccoord GlobalFieldCollection::get_ccoord(size_t index) const { return CcoordOps::get_ccoord(this->get_sizes(), this->get_locations(), std::move(index)); } /* ---------------------------------------------------------------------- */ template typename GlobalFieldCollection::iterator GlobalFieldCollection::begin() const { return this->pixels.begin(); } /* ---------------------------------------------------------------------- */ template typename GlobalFieldCollection::iterator GlobalFieldCollection::end() const { return this->pixels.end(); } //-------------------------------------------------------------------------// //! returns the linear index corresponding to cell coordinates template template size_t GlobalFieldCollection::get_index(CcoordRef && ccoord) const { static_assert( std::is_same>>::value, "can only be called with values or references of Ccoord"); return CcoordOps::get_index(this->get_sizes(), this->get_locations(), std::forward(ccoord)); } } // namespace muSpectre #endif // SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ diff --git a/src/common/field_collection_local.hh b/src/common/field_collection_local.hh index 791adad..cc5424f 100644 --- a/src/common/field_collection_local.hh +++ b/src/common/field_collection_local.hh @@ -1,197 +1,199 @@ /** * @file field_collection_local.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief FieldCollection base-class for local fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ #define SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ #include "common/field_collection_base.hh" namespace muSpectre { /** * forward declaration */ - template class GlobalFieldCollection; + template + class GlobalFieldCollection; /** `LocalFieldCollection` derives from `FieldCollectionBase` and stores * local fields, i.e. fields that are only defined for a subset of all pixels * in the computational domain. The coordinates of these active pixels are * explicitly stored by this field collection. * `LocalFieldCollection::add_pixel` allows to add individual pixels to the * field collection. */ template class LocalFieldCollection : public FieldCollectionBase> { public: //! for compile time check constexpr static bool Global{false}; //! base class using Parent = FieldCollectionBase>; //! helpful for functions that fill local fields from global fields using GlobalFieldCollection_t = GlobalFieldCollection; //! helpful for functions that fill local fields from global fields using LocalFieldCollection_t = LocalFieldCollection; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Field_p = typename Parent::Field_p; //!< field pointer using ccoords_container = std::vector; //!< list of pixels //! iterator over managed pixels using iterator = typename ccoords_container::iterator; //! const iterator over managed pixels using const_iterator = typename ccoords_container::const_iterator; //! Default constructor LocalFieldCollection(); //! Copy constructor LocalFieldCollection(const LocalFieldCollection & other) = delete; //! Move constructor LocalFieldCollection(LocalFieldCollection && other) = delete; //! Destructor virtual ~LocalFieldCollection() = default; //! Copy assignment operator LocalFieldCollection & operator=(const LocalFieldCollection & other) = delete; //! Move assignment operator LocalFieldCollection & operator=(LocalFieldCollection && other) = delete; //! add a pixel/voxel to the field collection inline void add_pixel(const Ccoord & local_ccoord); /** allocate memory, etc. at this point, the field collection knows how many entries it should have from the size of the coords containes (which grows by one every time add_pixel is called. The job of initialise is to make sure that all fields are either of size 0, in which case they need to be allocated, or are of the same size as the product of 'sizes' any field of a different size is wrong TODO: check whether it makes sense to put a runtime check here **/ inline void initialise(); //! returns the linear index corresponding to cell coordinates template inline size_t get_index(CcoordRef && ccoord) const; //! returns the cell coordinates corresponding to a linear index inline Ccoord get_ccoord(size_t index) const; //! iterator to first pixel inline iterator begin() { return this->ccoords.begin(); } //! iterator past last pixel inline iterator end() { return this->ccoords.end(); } //! const iterator to first pixel inline const_iterator begin() const { return this->ccoords.cbegin(); } //! const iterator past last pixel inline const_iterator end() const { return this->ccoords.cend(); } //! return globalness at compile time static constexpr inline bool is_global() { return Global; } protected: //! container of pixel coords for non-global collections ccoords_container ccoords{}; //! container of indices for non-global collections (slow!) std::map indices{}; 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() { + template + void LocalFieldCollection::initialise() { if (this->is_initialised) { throw std::runtime_error("double initialisation"); } std::for_each( std::begin(this->fields), std::end(this->fields), [this](auto && item) { auto && field = *item.second; const auto field_size = field.size(); if (field_size == 0) { field.resize(this->size()); } else if (field_size != this->size()) { std::stringstream err_stream; err_stream << "Field '" << field.get_name() << "' contains " << field_size << " entries, but the field collection " << "has " << this->size() << " pixels"; throw FieldCollectionError(err_stream.str()); } }); this->is_initialised = true; } //----------------------------------------------------------------------------// //! returns the linear index corresponding to cell coordinates template template size_t LocalFieldCollection::get_index(CcoordRef && ccoord) const { static_assert( std::is_same>>::value, "can only be called with values or references of Ccoord"); return this->indices.at(std::forward(ccoord)); } //----------------------------------------------------------------------------// //! returns the cell coordinates corresponding to a linear index template typename LocalFieldCollection::Ccoord LocalFieldCollection::get_ccoord(size_t index) const { return this->ccoords[std::move(index)]; } } // namespace muSpectre #endif // SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ diff --git a/src/common/field_map.hh b/src/common/field_map.hh index 521e59a..900857f 100644 --- a/src/common/field_map.hh +++ b/src/common/field_map.hh @@ -1,257 +1,259 @@ /** * @file field_map.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief just and indirection to include all iterables defined for fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/field_map_tensor.hh" #include "common/field_map_matrixlike.hh" #include "common/field_map_scalar.hh" #include #include #include #ifndef SRC_COMMON_FIELD_MAP_HH_ #define SRC_COMMON_FIELD_MAP_HH_ 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 { + template + class RawFieldMap { public: /** * determining the constness of the mapped array required in order * to formulate the constructors const-correctly */ constexpr static bool IsConst{std::is_const< std::remove_pointer_t>::value}; //! short-hand for the basic scalar type using T = typename EigenMap::Scalar; //! raw pointer type to store using T_ptr = std::conditional_t; //! input array (~field) type to be mapped using FieldVec_t = std::conditional_t; //! Plain mapped Eigen type using EigenPlain = typename EigenMap::PlainObject; //! Default constructor RawFieldMap() = delete; //! constructor from a *contiguous* array RawFieldMap(Eigen::Map vec, Dim_t nb_rows = EigenMap::RowsAtCompileTime, Dim_t nb_cols = EigenMap::ColsAtCompileTime) : data{vec.data()}, nb_rows{nb_rows}, nb_cols{nb_cols}, nb_components{nb_rows * nb_cols}, nb_pixels(vec.size() / nb_components) { if ((nb_rows == Eigen::Dynamic) or (nb_cols == Eigen::Dynamic)) { throw FieldError( "You have to specify the number of rows and columns if you map a " "dynamically sized Eigen Map type."); } if ((nb_rows < 1) or (nb_cols < 1)) { throw FieldError("Only positive numbers of rows and columns make " "sense"); } if (vec.size() % this->nb_components != 0) { std::stringstream err{}; err << "The vector size of " << vec.size() << " is not an integer multiple of the size of value_type, which " << "is " << this->nb_components << "."; throw std::runtime_error(err.str()); } } //! constructor from a *contiguous* array RawFieldMap(Eigen::Ref vec, Dim_t nb_rows = EigenMap::RowsAtCompileTime, Dim_t nb_cols = EigenMap::ColsAtCompileTime) : data{vec.data()}, nb_rows{nb_rows}, nb_cols{nb_cols}, nb_components{nb_rows * nb_cols}, nb_pixels(vec.size() / nb_components) { if (vec.size() % this->nb_components != 0) { std::stringstream err{}; err << "The vector size of " << vec.size() << " is not an integer multiple of the size of value_type, which " << "is " << this->nb_components << "."; throw std::runtime_error(err.str()); } } //! Copy constructor RawFieldMap(const RawFieldMap & other) = delete; //! Move constructor RawFieldMap(RawFieldMap && other) = default; //! Destructor virtual ~RawFieldMap() = default; //! Copy assignment operator RawFieldMap & operator=(const RawFieldMap & other) = delete; //! Move assignment operator RawFieldMap & operator=(RawFieldMap && other) = delete; //! returns number of EigenMaps stored within the array size_t size() const { return this->nb_pixels; } //! forward declaration of iterator type - template class iterator_t; + template + class iterator_t; using iterator = iterator_t; using const_iterator = iterator_t; //! returns an iterator to the first element iterator begin() { return iterator{*this, 0}; } const_iterator begin() const { return const_iterator{*this, 0}; } //! returns an iterator past the last element iterator end() { return iterator{*this, this->size()}; } const_iterator end() const { return const_iterator{*this, this->size()}; } //! evaluates the average of the field EigenPlain mean() const { using T_t = EigenPlain; T_t mean(T_t::Zero(this->nb_rows, this->nb_cols)); for (auto && val : *this) { mean += val; } mean /= this->size(); return mean; } protected: inline T_ptr get_data() { return data; } inline const T_ptr get_data() const { return data; } //! raw data pointer (ugly, I know) T_ptr data; const Dim_t nb_rows; const Dim_t nb_cols; const Dim_t nb_components; //! number of EigenMaps stored within the array size_t nb_pixels; private: }; /** * Small iterator class to be used with the RawFieldMap */ template template class RawFieldMap::iterator_t { public: //! short hand for the raw field map's type using Parent = RawFieldMap; //! the map needs to be friend in order to access the protected constructor friend Parent; //! stl compliance using value_type = std::conditional_t< IsConst, Eigen::Map, EigenMap>; using T_ptr = std::conditional_t; //! stl compliance using iterator_category = std::forward_iterator_tag; //! Default constructor iterator_t() = delete; //! Copy constructor iterator_t(const iterator_t & other) = default; //! Move constructor iterator_t(iterator_t && other) = default; //! Destructor virtual ~iterator_t() = default; //! Copy assignment operator iterator_t & operator=(const iterator_t & other) = default; //! Move assignment operator iterator_t & operator=(iterator_t && other) = default; //! pre-increment inline iterator_t & operator++() { ++this->index; return *this; } //! dereference inline value_type operator*() { return value_type(raw_ptr + this->map.nb_components * index, this->map.nb_rows, this->map.nb_cols); } //! inequality inline bool operator!=(const iterator_t & other) const { return this->index != other.index; } //! equality inline bool operator==(const iterator_t & other) const { return this->index == other.index; } protected: //! protected constructor iterator_t(const Parent & map, size_t start) : raw_ptr{map.get_data()}, map{map}, index{start} {} template iterator_t(std::enable_if_t map, size_t start) : raw_ptr{map.data}, map{map}, index{start} { static_assert(dummy_non_const == not IsConst, "SFINAE"); } //! raw data T_ptr raw_ptr; //! ref to underlying map const Parent & map; //! currently pointed-to element size_t index; private: }; } // namespace muSpectre #endif // SRC_COMMON_FIELD_MAP_HH_ diff --git a/src/common/field_map_base.hh b/src/common/field_map_base.hh index b12b8fd..e3ee1b6 100644 --- a/src/common/field_map_base.hh +++ b/src/common/field_map_base.hh @@ -1,887 +1,886 @@ /** * @file field_map.hh * * @author Till Junge * * @date 12 Sep 2017 * * @brief Defined a strongly defines proxy that iterates efficiently over a * field * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_MAP_BASE_HH_ #define SRC_COMMON_FIELD_MAP_BASE_HH_ -#include "common/common.hh" #include "common/field.hh" #include "field_collection_base.hh" #include #include #include #include namespace muSpectre { namespace internal { /** * Forward-declaration */ template class TypedSizedFieldBase; //! little helper to automate creation of const maps without duplication - template struct const_corrector { + template + struct const_corrector { //! non-const type using type = typename T::reference; }; //! specialisation for constant case - template struct const_corrector { + template + struct const_corrector { //! const type using type = typename T::const_reference; }; //! convenience alias template using const_corrector_t = typename const_corrector::type; //----------------------------------------------------------------------------// /** * `FieldMap` provides two central mechanisms: * - Map a field (that knows only about the size of the underlying object, * onto the mathematical object (reprensented by the respective Eigen class) * that provides linear algebra functionality. * - Provide an iterator that allows to iterate over all pixels. * A field is represented by `FieldBase` or a derived class. * `FieldMap` has the specialisations `MatrixLikeFieldMap`, * `ScalarFieldMap` and `TensorFieldMap`. */ template class FieldMap { static_assert((NbComponents != 0), "Fields with now components make no sense."); /* * Eigen::Dynamic is equal to -1, and is a legal value, hence * the following peculiar check */ static_assert( (NbComponents > -2), "Fields with a negative number of components make no sense."); public: //! Fundamental type stored using Scalar = T; //! number of scalars per entry constexpr static auto nb_components{NbComponents}; //! non-constant version of field using TypedField_nc = std::conditional_t< (NbComponents >= 1), TypedSizedFieldBase, TypedField>; //! field type as seen from iterator using TypedField_t = std::conditional_t; using Field = typename TypedField_nc::Base; //!< iterated field type //! const-correct field type using Field_c = std::conditional_t; using size_type = std::size_t; //!< stl conformance using pointer = std::conditional_t; //!< stl conformance //! Default constructor FieldMap() = delete; //! constructor explicit FieldMap(Field_c & field); //! constructor with run-time cost (for python and debugging) template explicit FieldMap(TypedSizedFieldBase & field); //! Copy constructor FieldMap(const FieldMap & other) = default; //! Move constructor FieldMap(FieldMap && other) = default; //! Destructor virtual ~FieldMap() = default; //! Copy assignment operator FieldMap & operator=(const FieldMap & other) = delete; //! Move assignment operator FieldMap & operator=(FieldMap && other) = delete; //! give human-readable field map type virtual std::string info_string() const = 0; //! return field name inline const std::string & get_name() const; //! return my collection (for iterating) inline const FieldCollection & get_collection() const; //! member access needs to be implemented by inheriting classes // inline value_type operator[](size_t index); // inline value_type operator[](Ccoord ccord); //! check compatibility (must be called by all inheriting classes at the //! end of their constructors inline void check_compatibility(); //! convenience call to collection's size method inline size_t size() const; //! compile-time compatibility check - template struct is_compatible; + template + struct is_compatible; /** * iterates over all pixels in the `muSpectre::FieldCollection` * and dereferences to an Eigen map to the currently used field. */ template class iterator; /** * Simple iterable proxy wrapper object around a FieldMap. When * iterated over, rather than dereferencing to the reference * type of iterator, it dereferences to a tuple of the pixel, * and the reference type of iterator */ - template class enumerator; + template + class enumerator; TypedField_t & get_field() { return this->field; } protected: //! raw pointer to entry (for Eigen Map) inline pointer get_ptr_to_entry(size_t index); //! raw pointer to entry (for Eigen Map) inline const T * get_ptr_to_entry(size_t index) const; const FieldCollection & collection; //!< collection holding Field TypedField_t & field; //!< mapped Field - - private: }; /** * iterates over all pixels in the `muSpectre::FieldCollection` * and dereferences to an Eigen map to the currently used field. */ template template class FieldMap::iterator { static_assert(!((ConstIter == false) && (ConstField == true)), "You can't have a non-const iterator over a const " "field"); public: //! for use by enumerator using FullyTypedFieldMap_t = FullyTypedFieldMap; //! stl conformance using value_type = const_corrector_t; //! stl conformance using const_value_type = const_corrector_t; //! stl conformance using pointer = typename FullyTypedFieldMap::pointer; //! stl conformance using difference_type = std::ptrdiff_t; //! stl conformance using iterator_category = std::random_access_iterator_tag; //! cell coordinates type using Ccoord = typename FieldCollection::Ccoord; //! stl conformance using reference = typename FullyTypedFieldMap::reference; //! fully typed reference as seen by the iterator using TypedMap_t = std::conditional_t; //! Default constructor iterator() = delete; //! constructor inline iterator(TypedMap_t & fieldmap, bool begin = true); //! constructor for random access inline iterator(TypedMap_t & fieldmap, size_t index); //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++(); //! post-increment inline iterator operator++(int); //! dereference inline value_type operator*(); //! dereference inline const_value_type operator*() const; //! member of pointer inline pointer operator->(); //! pre-decrement inline iterator & operator--(); //! post-decrement inline iterator operator--(int); //! access subscripting inline value_type operator[](difference_type diff); //! access subscripting inline const_value_type operator[](const difference_type diff) const; //! equality inline bool operator==(const iterator & other) const; //! inequality inline bool operator!=(const iterator & other) const; //! div. comparisons inline bool operator<(const iterator & other) const; //! div. comparisons inline bool operator<=(const iterator & other) const; //! div. comparisons inline bool operator>(const iterator & other) const; //! div. comparisons inline bool operator>=(const iterator & other) const; //! additions, subtractions and corresponding assignments inline iterator operator+(difference_type diff) const; //! additions, subtractions and corresponding assignments inline iterator operator-(difference_type diff) const; //! additions, subtractions and corresponding assignments inline iterator & operator+=(difference_type diff); //! additions, subtractions and corresponding assignments inline iterator & operator-=(difference_type diff); //! get pixel coordinates inline Ccoord get_ccoord() const; //! ostream operator (mainly for debugging) friend std::ostream & operator<<(std::ostream & os, const iterator & it) { if (ConstIter) { os << "const "; } os << "iterator on field '" << it.fieldmap.get_name() << "', entry " << it.index; return os; } protected: //! Copy constructor iterator(const iterator & other) = default; const FieldCollection & collection; //!< collection of the field TypedMap_t & fieldmap; //!< ref to the field itself size_t index; //!< index of currently pointed-to pixel - - private: }; /* ---------------------------------------------------------------------- */ template template class FieldMap::enumerator { public: //! fully typed reference as seen by the iterator using TypedMap_t = typename Iterator::TypedMap_t; //! Default constructor enumerator() = delete; //! constructor with field mapped enumerator(TypedMap_t & field_map) : field_map{field_map} {} /** * similar to iterators of the field map, but dereferences to a * tuple containing the cell coordinates and teh corresponding * entry */ class iterator; iterator begin() { return iterator(this->field_map); } iterator end() { return iterator(this->field_map, false); } protected: TypedMap_t & field_map; }; /* ---------------------------------------------------------------------- */ template template class FieldMap::enumerator::iterator { public: //! cell coordinates type using Ccoord = typename FieldCollection::Ccoord; //! stl conformance using value_type = std::tuple; //! stl conformance using const_value_type = std::tuple; //! stl conformance using difference_type = std::ptrdiff_t; //! stl conformance using iterator_category = std::random_access_iterator_tag; //! stl conformance using reference = std::tuple; //! Default constructor iterator() = delete; //! constructor for begin/end iterator(TypedMap_t & fieldmap, bool begin = true) : it{fieldmap, begin} {} //! constructor for random access iterator(TypedMap_t & fieldmap, size_t index) : it{fieldmap, index} {} //! constructor from iterator iterator(const SimpleIterator & it) : it{it} {} //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment iterator & operator++() { ++(this->it); return *this; } //! post-increment iterator operator++(int) { iterator current = *this; ++(this->it); return current; } //! dereference value_type operator*() { return value_type{it.get_ccoord(), *this->it}; } //! dereference const_value_type operator*() const { return const_value_type{it.get_ccoord(), *this->it}; } //! pre-decrement iterator & operator--() { --(this->it); return *this; } //! post-decrement iterator operator--(int) { iterator current = *this; --(this->it); return current; } //! access subscripting value_type operator[](difference_type diff) { SimpleIterator accessed{this->it + diff}; return *accessed; } //! access subscripting const_value_type operator[](const difference_type diff) const { SimpleIterator accessed{this->it + diff}; return *accessed; } //! equality bool operator==(const iterator & other) const { return this->it == other.it; } //! inequality bool operator!=(const iterator & other) const { return this->it != other.it; } //! div. comparisons bool operator<(const iterator & other) const { return this->it < other.it; } //! div. comparisons bool operator<=(const iterator & other) const { return this->it <= other.it; } //! div. comparisons bool operator>(const iterator & other) const { return this->it > other.it; } //! div. comparisons bool operator>=(const iterator & other) const { return this->it >= other.it; } //! additions, subtractions and corresponding assignments iterator operator+(difference_type diff) const { return iterator{this->it + diff}; } //! additions, subtractions and corresponding assignments iterator operator-(difference_type diff) const { return iterator{this->it - diff}; } //! additions, subtractions and corresponding assignments iterator & operator+=(difference_type diff) { this->it += diff; } //! additions, subtractions and corresponding assignments iterator & operator-=(difference_type diff) { this->it -= diff; } protected: SimpleIterator it; private: }; } // namespace internal namespace internal { /* ---------------------------------------------------------------------- */ template FieldMap::FieldMap( Field_c & field) : collection(field.get_collection()), field(static_cast(field)) { static_assert((NbComponents > 0) or (NbComponents == Eigen::Dynamic), "Only fields with more than 0 components allowed"); } /* ---------------------------------------------------------------------- */ template template FieldMap::FieldMap( TypedSizedFieldBase & field) : collection(field.get_collection()), field(static_cast(field)) { static_assert( std::is_same::value, "The field does not have the expected FieldCollection type"); static_assert(std::is_same::value, "The field does not have the expected Scalar type"); static_assert( (NbC == NbComponents), "The field does not have the expected number of components"); } /* ---------------------------------------------------------------------- */ template void FieldMap::check_compatibility() { if (typeid(T).hash_code() != this->field.get_stored_typeid().hash_code()) { std::string err{"Cannot create a Map of type '" + this->info_string() + "' for field '" + this->field.get_name() + "' of type '" + this->field.get_stored_typeid().name() + "'"}; throw FieldInterpretationError(err); } // check size compatibility if ((NbComponents != Dim_t(this->field.get_nb_components())) and (NbComponents != Eigen::Dynamic)) { throw FieldInterpretationError( "Cannot create a Map of type '" + this->info_string() + "' for field '" + this->field.get_name() + "' with " + std::to_string(this->field.get_nb_components()) + " components"); } } /* ---------------------------------------------------------------------- */ template size_t FieldMap::size() const { return this->collection.size(); } /* ---------------------------------------------------------------------- */ template template struct FieldMap::is_compatible { //! creates a more readable compile error constexpr static bool explain() { static_assert( std::is_same::value, "The field does not have the expected FieldCollection type"); static_assert(std::is_same::value, "The // field does not have the expected Scalar type"); static_assert( (TypedField_t::nb_components == NbComponents), "The field does not have the expected number of components"); // The static asserts wouldn't pass in the incompatible case, so this is // it return true; } //! evaluated compatibility constexpr static bool value{ std::is_base_of::value}; }; /* ---------------------------------------------------------------------- */ template const std::string & FieldMap::get_name() const { return this->field.get_name(); } /* ---------------------------------------------------------------------- */ template const FieldCollection & FieldMap::get_collection() const { return this->collection; } /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ // Iterator implementations //! constructor template template FieldMap::iterator< FullyTypedFieldMap, ConstIter>::iterator(TypedMap_t & fieldmap, bool begin) : collection(fieldmap.get_collection()), fieldmap(fieldmap), index(begin ? 0 : fieldmap.field.size()) {} /* ---------------------------------------------------------------------- */ //! constructor for random access template template FieldMap::iterator< FullyTypedFieldMap, ConstIter>::iterator(TypedMap_t & fieldmap, size_t index) : collection(fieldmap.collection), fieldmap(fieldmap), index(index) {} /* ---------------------------------------------------------------------- */ //! pre-increment template template typename FieldMap:: template iterator & FieldMap::iterator:: operator++() { this->index++; return *this; } /* ---------------------------------------------------------------------- */ //! post-increment template template typename FieldMap:: template iterator FieldMap::iterator:: operator++(int) { iterator current = *this; this->index++; return current; } /* ---------------------------------------------------------------------- */ //! dereference template template typename FieldMap:: template iterator::value_type FieldMap::iterator:: operator*() { return this->fieldmap.operator[](this->index); } /* ---------------------------------------------------------------------- */ //! dereference template template typename FieldMap:: template iterator::const_value_type FieldMap::iterator:: operator*() const { return this->fieldmap.operator[](this->index); } /* ---------------------------------------------------------------------- */ //! member of pointer template template typename FullyTypedFieldMap::pointer FieldMap::iterator:: operator->() { return this->fieldmap.ptr_to_val_t(this->index); } /* ---------------------------------------------------------------------- */ //! pre-decrement template template typename FieldMap:: template iterator & FieldMap::iterator:: operator--() { this->index--; return *this; } /* ---------------------------------------------------------------------- */ //! post-decrement template template typename FieldMap:: template iterator FieldMap::iterator:: operator--(int) { iterator current = *this; this->index--; return current; } /* ---------------------------------------------------------------------- */ //! Access subscripting template template typename FieldMap:: template iterator::value_type FieldMap::iterator:: operator[](difference_type diff) { return this->fieldmap[this->index + diff]; } /* ---------------------------------------------------------------------- */ //! Access subscripting template template typename FieldMap:: template iterator::const_value_type FieldMap::iterator:: operator[](const difference_type diff) const { return this->fieldmap[this->index + diff]; } /* ---------------------------------------------------------------------- */ //! equality template template bool FieldMap::iterator:: operator==(const iterator & other) const { return (this->index == other.index); } /* ---------------------------------------------------------------------- */ //! inquality template template bool FieldMap::iterator:: operator!=(const iterator & other) const { return !(*this == other); } /* ---------------------------------------------------------------------- */ //! div. comparisons template template bool FieldMap::iterator:: operator<(const iterator & other) const { return (this->index < other.index); } template template bool FieldMap::iterator:: operator<=(const iterator & other) const { return (this->index <= other.index); } template template bool FieldMap::iterator:: operator>(const iterator & other) const { return (this->index > other.index); } template template bool FieldMap::iterator:: operator>=(const iterator & other) const { return (this->index >= other.index); } /* ---------------------------------------------------------------------- */ //! additions, subtractions and corresponding assignments template template typename FieldMap:: template iterator FieldMap::iterator:: operator+(difference_type diff) const { return iterator(this->fieldmap, this->index + diff); } template template typename FieldMap:: template iterator FieldMap::iterator:: operator-(difference_type diff) const { return iterator(this->fieldmap, this->index - diff); } template template typename FieldMap:: template iterator & FieldMap::iterator:: operator+=(difference_type diff) { this->index += diff; return *this; } template template typename FieldMap:: template iterator & FieldMap::iterator:: operator-=(difference_type diff) { this->index -= diff; return *this; } /* ---------------------------------------------------------------------- */ //! get pixel coordinates template template typename FieldCollection::Ccoord FieldMap::iterator< FullyTypedFieldMap, ConstIter>::get_ccoord() const { return this->collection.get_ccoord(this->index); } ////----------------------------------------------------------------------------// // template std::ostream & operator << (std::ostream &os, // const typename FieldMap:: // template iterator & it) { // os << "iterator on field '" // << it.field.get_name() // << "', entry " << it.index; // return os; //} /* ---------------------------------------------------------------------- */ template typename FieldMap::pointer FieldMap::get_ptr_to_entry( size_t index) { return this->field.get_ptr_to_entry(std::move(index)); } /* ---------------------------------------------------------------------- */ template const T * FieldMap::get_ptr_to_entry( size_t index) const { return this->field.get_ptr_to_entry(std::move(index)); } } // namespace internal } // namespace muSpectre #endif // SRC_COMMON_FIELD_MAP_BASE_HH_ diff --git a/src/common/field_map_matrixlike.hh b/src/common/field_map_matrixlike.hh index d0e3b5c..88f26d8 100644 --- a/src/common/field_map_matrixlike.hh +++ b/src/common/field_map_matrixlike.hh @@ -1,379 +1,383 @@ /** * @file field_map_matrixlike.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief Eigen-Matrix and -Array maps over strongly typed fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ #define SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ #include "common/T4_map_proxy.hh" #include "common/field_map_base.hh" #include #include namespace muSpectre { namespace internal { /* ---------------------------------------------------------------------- */ /** * lists all matrix-like types consideres by * `muSpectre::internal::MatrixLikeFieldMap` */ enum class Map_t { Matrix, //!< for wrapping `Eigen::Matrix` Array, //!< for wrapping `Eigen::Array` T4Matrix //!< for wrapping `Eigen::T4Matrix` }; /** * traits structure to define the name shown when a * `muSpectre::MatrixLikeFieldMap` output into an ostream */ - template struct NameWrapper {}; + template + struct NameWrapper {}; /// specialisation for `muSpectre::ArrayFieldMap` - template <> struct NameWrapper { + template <> + struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "Array"; } }; /// specialisation for `muSpectre::MatrixFieldMap` - template <> struct NameWrapper { + template <> + struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "Matrix"; } }; /// specialisation for `muSpectre::T4MatrixFieldMap` - template <> struct NameWrapper { + template <> + struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "T4Matrix"; } }; /* ---------------------------------------------------------------------- */ /*! * A `MatrixLikeFieldMap` is the base class for maps of matrices, arrays and * fourth-order tensors mapped onto matrices. * * It should never be necessary to call directly any of the * constructors if this class, but rather use the template aliases: * - `muSpectre::ArrayFieldMap`: iterate in the form of `Eigen::Array<...>`. * - `muSpectre::MatrixFieldMap`: iterate in the form of * `Eigen::Matrix<...>`. * - `muSpectre::T4MatrixFieldMap`: iterate in the form of * `muSpectre::T4MatMap`. */ template class MatrixLikeFieldMap : public FieldMap { public: //! base class using Parent = FieldMap; //! sister class with all params equal, but ConstField guaranteed true using ConstMap = MatrixLikeFieldMap; using T_t = EigenPlain; //!< plain Eigen type to map //! cell coordinates type using Ccoord = Ccoord_t; using value_type = EigenArray; //!< stl conformance using const_reference = EigenConstArray; //!< stl conformance //! stl conformance using reference = std::conditional_t; // since it's a resource handle using size_type = typename Parent::size_type; //!< stl conformance using pointer = std::unique_ptr; //!< stl conformance using Field = typename Parent::Field; //!< stl conformance using Field_c = typename Parent::Field_c; //!< stl conformance //! stl conformance using const_iterator = typename Parent::template iterator; //! stl conformance using iterator = std::conditional_t< ConstField, const_iterator, typename Parent::template iterator>; using reverse_iterator = std::reverse_iterator; //!< stl conformance //! stl conformance using const_reverse_iterator = std::reverse_iterator; //! enumerator over a constant scalar field using const_enumerator = typename Parent::template enumerator; //! enumerator over a scalar field using enumerator = std::conditional_t>; //! give access to the protected fields friend iterator; //! Default constructor MatrixLikeFieldMap() = delete; /** * Constructor using a (non-typed) field. Compatibility is enforced at * runtime. This should not be a performance concern, as this constructor * will not be called in anny inner loops (if used as intended). */ explicit MatrixLikeFieldMap(Field_c & field); /** * Constructor using a typed field. Compatibility is enforced * statically. It is not always possible to call this constructor, as the * type of the field might not be known at compile time. */ template MatrixLikeFieldMap(TypedSizedFieldBase & field) // NOLINT : Parent(field) {} //! Copy constructor MatrixLikeFieldMap(const MatrixLikeFieldMap & other) = delete; //! Move constructorxo MatrixLikeFieldMap(MatrixLikeFieldMap && other) = default; //! Destructor virtual ~MatrixLikeFieldMap() = default; //! Copy assignment operator MatrixLikeFieldMap & operator=(const MatrixLikeFieldMap & other) = delete; //! Move assignment operator MatrixLikeFieldMap & operator=(MatrixLikeFieldMap && other) = delete; //! Assign a matrixlike value to every entry template inline MatrixLikeFieldMap & operator=(const Eigen::EigenBase & val); //! give human-readable field map type inline std::string info_string() const final; //! member access inline reference operator[](size_type index); //! member access inline reference operator[](const Ccoord & ccoord); //! member access inline const_reference operator[](size_type index) const; //! member access inline const_reference operator[](const Ccoord & ccoord) const; //! return an iterator to head of field for ranges inline iterator begin() { return std::move(iterator(*this)); } //! return an iterator to head of field for ranges inline const_iterator cbegin() const { return const_iterator(*this); } //! return an iterator to head of field for ranges inline const_iterator begin() const { return this->cbegin(); } //! return an iterator to tail of field for ranges inline iterator end() { return iterator(*this, false); } //! return an iterator to tail of field for ranges inline const_iterator cend() const { return const_iterator(*this, false); } //! return an iterator to tail of field for ranges inline const_iterator end() const { return this->cend(); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ enumerator enumerate() { return enumerator(*this); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ const_enumerator enumerate() const { return const_enumerator(*this); } //! evaluate the average of the field inline T_t mean() const; protected: //! for sad, legacy iterator use inline pointer ptr_to_val_t(size_type index); static const std::string field_info_root() { return NameWrapper::field_info_root(); } //!< for printing and debug private: }; /* ---------------------------------------------------------------------- */ template MatrixLikeFieldMap::MatrixLikeFieldMap(Field_c & field) : Parent(field) { this->check_compatibility(); } /* ---------------------------------------------------------------------- */ //! human-readable field map type template std::string MatrixLikeFieldMap::info_string() const { std::stringstream info; info << this->field_info_root() << "(" << typeid(typename EigenArray::value_type).name() << ", " << EigenArray::RowsAtCompileTime << "x" << EigenArray::ColsAtCompileTime << ")"; return info.str(); } /* ---------------------------------------------------------------------- */ //! member access template typename MatrixLikeFieldMap::reference MatrixLikeFieldMap:: operator[](size_type index) { return reference(this->get_ptr_to_entry(index)); } template typename MatrixLikeFieldMap::reference MatrixLikeFieldMap:: operator[](const Ccoord & ccoord) { size_t && index{this->collection.get_index(ccoord)}; return reference(this->get_ptr_to_entry(index)); } /* ---------------------------------------------------------------------- */ //! member access template typename MatrixLikeFieldMap::const_reference MatrixLikeFieldMap:: operator[](size_type index) const { return const_reference(this->get_ptr_to_entry(index)); } template typename MatrixLikeFieldMap::const_reference MatrixLikeFieldMap:: operator[](const Ccoord & ccoord) const { size_t && index{this->collection.get_index(ccoord)}; return const_reference(this->get_ptr_to_entry(index)); } //----------------------------------------------------------------------------// template template MatrixLikeFieldMap & MatrixLikeFieldMap:: operator=(const Eigen::EigenBase & val) { for (auto && entry : *this) { entry = val; } return *this; } /* ---------------------------------------------------------------------- */ template typename MatrixLikeFieldMap::T_t MatrixLikeFieldMap::mean() const { T_t mean{T_t::Zero()}; for (auto && val : *this) { mean += val; } mean *= 1. / Real(this->size()); return mean; } /* ---------------------------------------------------------------------- */ template typename MatrixLikeFieldMap::pointer MatrixLikeFieldMap::ptr_to_val_t(size_type index) { return std::make_unique( this->get_ptr_to_entry(std::move(index))); } } // namespace internal /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen matrix map as iterate template using MatrixFieldMap = internal::MatrixLikeFieldMap< FieldCollection, Eigen::Map>, Eigen::Map>, Eigen::Matrix, internal::Map_t::Matrix, ConstField>; /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen matrix map as iterate template using T4MatrixFieldMap = internal::MatrixLikeFieldMap, T4MatMap, T4Mat, internal::Map_t::T4Matrix, MapConst>; /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen array map as iterate template using ArrayFieldMap = internal::MatrixLikeFieldMap< FieldCollection, Eigen::Map>, Eigen::Map>, Eigen::Array, internal::Map_t::Array, ConstField>; } // namespace muSpectre #endif // SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ diff --git a/src/common/geometry.hh b/src/common/geometry.hh index 7af6d04..1a93223 100644 --- a/src/common/geometry.hh +++ b/src/common/geometry.hh @@ -1,252 +1,263 @@ /** * @file geometry.hh * * @author Till Junge * * @date 18 Apr 2018 * * @brief Geometric calculation helpers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Emacs; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "common/common.hh" #include "common/tensor_algebra.hh" #include "common/eigen_tools.hh" #include #include #include + #ifndef SRC_COMMON_GEOMETRY_HH_ #define SRC_COMMON_GEOMETRY_HH_ namespace muSpectre { /** * The rotation matrices depend on the order in which we rotate * around different axes. See [[ * https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix ]] to * find the matrices */ enum class RotationOrder { Z, XZXEuler, XYXEuler, YXYEuler, YZYEuler, ZYZEuler, ZXZEuler, XZYTaitBryan, XYZTaitBryan, YXZTaitBryan, YZXTaitBryan, ZYXTaitBryan, ZXYTaitBryan }; namespace internal { - template struct DefaultOrder { + template + struct DefaultOrder { constexpr static RotationOrder value{RotationOrder::ZXYTaitBryan}; }; - template <> struct DefaultOrder { + template <> + struct DefaultOrder { constexpr static RotationOrder value{RotationOrder::Z}; }; } // namespace internal template ::value> class Rotator { public: static_assert(((Dim == twoD) and (Order == RotationOrder::Z)) or ((Dim == threeD) and (Order != RotationOrder::Z)), "In 2d, only order 'Z' makes sense. In 3d, it doesn't"); using Angles_t = Eigen::Matrix; using RotMat_t = Eigen::Matrix; //! Default constructor Rotator() = delete; explicit Rotator(const Eigen::Ref & angles) : angles{angles}, rot_mat{this->compute_rotation_matrix()} {} //! Copy constructor Rotator(const Rotator & other) = default; //! Move constructor Rotator(Rotator && other) = default; //! Destructor virtual ~Rotator() = default; //! Copy assignment operator Rotator & operator=(const Rotator & other) = default; //! Move assignment operator Rotator & operator=(Rotator && other) = default; /** - * Applies the rotation into the frame define my the rotation + * Applies the rotation into the frame defined by the rotation * matrix * * @param input is a first-, second-, or fourth-rank tensor * (column vector, square matrix, or T4Matrix, or a Eigen::Map of * either of these, or an expression that evaluates into any of * these) */ - template inline decltype(auto) rotate(In_t && input); + template + inline decltype(auto) rotate(In_t && input); /** - * Applies the rotation back out from the frame define my the + * Applies the rotation back out from the frame defined by the * rotation matrix * * @param input is a first-, second-, or fourth-rank tensor * (column vector, square matrix, or T4Matrix, or a Eigen::Map of * either of these, or an expression that evaluates into any of * these) */ - template inline decltype(auto) rotate_back(In_t && input); + template + inline decltype(auto) rotate_back(In_t && input); const RotMat_t & get_rot_mat() const { return rot_mat; } protected: inline RotMat_t compute_rotation_matrix(); EIGEN_MAKE_ALIGNED_OPERATOR_NEW; Angles_t angles; RotMat_t rot_mat; private: }; namespace internal { - template struct RotationMatrixComputer {}; + template + struct RotationMatrixComputer {}; - template struct RotationMatrixComputer { + template + struct RotationMatrixComputer { constexpr static Dim_t Dim{twoD}; using RotMat_t = typename Rotator::RotMat_t; using Angles_t = typename Rotator::Angles_t; inline static decltype(auto) compute(const Eigen::Ref & angles) { static_assert(Order == RotationOrder::Z, "Two-d rotations can only be around the z axis"); return RotMat_t(Eigen::Rotation2Dd(angles(0))); } }; template struct RotationMatrixComputer { constexpr static Dim_t Dim{threeD}; using RotMat_t = typename Rotator::RotMat_t; using Angles_t = typename Rotator::Angles_t; inline static decltype(auto) compute(const Eigen::Ref & angles) { static_assert(Order != RotationOrder::Z, "three-d rotations cannot only be around the z axis"); switch (Order) { case RotationOrder::ZXZEuler: { return RotMat_t( (Eigen::AngleAxisd(angles(0), Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(angles(1), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(angles(2), Eigen::Vector3d::UnitZ()))); break; } case RotationOrder::ZXYTaitBryan: { return RotMat_t( (Eigen::AngleAxisd(angles(0), Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(angles(1), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(angles(2), Eigen::Vector3d::UnitY()))); } default: { throw std::runtime_error("not yet implemented."); } } } }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto Rotator::compute_rotation_matrix() -> RotMat_t { return internal::RotationMatrixComputer::compute(this->angles); } namespace internal { - template struct RotationHelper {}; + template + struct RotationHelper {}; /* ---------------------------------------------------------------------- */ - template <> struct RotationHelper { + template <> + struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { return R * input; } }; /* ---------------------------------------------------------------------- */ - template <> struct RotationHelper { + template <> + struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { return R * input * R.transpose(); } }; /* ---------------------------------------------------------------------- */ - template <> struct RotationHelper { + template <> + struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { constexpr Dim_t Dim{EigenCheck::tensor_dim::value}; auto && rotator_forward{ Matrices::outer_under(R.transpose(), R.transpose())}; auto && rotator_back = Matrices::outer_under(R, R); - // unclear behaviour. When I return this value as an - // expression, clange segfaults or returns an uninitialised - // tensor + // Clarification. When I return this value as an + // expression, clang segfaults or returns an uninitialised + // tensor, hence the explicit cast into a T4Mat. return T4Mat(rotator_back * input * rotator_forward); } }; } // namespace internal /* ---------------------------------------------------------------------- */ template template auto Rotator::rotate(In_t && input) -> decltype(auto) { constexpr Dim_t tensor_rank{EigenCheck::tensor_rank::value}; return internal::RotationHelper::rotate( std::forward(input), this->rot_mat); } /* ---------------------------------------------------------------------- */ template template auto Rotator::rotate_back(In_t && input) -> decltype(auto) { constexpr Dim_t tensor_rank{EigenCheck::tensor_rank::value}; return internal::RotationHelper::rotate( std::forward(input), this->rot_mat.transpose()); } } // namespace muSpectre #endif // SRC_COMMON_GEOMETRY_HH_ diff --git a/src/common/iterators.hh b/src/common/iterators.hh index 18414b8..dec4a59 100644 --- a/src/common/iterators.hh +++ b/src/common/iterators.hh @@ -1,357 +1,367 @@ /** * @file iterators.hh * * @author Nicolas Richart * * @date creation Wed Jul 19 2017 * * @brief iterator interfaces * * Copyright (©) 2010-2011 EPFL (Ecole Polytechnique Fédérale de Lausanne) * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * * Akantu is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Akantu is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with Akantu. If not, see . * * Above block was left intact as in akantu. µSpectre exercises the * right to redistribute and modify the code below * */ /* -------------------------------------------------------------------------- */ #include #include /* -------------------------------------------------------------------------- */ #ifndef SRC_COMMON_ITERATORS_HH_ #define SRC_COMMON_ITERATORS_HH_ namespace akantu { namespace tuple { /* ------------------------------------------------------------------------ */ namespace details { //! static for loop - template struct Foreach { + template + struct Foreach { //! undocumented template static inline bool not_equal(Tuple && a, Tuple && b) { if (std::get(std::forward(a)) == std::get(std::forward(b))) return false; return Foreach::not_equal(std::forward(a), std::forward(b)); } }; /* ---------------------------------------------------------------------- */ //! static comparison - template <> struct Foreach<0> { + template <> + struct Foreach<0> { //! undocumented template static inline bool not_equal(Tuple && a, Tuple && b) { return std::get<0>(std::forward(a)) != std::get<0>(std::forward(b)); } }; //! eats up a bunch of arguments and returns them packed in a tuple template decltype(auto) make_tuple_no_decay(Ts &&... args) { return std::tuple(std::forward(args)...); } //! helper for static for loop template void foreach_impl(F && func, Tuple && tuple, std::index_sequence &&) { (void)std::initializer_list{ (std::forward(func)(std::get(std::forward(tuple))), 0)...}; } //! detail template decltype(auto) transform_impl(F && func, Tuple && tuple, std::index_sequence &&) { return make_tuple_no_decay( std::forward(func)(std::get(std::forward(tuple)))...); } }; // namespace details /* ------------------------------------------------------------------------ */ //! detail - template bool are_not_equal(Tuple && a, Tuple && b) { + template + bool are_not_equal(Tuple && a, Tuple && b) { return details::Foreach>::value>:: not_equal(std::forward(a), std::forward(b)); } //! detail - template void foreach_(F && func, Tuple && tuple) { + template + void foreach_(F && func, Tuple && tuple) { return details::foreach_impl( std::forward(func), std::forward(tuple), std::make_index_sequence< std::tuple_size>::value>{}); } //! detail template decltype(auto) transform(F && func, Tuple && tuple) { return details::transform_impl( std::forward(func), std::forward(tuple), std::make_index_sequence< std::tuple_size>::value>{}); } } // namespace tuple /* -------------------------------------------------------------------------- */ namespace iterators { //! iterator for emulation of python zip - template class ZipIterator { + template + class ZipIterator { private: using tuple_t = std::tuple; public: //! undocumented - ZipIterator(tuple_t iterators) : iterators(std::move(iterators)) {} + explicit ZipIterator(tuple_t iterators) + : iterators(std::move(iterators)) {} //! undocumented decltype(auto) operator*() { return tuple::transform( [](auto && it) -> decltype(auto) { return *it; }, iterators); } //! undocumented ZipIterator & operator++() { tuple::foreach_([](auto && it) { ++it; }, iterators); return *this; } //! undocumented bool operator==(const ZipIterator & other) const { return not tuple::are_not_equal(iterators, other.iterators); } //! undocumented bool operator!=(const ZipIterator & other) const { return tuple::are_not_equal(iterators, other.iterators); } private: tuple_t iterators; }; } // namespace iterators /* -------------------------------------------------------------------------- */ //! emulates python zip() template decltype(auto) zip_iterator(std::tuple && iterators_tuple) { auto zip = iterators::ZipIterator( std::forward(iterators_tuple)); return zip; } /* -------------------------------------------------------------------------- */ namespace containers { //! helper for the emulation of python zip - template class ZipContainer { + template + class ZipContainer { using containers_t = std::tuple; public: //! undocumented explicit ZipContainer(Containers &&... containers) : containers(std::forward(containers)...) {} //! undocumented decltype(auto) begin() const { return zip_iterator( tuple::transform([](auto && c) { return c.begin(); }, std::forward(containers))); } //! undocumented decltype(auto) end() const { return zip_iterator( tuple::transform([](auto && c) { return c.end(); }, std::forward(containers))); } //! undocumented decltype(auto) begin() { return zip_iterator( tuple::transform([](auto && c) { return c.begin(); }, std::forward(containers))); } //! undocumented decltype(auto) end() { return zip_iterator( tuple::transform([](auto && c) { return c.end(); }, std::forward(containers))); } private: containers_t containers; }; } // namespace containers /* -------------------------------------------------------------------------- */ /** * emulates python's zip() */ - template decltype(auto) zip(Containers &&... conts) { + template + decltype(auto) zip(Containers &&... conts) { return containers::ZipContainer( std::forward(conts)...); } /* -------------------------------------------------------------------------- */ /* Arange */ /* -------------------------------------------------------------------------- */ namespace iterators { /** * emulates python's range iterator */ - template class ArangeIterator { + template + class ArangeIterator { public: //! undocumented using value_type = T; //! undocumented using pointer = T *; //! undocumented using reference = T &; //! undocumented using iterator_category = std::input_iterator_tag; //! undocumented constexpr ArangeIterator(T value, T step) : value(value), step(step) {} //! undocumented constexpr ArangeIterator(const ArangeIterator &) = default; //! undocumented constexpr ArangeIterator & operator++() { value += step; return *this; } //! undocumented constexpr const T & operator*() const { return value; } //! undocumented constexpr bool operator==(const ArangeIterator & other) const { return (value == other.value) and (step == other.step); } //! undocumented constexpr bool operator!=(const ArangeIterator & other) const { return not operator==(other); } private: T value{0}; const T step{1}; }; } // namespace iterators namespace containers { //! helper class to generate range iterators - template class ArangeContainer { + template + class ArangeContainer { public: //! undocumented using iterator = iterators::ArangeIterator; //! undocumented constexpr ArangeContainer(T start, T stop, T step = 1) : start(start), stop((stop - start) % step == 0 ? stop : start + (1 + (stop - start) / step) * step), step(step) {} //! undocumented explicit constexpr ArangeContainer(T stop) : ArangeContainer(0, stop, 1) {} //! undocumented constexpr T operator[](size_t i) { T val = start + i * step; assert(val < stop && "i is out of range"); return val; } //! undocumented constexpr T size() { return (stop - start) / step; } //! undocumented constexpr iterator begin() { return iterator(start, step); } //! undocumented constexpr iterator end() { return iterator(stop, step); } private: const T start{0}, stop{0}, step{1}; }; } // namespace containers /** * emulates python's range() */ template >::value>> inline decltype(auto) arange(const T & stop) { return containers::ArangeContainer(stop); } /** * emulates python's range() */ template >::value>> inline constexpr decltype(auto) arange(const T1 & start, const T2 & stop) { return containers::ArangeContainer>(start, stop); } /** * emulates python's range() */ template >::value>> inline constexpr decltype(auto) arange(const T1 & start, const T2 & stop, const T3 & step) { return containers::ArangeContainer>( start, stop, step); } /* -------------------------------------------------------------------------- */ /** * emulates python's enumerate */ template inline constexpr decltype(auto) enumerate(Container && container, size_t start_ = 0) { auto stop = std::forward(container).size(); decltype(stop) start = start_; return zip(arange(start, stop), std::forward(container)); } } // namespace akantu #endif // SRC_COMMON_ITERATORS_HH_ diff --git a/src/common/ref_array.hh b/src/common/ref_array.hh index 8af77fb..c9e11df 100644 --- a/src/common/ref_array.hh +++ b/src/common/ref_array.hh @@ -1,97 +1,100 @@ /** * file ref_array.hh * * @author Till Junge * * @date 04 Dec 2018 * * @brief convenience class to simulate an array of references * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GNU Emacs; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_REF_ARRAY_HH_ #define SRC_COMMON_REF_ARRAY_HH_ #include #include #include "common/iterators.hh" namespace muSpectre { namespace internal { template struct TypeChecker { constexpr static bool value{ std::is_same>::value and TypeChecker::value}; }; - template struct TypeChecker { + template + struct TypeChecker { constexpr static bool value{ std::is_same>::value}; }; } // namespace internal - template class RefArray { + template + class RefArray { public: //! Default constructor RefArray() = delete; - template RefArray(Vals &... vals) : values{&vals...} { + template + explicit RefArray(Vals &... vals) : values{&vals...} { static_assert(internal::TypeChecker::value, "Only refs to type T allowed"); } //! Copy constructor RefArray(const RefArray & other) = default; //! Move constructor RefArray(RefArray && other) = default; //! Destructor virtual ~RefArray() = default; //! Copy assignment operator RefArray & operator=(const RefArray & other) = default; //! Move assignment operator RefArray & operator=(RefArray && other) = delete; T & operator[](size_t index) { return *this->values[index]; } constexpr T & operator[](size_t index) const { return *this->values[index]; } protected: std::array values{}; private: }; } // namespace muSpectre #endif // SRC_COMMON_REF_ARRAY_HH_ diff --git a/src/common/statefield.hh b/src/common/statefield.hh index b59f36f..243d908 100644 --- a/src/common/statefield.hh +++ b/src/common/statefield.hh @@ -1,673 +1,676 @@ /** * file statefield.hh * * @author Till Junge * * @date 28 Feb 2018 * * @brief A state field is an abstraction of a field that can hold * current, as well as a chosen number of previous values. This is * useful for instance for internal state variables in plastic laws, * where a current, new, or trial state is computed based on its * previous state, and at convergence, this new state gets cycled into * the old, the old into the old-1 etc. The state field abstraction * helps doing this safely (i.e. only const references to the old * states are available, while the current state can be assigned * to/modified), and efficiently (i.e., no need to copy values from * new to old, we just cycle the labels). This file implements the * state field as well as state maps using the Field, FieldCollection * and FieldMap abstractions of µSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_STATEFIELD_HH_ #define SRC_COMMON_STATEFIELD_HH_ -#include "field.hh" -#include "field_helpers.hh" -#include "utilities.hh" -#include "ref_array.hh" +#include "common/field_helpers.hh" +#include "common/field.hh" +#include "common/ref_array.hh" #include #include #include namespace muSpectre { /** * Forward-declaration */ - template class TypedField; + template + class TypedField; /** * Base class for state fields, useful for storing polymorphic references */ - template class StateFieldBase { + template + class StateFieldBase { public: //! get naming prefix const std::string & get_prefix() const { return this->prefix; } //! get a ref to the `StateField` 's field collection const FieldCollection & get_collection() const { return this->collection; } virtual ~StateFieldBase() = default; /** * returns number of old states that are stored */ size_t get_nb_memory() const { return this->nb_memory; } //! return type_id of stored type virtual const std::type_info & get_stored_typeid() const = 0; /** * cycle the fields (current becomes old, old becomes older, * oldest becomes current) */ virtual void cycle() = 0; protected: //! constructor StateFieldBase(std::string unique_prefix, const FieldCollection & collection, size_t nb_memory = 1) : prefix{unique_prefix}, nb_memory{nb_memory}, collection{collection} {} /** * the unique prefix is used as the first part of the unique name * of the subfields belonging to this state field */ std::string prefix; /** * number of old states to store, defaults to 1 */ const size_t nb_memory; //! reference to the collection this statefield belongs to const FieldCollection & collection; }; /* ---------------------------------------------------------------------- */ template class TypedStateField : public StateFieldBase { public: //! Parent class using Parent = StateFieldBase; //! Typed field using TypedField_t = TypedField; //! returns a TypedField ref to the current value of this state field virtual TypedField_t & get_current_field() = 0; //! returns a const TypedField ref to an old value of this state field virtual const TypedField_t & get_old_field(size_t nb_steps_ago = 1) const = 0; //! returns a `StateField` reference if `other is a compatible state field inline static TypedStateField & check_ref(Parent & other) { // the following triggers and exception if the fields are incompatible if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a rerference of requested type " << "for statefield '" << other.get_prefix() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } return static_cast(other); } //! return type_id of stored type const std::type_info & get_stored_typeid() const final { return typeid(T); }; virtual ~TypedStateField() = default; protected: //! constructor TypedStateField(const std::string & unique_prefix, const FieldCollection & collection, size_t nb_memory) : Parent{unique_prefix, collection, nb_memory} {} }; /* ---------------------------------------------------------------------- */ template class TypedSizedStateField : public TypedStateField { public: //! Parent class using Parent = TypedStateField; //! the current (historically accurate) ordering of the fields using index_t = std::array; //! get the current ordering of the fields inline const index_t & get_indices() const { return this->indices; } //! destructor virtual ~TypedSizedStateField() = default; protected: //! constructor TypedSizedStateField(std::string unique_prefix, const FieldCollection & collection, index_t indices) : Parent{unique_prefix, collection, nb_memory}, indices{indices} {}; index_t indices; ///< these are cycled through }; //! early declaration - template class StateFieldMap; + template + class StateFieldMap; namespace internal { template inline decltype(auto) build_fields_helper(std::string prefix, typename Field::Base::collection_t & collection, std::index_sequence) { auto get_field{[&prefix, &collection](size_t i) -> Field & { std::stringstream name_stream{}; name_stream << prefix << ", sub_field index " << i; return make_field(name_stream.str(), collection); }}; return RefArray(get_field(I)...); } /* ---------------------------------------------------------------------- */ template inline decltype(auto) build_indices(std::index_sequence) { return std::array{(size - I) % size...}; } } // namespace internal /** * A statefield is an abstraction around a Field that can hold a * current and `nb_memory` previous values. There are useful for * history variables, for instance. */ template class StateField : public TypedSizedStateField { public: //! the underlying field's collection type using FieldCollection_t = typename Field_t::Base::collection_t; //! base type for fields using Scalar = typename Field_t::Scalar; //! Base class for all state fields of same memory using Base = TypedSizedStateField; /** * storage of field refs (can't be a `std::array`, because arrays * of refs are explicitely forbidden */ using Fields_t = RefArray; //! Typed field using TypedField_t = TypedField; //! Default constructor StateField() = delete; //! Copy constructor StateField(const StateField & other) = delete; - //! Move coonstructor + //! Move constructor StateField(StateField && other) = delete; //! Destructor virtual ~StateField() = default; //! Copy assignment operator StateField & operator=(const StateField & other) = delete; //! Move assignment operator StateField & operator=(StateField && other) = delete; //! get (modifiable) current field inline Field_t & current() { return this->fields[this->indices[0]]; } //! get (constant) previous field - template inline const Field_t & old() { + template + inline const Field_t & old() { static_assert(nb_steps_ago <= nb_memory, "you can't go that far inte the past"); static_assert(nb_steps_ago > 0, "Did you mean to call current()?"); return this->fields[this->indices.at(nb_steps_ago)]; } //! returns a TypedField ref to the current value of this state field TypedField_t & get_current_field() final { return this->current(); } //! returns a const TypedField ref to an old value of this state field const TypedField_t & get_old_field(size_t nb_steps_ago = 1) const final { return this->fields[this->indices.at(nb_steps_ago)]; } //! factory function template friend StateFieldType & make_statefield(const std::string & unique_prefix, CollectionType & collection); //! returns a `StateField` reference if `other is a compatible state field inline static StateField & check_ref(Base & other) { // the following triggers and exception if the fields are incompatible Field_t::check_ref(other.fields[0]); return static_cast(other); } //! returns a const `StateField` reference if `other` is a compatible state //! field inline static const StateField & check_ref(const Base & other) { // the following triggers and exception if the fields are incompatible Field_t::check_ref(other.fields[0]); return static_cast(other); } //! get a ref to the `StateField` 's fields Fields_t & get_fields() { return this->fields; } /** * Pure convenience functions to get a MatrixFieldMap of * appropriate dimensions mapped to this field. You can also * create other types of maps, as long as they have the right * fundamental type (T), the correct size (nbComponents), and * memory (nb_memory). */ inline decltype(auto) get_map() { using FieldMap = decltype(this->fields[0].get_map()); return StateFieldMap(*this); } /** * Pure convenience functions to get a MatrixFieldMap of * appropriate dimensions mapped to this field. You can also * create other types of maps, as long as they have the right * fundamental type (T), the correct size (nbComponents), and * memory (nb_memory). */ inline decltype(auto) get_const_map() { using FieldMap = decltype(this->fields[0].get_const_map()); return StateFieldMap(*this); } /** * cycle the fields (current becomes old, old becomes older, * oldest becomes current) */ inline void cycle() final { for (auto & val : this->indices) { val = (val + 1) % (nb_memory + 1); } } protected: /** * Constructor. @param unique_prefix is used to create the names * of the fields that this abstraction creates in the background * @param collection is the field collection in which the * subfields will be stored */ inline StateField(const std::string & unique_prefix, FieldCollection_t & collection) : Base{unique_prefix, collection, internal::build_indices( std::make_index_sequence{})}, fields{internal::build_fields_helper( unique_prefix, collection, std::make_index_sequence{})} {} Fields_t fields; //!< container for the states private: }; namespace internal { template inline decltype(auto) build_maps_helper(Fields & fields, std::index_sequence) { return std::array{FieldMap(fields[I])...}; } } // namespace internal /* ---------------------------------------------------------------------- */ template inline StateFieldType & make_statefield(const std::string & unique_prefix, CollectionType & collection) { std::unique_ptr ptr{ new StateFieldType(unique_prefix, collection)}; auto & retref{*ptr}; collection.register_statefield(std::move(ptr)); return retref; } /** * extends the StateField <-> Field equivalence to StateFieldMap <-> FieldMap */ - template class StateFieldMap { + template + class StateFieldMap { public: /** * iterates over all pixels in the `muSpectre::FieldCollection` and * dereferences to a proxy giving access to the appropriate iterates * of the underlying `FieldMap` type. */ class iterator; //! stl conformance using reference = typename iterator::reference; //! stl conformance using value_type = typename iterator::value_type; //! stl conformance using size_type = typename iterator::size_type; //! field collection type where this state field can be stored using FieldCollection_t = typename FieldMap::Field::collection_t; //! Fundamental type stored using Scalar = typename FieldMap::Scalar; //! base class (must be at least sized) using TypedSizedStateField_t = TypedSizedStateField; //! for traits access using FieldMap_t = FieldMap; //! for traits access using ConstFieldMap_t = typename FieldMap::ConstMap; //! Default constructor StateFieldMap() = delete; //! constructor using a StateField template explicit StateFieldMap(StateField & statefield) : collection{statefield.get_collection()}, statefield{statefield}, maps{internal::build_maps_helper( statefield.get_fields(), std::make_index_sequence{})}, const_maps{ internal::build_maps_helper( statefield.get_fields(), std::make_index_sequence{})} { static_assert(std::is_base_of::value, "Not the right type of StateField ref"); } //! Copy constructor StateFieldMap(const StateFieldMap & other) = delete; //! Move constructor StateFieldMap(StateFieldMap && other) = default; //! Destructor virtual ~StateFieldMap() = default; //! Copy assignment operator StateFieldMap & operator=(const StateFieldMap & other) = delete; //! Move assignment operator StateFieldMap & operator=(StateFieldMap && other) = delete; //! access the wrapper to a given pixel directly value_type operator[](size_type index) { return *iterator(*this, index); } /** * return a ref to the current field map. useful for instance for * initialisations of `StateField` instances */ FieldMap & current() { return this->maps[this->statefield.get_indices()[0]]; } //! stl conformance iterator begin() { return iterator(*this, 0); } //! stl conformance iterator end() { return iterator(*this, this->collection.size()); } protected: const FieldCollection_t & collection; //!< collection holding the field TypedSizedStateField_t & statefield; //!< ref to the field itself std::array maps; //!< refs to the addressable maps; //! const refs to the addressable maps; std::array const_maps; private: }; /** * Iterator class used by the `StateFieldMap` */ template class StateFieldMap::iterator { public: class StateWrapper; using Ccoord = typename FieldMap::Ccoord; //!< cell coordinates type using value_type = StateWrapper; //!< stl conformance using const_value_type = value_type; //!< stl conformance using pointer_type = value_type *; //!< stl conformance using difference_type = std::ptrdiff_t; //!< stl conformance using size_type = size_t; //!< stl conformance using iterator_category = std::random_access_iterator_tag; //!< stl conformance using reference = StateWrapper; //!< stl conformance //! Default constructor iterator() = delete; //! constructor iterator(StateFieldMap & map, size_t index = 0) : index{index}, map{map} {}; //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++() { this->index++; return *this; } //! post-increment inline iterator operator++(int) { iterator curr{*this}; this->index++; return curr; } //! dereference inline value_type operator*() { return value_type(*this); } //! pre-decrement inline iterator & operator--() { this->index--; return *this; } //! post-decrement inline iterator operator--(int) { iterator curr{*this}; this->index--; return curr; } //! access subscripting inline value_type operator[](difference_type diff) { return value_type{iterator{this->map, this->index + diff}}; } //! equality inline bool operator==(const iterator & other) const { return this->index == other.index; } //! inequality inline bool operator!=(const iterator & other) const { return this->index != other.index; } //! div. comparisons inline bool operator<(const iterator & other) const { return this->index < other.index; } //! div. comparisons inline bool operator<=(const iterator & other) const { return this->index <= other.index; } //! div. comparisons inline bool operator>(const iterator & other) const { return this->index > other.index; } //! div. comparisons inline bool operator>=(const iterator & other) const { return this->index >= other.index; } //! additions, subtractions and corresponding assignments inline iterator operator+(difference_type diff) const { return iterator{this->map, this - index + diff}; } //! additions, subtractions and corresponding assignments inline iterator operator-(difference_type diff) const { return iterator{this->map, this - index - diff}; } //! additions, subtractions and corresponding assignments inline iterator & operator+=(difference_type diff) { this->index += diff; return *this; } //! additions, subtractions and corresponding assignments inline iterator & operator-=(difference_type diff) { this->index -= diff; return *this; } //! get pixel coordinates inline Ccoord get_ccoord() const { return this->map.collection.get_ccoord(this->index); } //! access the index inline const size_t & get_index() const { return this->index; } protected: size_t index; //!< current pixel this iterator refers to StateFieldMap & map; //!< map over with `this` iterates - - private: }; namespace internal { //! FieldMap is an `Eigen::Map` or `Eigen::TensorMap` here template inline Array build_old_vals_helper(iterator & it, maps_t & maps, indices_t & indices, std::index_sequence) { return Array{maps[indices[I + 1]][it.get_index()]...}; } template inline Array build_old_vals(iterator & it, maps_t & maps, indices_t & indices) { return build_old_vals_helper(it, maps, indices, std::make_index_sequence{}); } } // namespace internal /** * Light-weight resource-handle representing the current and old * values of a field at a given pixel identified by an iterator * pointing to it */ template class StateFieldMap::iterator::StateWrapper { public: //! short-hand using iterator = typename StateFieldMap::iterator; //! short-hand using Ccoord = typename iterator::Ccoord; //! short-hand using Map = typename FieldMap::reference; //! short-hand using ConstMap = typename FieldMap::const_reference; /** * storage type differs depending on whether Map is a Reference type (in the * C++ sense) or not, because arrays of references are forbidden */ using Array_t = std::conditional_t< std::is_reference::value, RefArray, nb_memory>, std::array>; //! Default constructor StateWrapper() = delete; //! Copy constructor StateWrapper(const StateWrapper & other) = default; //! Move constructor StateWrapper(StateWrapper && other) = default; //! construct with `StateFieldMap::iterator` StateWrapper(iterator & it) : it{it}, current_val{ it.map.maps[it.map.statefield.get_indices()[0]][it.index]}, old_vals(internal::build_old_vals( it, it.map.const_maps, it.map.statefield.get_indices())) {} //! Destructor virtual ~StateWrapper() = default; //! Copy assignment operator StateWrapper & operator=(const StateWrapper & other) = default; //! Move assignment operator StateWrapper & operator=(StateWrapper && other) = default; //! returns reference to the currectly mapped value inline Map & current() { return this->current_val; } //! recurnts reference the the value that was current `nb_steps_ago` ago - template inline const ConstMap & old() const { + template + inline const ConstMap & old() const { static_assert(nb_steps_ago <= nb_memory, "You have not stored that time step"); static_assert(nb_steps_ago > 0, "Did you mean to access the current value? If so, use " "current()"); return this->old_vals[nb_steps_ago - 1]; } //! read the coordinates of the current pixel inline Ccoord get_ccoord() const { return this->it.get_ccoord(); } protected: iterator & it; //!< ref to the iterator that dereferences to `this` Map current_val; //!< current value Array_t old_vals; //!< all stored old values }; } // namespace muSpectre #endif // SRC_COMMON_STATEFIELD_HH_ diff --git a/src/common/tensor_algebra.hh b/src/common/tensor_algebra.hh index 3d47b42..cf12935 100644 --- a/src/common/tensor_algebra.hh +++ b/src/common/tensor_algebra.hh @@ -1,365 +1,380 @@ /** * @file tensor_algebra.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief collection of compile-time quantities and algrebraic functions for * tensor operations * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_TENSOR_ALGEBRA_HH_ #define SRC_COMMON_TENSOR_ALGEBRA_HH_ #include "common/T4_map_proxy.hh" #include "common/common.hh" #include "common/eigen_tools.hh" #include #include #include namespace muSpectre { namespace Tensors { //! second-order tensor representation template using Tens2_t = Eigen::TensorFixedSize>; //! fourth-order tensor representation template using Tens4_t = Eigen::TensorFixedSize>; //----------------------------------------------------------------------------// //! compile-time second-order identity - template constexpr inline Tens2_t I2() { + template + constexpr inline Tens2_t I2() { Tens2_t T; using Mat_t = Eigen::Matrix; Eigen::Map(&T(0, 0)) = Mat_t::Identity(); return T; } /* ---------------------------------------------------------------------- */ //! Check whether a given expression represents a Tensor specified order - template struct is_tensor { + template + struct is_tensor { //! evaluated test constexpr static bool value = (std::is_convertible>::value || std::is_convertible>::value || std::is_convertible>::value); }; /* ---------------------------------------------------------------------- */ /** compile-time outer tensor product as defined by Curnier * R_ijkl = A_ij.B_klxx * 0123 01 23 */ template constexpr inline decltype(auto) outer(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t order{2}; static_assert(is_tensor::value, "T1 needs to be convertible to a second order Tensor"); static_assert(is_tensor::value, "T2 needs to be convertible to a second order Tensor"); // actual function std::array, 0> dims{}; return A.contract(B, dims); } /* ---------------------------------------------------------------------- */ /** compile-time underlined outer tensor product as defined by Curnier * R_ijkl = A_ik.B_jlxx * 0123 02 13 * 0213 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_under(T1 && A, T2 && B) { constexpr size_t order{4}; return outer(A, B).shuffle(std::array{{0, 2, 1, 3}}); } /* ---------------------------------------------------------------------- */ /** compile-time overlined outer tensor product as defined by Curnier * R_ijkl = A_il.B_jkxx * 0123 03 12 * 0231 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_over(T1 && A, T2 && B) { constexpr size_t order{4}; return outer(A, B).shuffle(std::array{{0, 2, 3, 1}}); } //! compile-time fourth-order symmetrising identity - template constexpr inline Tens4_t I4S() { + template + constexpr inline Tens4_t I4S() { auto I = I2(); return 0.5 * (outer_under(I, I) + outer_over(I, I)); } } // namespace Tensors namespace Matrices { //! second-order tensor representation - template using Tens2_t = Eigen::Matrix; + template + using Tens2_t = Eigen::Matrix; //! fourth-order tensor representation - template using Tens4_t = T4Mat; + template + using Tens4_t = T4Mat; //----------------------------------------------------------------------------// //! compile-time second-order identity - template constexpr inline Tens2_t I2() { + template + constexpr inline Tens2_t I2() { return Tens2_t::Identity(); } /* ---------------------------------------------------------------------- */ /** compile-time outer tensor product as defined by Curnier * R_ijkl = A_ij.B_klxx * 0123 01 23 */ template constexpr inline decltype(auto) outer(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, j) * B(k, l); } } } } return product; } /* ---------------------------------------------------------------------- */ /** compile-time underlined outer tensor product as defined by Curnier * R_ijkl = A_ik.B_jlxx * 0123 02 13 * 0213 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_under(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, k) * B(j, l); } } } } return product; } /* ---------------------------------------------------------------------- */ /** compile-time overlined outer tensor product as defined by Curnier * R_ijkl = A_il.B_jkxx * 0123 03 12 * 0231 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_over(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, l) * B(j, k); } } } } return product; } /** * Standart tensor multiplication */ template constexpr inline decltype(auto) tensmult(const Eigen::MatrixBase & A, const Eigen::MatrixBase & B) { constexpr Dim_t dim{T2::RowsAtCompileTime}; static_assert(dim == T2::ColsAtCompileTime, "B is not square"); static_assert(dim != Eigen::Dynamic, "B not statically sized"); static_assert(dim * dim == T4::RowsAtCompileTime, "A and B not compatible"); static_assert(T4::RowsAtCompileTime == T4::ColsAtCompileTime, "A is not square"); Tens2_t result; result.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { result(i, j) += get(A, i, j, k, l) * B(k, l); } } } } return result; } //! compile-time fourth-order tracer - template constexpr inline Tens4_t Itrac() { + template + constexpr inline Tens4_t Itrac() { auto I = I2(); return outer(I, I); } //! compile-time fourth-order identity - template constexpr inline Tens4_t Iiden() { + template + constexpr inline Tens4_t Iiden() { auto I = I2(); return outer_under(I, I); } //! compile-time fourth-order transposer - template constexpr inline Tens4_t Itrns() { + template + constexpr inline Tens4_t Itrns() { auto I = I2(); return outer_over(I, I); } //! compile-time fourth-order symmetriser - template constexpr inline Tens4_t Isymm() { + template + constexpr inline Tens4_t Isymm() { auto I = I2(); return 0.5 * (outer_under(I, I) + outer_over(I, I)); } namespace internal { /* ---------------------------------------------------------------------- */ - template struct Dotter {}; + template + struct Dotter {}; /* ---------------------------------------------------------------------- */ - template struct Dotter { + template + struct Dotter { template static constexpr decltype(auto) dot(T1 && t1, T2 && t2) { using T4_t = T4Mat::Scalar, Dim>; T4_t ret_val{T4_t::Zero()}; for (Int i = 0; i < Dim; ++i) { for (Int a = 0; a < Dim; ++a) { for (Int j = 0; j < Dim; ++j) { for (Int k = 0; k < Dim; ++k) { for (Int l = 0; l < Dim; ++l) { get(ret_val, i, j, k, l) += t1(i, a) * get(t2, a, j, k, l); } } } } } return ret_val; } }; /* ---------------------------------------------------------------------- */ - template struct Dotter { + template + struct Dotter { template static constexpr decltype(auto) dot(T4 && t4, T2 && t2) { using T4_t = T4Mat::Scalar, Dim>; T4_t ret_val{T4_t::Zero()}; for (Int i = 0; i < Dim; ++i) { for (Int j = 0; j < Dim; ++j) { for (Int k = 0; k < Dim; ++k) { for (Int a = 0; a < Dim; ++a) { for (Int l = 0; l < Dim; ++l) { get(ret_val, i, j, k, l) += get(t4, i, j, k, a) * t2(a, l); } } } } } return ret_val; } }; /* ---------------------------------------------------------------------- */ - template struct Dotter { + template + struct Dotter { template static constexpr decltype(auto) ddot(T1 && t1, T2 && t2) { return t1 * t2; } }; /* ---------------------------------------------------------------------- */ - template struct Dotter { + template + struct Dotter { template static constexpr decltype(auto) ddot(T1 && t1, T2 && t2) { return (t1 * t2.transpose()).trace(); } }; } // namespace internal /* ---------------------------------------------------------------------- */ template decltype(auto) dot(T1 && t1, T2 && t2) { constexpr Dim_t rank1{EigenCheck::tensor_rank::value}; constexpr Dim_t rank2{EigenCheck::tensor_rank::value}; return internal::Dotter::dot(std::forward(t1), std::forward(t2)); } /* ---------------------------------------------------------------------- */ template decltype(auto) ddot(T1 && t1, T2 && t2) { constexpr Dim_t rank1{EigenCheck::tensor_rank::value}; constexpr Dim_t rank2{EigenCheck::tensor_rank::value}; return internal::Dotter::ddot(std::forward(t1), std::forward(t2)); } } // namespace Matrices } // namespace muSpectre #endif // SRC_COMMON_TENSOR_ALGEBRA_HH_ diff --git a/src/common/utilities.hh b/src/common/utilities.hh index 57adfde..57ad212 100644 --- a/src/common/utilities.hh +++ b/src/common/utilities.hh @@ -1,184 +1,185 @@ /** * @file utilities.hh * * @author Till Junge * * @date 17 Nov 2017 * * @brief additions to the standard name space to anticipate C++17 features * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_UTILITIES_HH_ #define SRC_COMMON_UTILITIES_HH_ #include #ifdef NO_EXPERIMENTAL #include #else #include #endif namespace std_replacement { namespace detail { - template struct is_reference_wrapper : std::false_type {}; + template + struct is_reference_wrapper : std::false_type {}; template struct is_reference_wrapper> : std::true_type {}; //! from cppreference template auto INVOKE(T Base::*pmf, Derived && ref, Args &&... args) noexcept(noexcept( (std::forward(ref).*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && std::is_base_of>::value, decltype((std::forward(ref).* pmf)(std::forward(args)...))> { return (std::forward(ref).*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmf, RefWrap && ref, Args &&... args) noexcept( noexcept((ref.get().*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && is_reference_wrapper>::value, decltype((ref.get().*pmf)(std::forward(args)...))> { return (ref.get().*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmf, Pointer && ptr, Args &&... args) noexcept(noexcept( ((*std::forward(ptr)).*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && !is_reference_wrapper>::value && !std::is_base_of>::value, decltype(((*std::forward(ptr)).* pmf)(std::forward(args)...))> { return ((*std::forward(ptr)).*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmd, Derived && ref) noexcept(noexcept(std::forward(ref).*pmd)) -> std::enable_if_t< !std::is_function::value && std::is_base_of>::value, decltype(std::forward(ref).*pmd)> { return std::forward(ref).*pmd; } //! from cppreference template auto INVOKE(T Base::*pmd, RefWrap && ref) noexcept(noexcept(ref.get().*pmd)) -> std::enable_if_t< !std::is_function::value && is_reference_wrapper>::value, decltype(ref.get().*pmd)> { return ref.get().*pmd; } //! from cppreference template auto INVOKE(T Base::*pmd, Pointer && ptr) noexcept( noexcept((*std::forward(ptr)).*pmd)) -> std::enable_if_t< !std::is_function::value && !is_reference_wrapper>::value && !std::is_base_of>::value, decltype((*std::forward(ptr)).*pmd)> { return (*std::forward(ptr)).*pmd; } //! from cppreference template auto INVOKE(F && f, Args &&... args) noexcept( noexcept(std::forward(f)(std::forward(args)...))) -> std::enable_if_t< !std::is_member_pointer>::value, decltype(std::forward(f)(std::forward(args)...))> { return std::forward(f)(std::forward(args)...); } } // namespace detail //! from cppreference template auto invoke(F && f, ArgTypes &&... args) // exception specification for QoI noexcept(noexcept(detail::INVOKE(std::forward(f), std::forward(args)...))) -> decltype(detail::INVOKE(std::forward(f), std::forward(args)...)) { return detail::INVOKE(std::forward(f), std::forward(args)...); } namespace detail { //! from cppreference template constexpr decltype(auto) apply_impl(F && f, Tuple && t, std::index_sequence) { return std_replacement::invoke(std::forward(f), std::get(std::forward(t))...); } } // namespace detail //! from cppreference template constexpr decltype(auto) apply(F && f, Tuple && t) { return detail::apply_impl( std::forward(f), std::forward(t), std::make_index_sequence< std::tuple_size>::value>{}); } } // namespace std_replacement namespace muSpectre { using std_replacement::apply; /** * emulation `std::optional` (a C++17 feature) */ template #ifdef NO_EXPERIMENTAL using optional = typename boost::optional; #else using optional = typename std::experimental::optional; #endif } // namespace muSpectre #endif // SRC_COMMON_UTILITIES_HH_ diff --git a/src/common/voigt_conversion.hh b/src/common/voigt_conversion.hh index 4b44d37..0050e32 100644 --- a/src/common/voigt_conversion.hh +++ b/src/common/voigt_conversion.hh @@ -1,219 +1,220 @@ /** * @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 Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_COMMON_VOIGT_CONVERSION_HH_ #define SRC_COMMON_VOIGT_CONVERSION_HH_ #include "common/common.hh" #include #include #include namespace muSpectre { /** * implements a bunch of static functions to convert between full * and Voigt notation of tensors */ - template class VoigtConversion { + 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 static const Eigen::Matrix mat; //! matrix of vector index I as function of tensor indices i,j static const Eigen::Matrix sym_mat; //! array of matrix indices ij as function of vector index I static const Eigen::Matrix vec; //! factors to multiply the strain by for voigt notation static const Eigen::Matrix factors; }; //! voigt vector indices for non-symmetric tensors template <> const Eigen::Matrix VoigtConversion<1>::mat = (Eigen::Matrix() << 0).finished(); //! voigt vector indices for non-symmetric tensors template <> const Eigen::Matrix VoigtConversion<2>::mat = (Eigen::Matrix() << 0, 2, 3, 1).finished(); //! voigt vector indices for non-symmetric tensors template <> const Eigen::Matrix VoigtConversion<3>::mat = (Eigen::Matrix() << 0, 5, 4, 8, 1, 3, 7, 6, 2).finished(); //! voigt vector indices template <> const Eigen::Matrix VoigtConversion<1>::sym_mat = (Eigen::Matrix() << 0).finished(); //! voigt vector indices template <> const Eigen::Matrix VoigtConversion<2>::sym_mat = (Eigen::Matrix() << 0, 2, 2, 1).finished(); //! voigt vector indices template <> const Eigen::Matrix VoigtConversion<3>::sym_mat = (Eigen::Matrix() << 0, 5, 4, 5, 1, 3, 4, 3, 2).finished(); //! matrix indices from voigt vectors template <> const Eigen::Matrix VoigtConversion<1>::vec = (Eigen::Matrix() << 0, 0).finished(); //! matrix indices from voigt vectors template <> const Eigen::Matrix VoigtConversion<2>::vec = (Eigen::Matrix() << 0, 0, 1, 1, 0, 1, 1, 0).finished(); //! matrix indices from voigt vectors template <> const Eigen::Matrix VoigtConversion<3>::vec = (Eigen::Matrix() << 0, 0, 1, 1, 2, 2, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0) .finished(); //! factors for shear components in voigt notation template <> const Eigen::Matrix VoigtConversion<1>::factors = (Eigen::Matrix() << 1).finished(); //! factors for shear components in voigt notation template <> const Eigen::Matrix VoigtConversion<2>::factors = (Eigen::Matrix() << 1, 1, 2).finished(); //! factors for shear components in voigt notation template <> const Eigen::Matrix VoigtConversion<3>::factors = (Eigen::Matrix() << 1, 1, 1, 2, 2, 2).finished(); //----------------------------------------------------------------------------// template template inline void VoigtConversion::fourth_to_voigt(const Tens4 & t, Voigt & v) { // upper case indices for Voigt notation, lower case for standard tensorial for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); for (Dim_t J = 0; J < vsize(dim); ++J) { auto && k = vec(J, 0); auto && l = vec(J, 1); v(I, J) = t(i, j, k, l); } } } //----------------------------------------------------------------------------// template template inline Eigen::Matrix(dim), vsize(dim)> VoigtConversion::fourth_to_voigt(const Tens4 & t) { using V_t = Eigen::Matrix(dim), vsize(dim)>; V_t temp; fourth_to_voigt(t, temp); return temp; } //----------------------------------------------------------------------------// template template inline void VoigtConversion::second_to_voigt(const Tens2 & F, Voigt & v) { for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = F(i, j); } } //----------------------------------------------------------------------------// template template inline void VoigtConversion::gradient_to_voigt_strain(const Tens2 & F, Voigt & v) { for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = (F(i, j) + F(j, i)) / 2 * factors(I); } } //----------------------------------------------------------------------------// template template inline void VoigtConversion::gradient_to_voigt_GreenLagrange_strain(const Tens2 & F, Voigt & v) { using mat = Eigen::Matrix; mat E = 0.5 * (F.transpose() * F - mat::Identity()); for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = E(i, j) * factors(I); } } } // namespace muSpectre #endif // SRC_COMMON_VOIGT_CONVERSION_HH_ diff --git a/src/fft/fft_engine_base.cc b/src/fft/fft_engine_base.cc index 0b13831..3db922e 100644 --- a/src/fft/fft_engine_base.cc +++ b/src/fft/fft_engine_base.cc @@ -1,70 +1,72 @@ /** * @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 Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/fft_engine_base.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ 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, nb_components)}, norm_factor{1. / CcoordOps::get_size(domain_resolutions)}, nb_components{nb_components} {} /* ---------------------------------------------------------------------- */ template void FFTEngineBase::initialise(FFT_PlanFlags /*plan_flags*/) { this->work_space_container.initialise(); } /* ---------------------------------------------------------------------- */ - template size_t FFTEngineBase::size() const { + 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; } // namespace muSpectre diff --git a/src/fft/fft_engine_base.hh b/src/fft/fft_engine_base.hh index 6b28837..4760f11 100644 --- a/src/fft/fft_engine_base.hh +++ b/src/fft/fft_engine_base.hh @@ -1,185 +1,186 @@ /** * @file fft_engine_base.hh * * @author Till Junge * * @date 01 Dec 2017 * * @brief Interface for FFT engines * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_FFT_ENGINE_BASE_HH_ #define SRC_FFT_FFT_ENGINE_BASE_HH_ #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 class FFTEngineBase { + template + class FFTEngineBase { public: constexpr static Dim_t sdim{DimS}; //!< spatial dimension of the cell //! cell coordinates type using Ccoord = Ccoord_t; //! global FieldCollection using GFieldCollection_t = GlobalFieldCollection; //! local FieldCollection (for Fourier-space pixels) using LFieldCollection_t = LocalFieldCollection; //! Field type on which to apply the projection using Field_t = TypedField; /** * Field type holding a Fourier-space representation of a * real-valued second-order tensor field */ 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, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTEngineBase(const FFTEngineBase & other) = delete; //! Move constructor FFTEngineBase(FFTEngineBase && other) = default; //! Destructor virtual ~FFTEngineBase() = default; //! Copy assignment operator FFTEngineBase & operator=(const FFTEngineBase & other) = delete; //! Move assignment operator FFTEngineBase & operator=(FFTEngineBase && other) = default; //! compute the plan, etc virtual void initialise(FFT_PlanFlags /*plan_flags*/); //! forward transform (dummy for interface) virtual Workspace_t & fft(Field_t & /*field*/) = 0; //! inverse transform (dummy for interface) virtual void ifft(Field_t & /*field*/) const = 0; /** * iterators over only those pixels that exist in frequency space * (i.e. about half of all pixels, see rfft) */ //! returns an iterator to the first pixel in Fourier space inline iterator begin() { return this->work_space_container.begin(); } //! returns an iterator past to the last pixel in Fourier space inline iterator end() { return this->work_space_container.end(); } //! nb of pixels (mostly for debugging) size_t size() const; //! nb of pixels in Fourier space size_t workspace_size() const; //! return the communicator object const Communicator & get_communicator() const { return this->comm; } //! returns the process-local resolutions of the cell const Ccoord & get_subdomain_resolutions() const { return this->subdomain_resolutions; } //! returns the process-local locations of the cell const Ccoord & get_subdomain_locations() const { return this->subdomain_locations; } //! returns the process-local resolutions of the cell in Fourier space const Ccoord & get_fourier_resolutions() const { return this->fourier_resolutions; } //! returns the process-local locations of the cell in Fourier space const Ccoord & get_fourier_locations() const { return this->fourier_locations; } //! returns the resolutions of the cell const Ccoord & get_domain_resolutions() const { return this->domain_resolutions; } //! only required for testing and debugging LFieldCollection_t & get_field_collection() { return this->work_space_container; } //! only required for testing and debugging Workspace_t & get_work_space() { return this->work; } //! factor by which to multiply projection before inverse transform (this is //! typically 1/nb_pixels for so-called unnormalized transforms (see, //! e.g. //! http://www.fftw.org/fftw3_doc/Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data //! or https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.fft.html //! . Rather than scaling the inverse transform (which would cost one more //! loop), FFT engines provide this value so it can be used in the //! projection operator (where no additional loop is required) inline Real normalisation() const { return norm_factor; } //! return the number of components per pixel Dim_t get_nb_components() const { return nb_components; } protected: /** * Field collection in which to store fields associated with * Fourier-space points */ Communicator comm; //!< communicator LFieldCollection_t work_space_container{}; Ccoord subdomain_resolutions; //!< resolutions of the process-local //!< (subdomain) portion of the cell Ccoord subdomain_locations; // !< location of the process-local (subdomain) // portion of the cell Ccoord fourier_resolutions; //!< resolutions of the process-local (subdomain) //!< portion of the Fourier transformed data Ccoord fourier_locations; // !< location of the process-local (subdomain) // portion of the Fourier transformed data const Ccoord domain_resolutions; //!< resolutions of the full domain of the cell Workspace_t & work; //!< field to store the Fourier transform of P const Real norm_factor; //!< normalisation coefficient of fourier transform Dim_t nb_components; private: }; } // namespace muSpectre #endif // SRC_FFT_FFT_ENGINE_BASE_HH_ diff --git a/src/fft/fft_utils.hh b/src/fft/fft_utils.hh index e4dfade..6ddf14b 100644 --- a/src/fft/fft_utils.hh +++ b/src/fft/fft_utils.hh @@ -1,130 +1,131 @@ /** * @file fft_utils.hh * * @author Till Junge * * @date 06 Dec 2017 * * @brief collection of functions used in the context of spectral operations * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_FFT_UTILS_HH_ #define SRC_FFT_FFT_UTILS_HH_ #include "common/common.hh" #include #include #include namespace muSpectre { /** * compute fft frequencies (in time (or length) units of of sampling * periods), see numpy's fftfreq function for reference */ std::valarray fft_freqs(size_t nb_samples); /** * compute fft frequencies in correct length or time units. Here, * length refers to the total size of the domain over which the fft * is taken (for instance the length of an edge of an RVE) */ std::valarray fft_freqs(size_t nb_samples, Real length); /** * Get fft_freqs for a grid */ template inline std::array, dim> fft_freqs(Ccoord_t sizes, std::array lengths) { std::array, dim> retval{}; for (size_t i = 0; i < dim; ++i) { retval[i] = std::move(fft_freqs(sizes[i], lengths[i])); } return retval; } /** * simple class encapsulating the creation, and retrieval of * wave vectors */ - template class FFT_freqs { + template + class FFT_freqs { public: //! return type for wave vectors using Vector = Eigen::Matrix; //! Default constructor FFT_freqs() = delete; //! constructor with problem sizes FFT_freqs(Ccoord_t sizes, std::array lengths) : freqs{fft_freqs(sizes, lengths)} {} //! Copy constructor FFT_freqs(const FFT_freqs & other) = delete; //! Move constructor FFT_freqs(FFT_freqs && other) = default; //! Destructor virtual ~FFT_freqs() = default; //! Copy assignment operator FFT_freqs & operator=(const FFT_freqs & other) = delete; //! Move assignment operator FFT_freqs & operator=(FFT_freqs && other) = default; //! get unnormalised wave vector (in sampling units) inline Vector get_xi(const Ccoord_t ccoord) const; //! get normalised wave vector inline Vector get_unit_xi(const Ccoord_t ccoord) const { auto && xi = this->get_xi(std::move(ccoord)); return xi / xi.norm(); } protected: //! container for frequencies ordered by spatial dimension const std::array, dim> freqs; private: }; template typename FFT_freqs::Vector FFT_freqs::get_xi(const Ccoord_t ccoord) const { Vector retval{}; for (Dim_t i = 0; i < dim; ++i) { retval(i) = this->freqs[i][ccoord[i]]; } return retval; } } // namespace muSpectre #endif // SRC_FFT_FFT_UTILS_HH_ diff --git a/src/fft/fftw_engine.cc b/src/fft/fftw_engine.cc index 97ed6f0..5fc5db0 100644 --- a/src/fft/fftw_engine.cc +++ b/src/fft/fftw_engine.cc @@ -1,156 +1,158 @@ /** * @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 Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/fftw_engine.hh" #include "common/ccoord_operations.hh" namespace muSpectre { template FFTWEngine::FFTWEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm} { for (auto && pixel : CcoordOps::Pixels(this->fourier_resolutions)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void FFTWEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } Parent::initialise(plan_flags); const int & rank = Dim; std::array narr; const int * const n = &narr[0]; std::copy(this->subdomain_resolutions.begin(), this->subdomain_resolutions.end(), narr.begin()); int howmany = this->nb_components; // temporary buffer for plan size_t alloc_size = (CcoordOps::get_size(this->subdomain_resolutions) * howmany); 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(Till): We cannot run fftw_cleanup since subsequent FFTW calls will // fail but multiple FFT engines can be active at the same time. // fftw_cleanup(); } /* ---------------------------------------------------------------------- */ template typename FFTWEngine::Workspace_t & FFTWEngine::fft(Field_t & field) { if (this->plan_fft == nullptr) { throw std::runtime_error("fft plan not initialised"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } fftw_execute_dft_r2c(this->plan_fft, field.data(), reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ - template void FFTWEngine::ifft(Field_t & field) const { + template + void FFTWEngine::ifft(Field_t & field) const { if (this->plan_ifft == nullptr) { throw std::runtime_error("ifft plan not initialised"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } fftw_execute_dft_c2r(this->plan_ifft, reinterpret_cast(this->work.data()), field.data()); } template class FFTWEngine; template class FFTWEngine; } // namespace muSpectre diff --git a/src/fft/fftw_engine.hh b/src/fft/fftw_engine.hh index a2a828f..e2d482e 100644 --- a/src/fft/fftw_engine.hh +++ b/src/fft/fftw_engine.hh @@ -1,97 +1,96 @@ /** * @file fftw_engine.hh * * @author Till Junge * * @date 03 Dec 2017 * * @brief FFT engine using FFTW * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_FFTW_ENGINE_HH_ #define SRC_FFT_FFTW_ENGINE_HH_ #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 Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor FFTWEngine() = delete; //! Constructor with cell resolutions FFTWEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTWEngine(const FFTWEngine & other) = delete; //! Move constructor FFTWEngine(FFTWEngine && other) = default; //! Destructor virtual ~FFTWEngine() noexcept; //! Copy assignment operator FFTWEngine & operator=(const FFTWEngine & other) = delete; //! Move assignment operator FFTWEngine & operator=(FFTWEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: fftw_plan plan_fft{}; //!< holds the plan for forward fourier transform fftw_plan plan_ifft{}; //!< holds the plan for inverse fourier transform bool initialised{false}; //!< to prevent double initialisation - - private: }; } // namespace muSpectre #endif // SRC_FFT_FFTW_ENGINE_HH_ diff --git a/src/fft/fftwmpi_engine.cc b/src/fft/fftwmpi_engine.cc index fa02a6f..b862339 100644 --- a/src/fft/fftwmpi_engine.cc +++ b/src/fft/fftwmpi_engine.cc @@ -1,233 +1,236 @@ /** * @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 Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/fftwmpi_engine.hh" #include "common/ccoord_operations.hh" namespace muSpectre { - template int FFTWMPIEngine::nb_engines{0}; + template + int FFTWMPIEngine::nb_engines{0}; template FFTWMPIEngine::FFTWMPIEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm} { if (!this->nb_engines) fftw_mpi_init(); this->nb_engines++; std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); narr[Dim - 1] = this->domain_resolutions[Dim - 1] / 2 + 1; ptrdiff_t res_x, loc_x, res_y, loc_y; this->workspace_size = fftw_mpi_local_size_many_transposed( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, this->comm.get_mpi_comm(), &res_x, &loc_x, &res_y, &loc_y); this->fourier_resolutions[1] = this->fourier_resolutions[0]; this->fourier_locations[1] = this->fourier_locations[0]; this->subdomain_resolutions[0] = res_x; this->subdomain_locations[0] = loc_x; this->fourier_resolutions[0] = res_y; this->fourier_locations[0] = loc_y; for (auto & n : this->subdomain_resolutions) { if (n == 0) { throw std::runtime_error("FFTW MPI planning returned zero resolution. " "You may need to run on fewer processes."); } } for (auto & n : this->fourier_resolutions) { if (n == 0) { throw std::runtime_error("FFTW MPI planning returned zero Fourier " "resolution. You may need to run on fewer " "processes."); } } for (auto && pixel : std::conditional_t, CcoordOps::Pixels>( this->fourier_resolutions, this->fourier_locations)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void FFTWMPIEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } // Initialize parent after local resolutions have been determined and // work space has been initialized Parent::initialise(plan_flags); this->real_workspace = fftw_alloc_real(2 * this->workspace_size); // We need to check whether the workspace provided by our field is large // enough. MPI parallel FFTW may request a workspace size larger than the // nominal size of the complex buffer. if (static_cast(this->work.size() * this->nb_components) < this->workspace_size) { this->work.set_pad_size(this->workspace_size - this->nb_components * this->work.size()); } unsigned int flags; switch (plan_flags) { case FFT_PlanFlags::estimate: { flags = FFTW_ESTIMATE; break; } case FFT_PlanFlags::measure: { flags = FFTW_MEASURE; break; } case FFT_PlanFlags::patient: { flags = FFTW_PATIENT; break; } default: throw std::runtime_error("unknown planner flag type"); break; } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); Real * in{this->real_workspace}; fftw_complex * out{reinterpret_cast(this->work.data())}; this->plan_fft = fftw_mpi_plan_many_dft_r2c( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, in, out, this->comm.get_mpi_comm(), FFTW_MPI_TRANSPOSED_OUT | flags); if (this->plan_fft == nullptr) { throw std::runtime_error("r2c plan failed"); } fftw_complex * i_in = reinterpret_cast(this->work.data()); Real * i_out = this->real_workspace; this->plan_ifft = fftw_mpi_plan_many_dft_c2r( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, i_in, i_out, this->comm.get_mpi_comm(), FFTW_MPI_TRANSPOSED_IN | flags); if (this->plan_ifft == nullptr) { throw std::runtime_error("c2r plan failed"); } this->initialised = true; } /* ---------------------------------------------------------------------- */ - template FFTWMPIEngine::~FFTWMPIEngine() noexcept { + template + FFTWMPIEngine::~FFTWMPIEngine() noexcept { if (this->real_workspace != nullptr) fftw_free(this->real_workspace); if (this->plan_fft != nullptr) fftw_destroy_plan(this->plan_fft); if (this->plan_ifft != nullptr) fftw_destroy_plan(this->plan_ifft); // TODO(junge): We cannot run fftw_mpi_cleanup since also calls fftw_cleanup // and any running FFTWEngine will fail afterwards. // this->nb_engines--; // if (!this->nb_engines) fftw_mpi_cleanup(); } /* ---------------------------------------------------------------------- */ template typename FFTWMPIEngine::Workspace_t & FFTWMPIEngine::fft(Field_t & field) { if (this->plan_fft == nullptr) { throw std::runtime_error("fft plan not initialised"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Copy non-padded field to padded real_workspace. // Transposed output of M x N x L transform for >= 3 dimensions is padded // M x N x 2*(L/2+1). ptrdiff_t fstride = (this->nb_components * this->subdomain_resolutions[Dim - 1]); ptrdiff_t wstride = (this->nb_components * 2 * (this->subdomain_resolutions[Dim - 1] / 2 + 1)); ptrdiff_t n = field.size() / this->subdomain_resolutions[Dim - 1]; auto fdata = field.data(); auto wdata = this->real_workspace; for (int i = 0; i < n; i++) { std::copy(fdata, fdata + fstride, wdata); fdata += fstride; wdata += wstride; } // Compute FFT fftw_mpi_execute_dft_r2c( this->plan_fft, this->real_workspace, reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ - template void FFTWMPIEngine::ifft(Field_t & field) const { + template + void FFTWMPIEngine::ifft(Field_t & field) const { if (this->plan_ifft == nullptr) { throw std::runtime_error("ifft plan not initialised"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Compute inverse FFT fftw_mpi_execute_dft_c2r( this->plan_ifft, reinterpret_cast(this->work.data()), this->real_workspace); // Copy non-padded field to padded real_workspace. // Transposed output of M x N x L transform for >= 3 dimensions is padded // M x N x 2*(L/2+1). ptrdiff_t fstride{this->nb_components * this->subdomain_resolutions[Dim - 1]}; ptrdiff_t wstride{this->nb_components * 2 * (this->subdomain_resolutions[Dim - 1] / 2 + 1)}; ptrdiff_t n(field.size() / this->subdomain_resolutions[Dim - 1]); auto fdata{field.data()}; auto wdata{this->real_workspace}; for (int i = 0; i < n; i++) { std::copy(wdata, wdata + fstride, fdata); fdata += fstride; wdata += wstride; } } template class FFTWMPIEngine; template class FFTWMPIEngine; } // namespace muSpectre diff --git a/src/fft/fftwmpi_engine.hh b/src/fft/fftwmpi_engine.hh index 46e77b6..aecb4cd 100644 --- a/src/fft/fftwmpi_engine.hh +++ b/src/fft/fftwmpi_engine.hh @@ -1,103 +1,102 @@ /** * @file fftwmpi_engine.hh * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief FFT engine using MPI-parallel FFTW * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_FFTWMPI_ENGINE_HH_ #define SRC_FFT_FFTWMPI_ENGINE_HH_ #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 Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor FFTWMPIEngine() = delete; //! Constructor with system resolutions FFTWMPIEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTWMPIEngine(const FFTWMPIEngine & other) = delete; //! Move constructor FFTWMPIEngine(FFTWMPIEngine && other) = default; //! Destructor virtual ~FFTWMPIEngine() noexcept; //! Copy assignment operator FFTWMPIEngine & operator=(const FFTWMPIEngine & other) = delete; //! Move assignment operator FFTWMPIEngine & operator=(FFTWMPIEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: static int nb_engines; //!< number of times this engine has been instatiated fftw_plan plan_fft{}; //!< holds the plan for forward fourier transform fftw_plan plan_ifft{}; //!< holds the plan for inverse fourier transform ptrdiff_t workspace_size{}; //!< size of workspace buffer returned by planner Real * real_workspace{}; //!< temporary real workspace that is correctly //!< padded bool initialised{false}; //!< to prevent double initialisation - - private: }; } // namespace muSpectre #endif // SRC_FFT_FFTWMPI_ENGINE_HH_ diff --git a/src/fft/pfft_engine.cc b/src/fft/pfft_engine.cc index bc638a3..47d5ba8 100644 --- a/src/fft/pfft_engine.cc +++ b/src/fft/pfft_engine.cc @@ -1,241 +1,244 @@ /** * @file pfft_engine.cc * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief implements the MPI-parallel pfft engine * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "fft/pfft_engine.hh" #include "common/ccoord_operations.hh" namespace muSpectre { - template int PFFTEngine::nb_engines{0}; + template + int PFFTEngine::nb_engines{0}; template PFFTEngine::PFFTEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm}, mpi_comm{ comm.get_mpi_comm()} { if (!this->nb_engines) pfft_init(); this->nb_engines++; int size{comm.size()}; int dim_x{size}; int dim_y{1}; // Note: All TODOs below don't affect the function of the PFFT engine. It // presently uses slab decompositions, the TODOs are what needs to be done // to get stripe decomposition to work - but it does not work yet. Slab // vs stripe decomposition may have an impact on how the code scales. // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. // if (DimS > 2) { if (false) { dim_y = static_cast(sqrt(size)); while ((size / dim_y) * dim_y != size) dim_y--; dim_x = size / dim_y; } // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. if (DimS > 2) { if (false) { if (pfft_create_procmesh_2d(this->comm.get_mpi_comm(), dim_x, dim_y, &this->mpi_comm)) { throw std::runtime_error("Failed to create 2d PFFT process mesh."); } } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); ptrdiff_t res[DimS], loc[DimS], fres[DimS], floc[DimS]; this->workspace_size = pfft_local_size_many_dft_r2c( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, this->mpi_comm, PFFT_TRANSPOSED_OUT, res, loc, fres, floc); std::copy(res, res + DimS, this->subdomain_resolutions.begin()); std::copy(loc, loc + DimS, this->subdomain_locations.begin()); std::copy(fres, fres + DimS, this->fourier_resolutions.begin()); std::copy(floc, floc + DimS, this->fourier_locations.begin()); // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. for (int i = 0; i < DimS-1; ++i) { for (int i = 0; i < 1; ++i) { std::swap(this->fourier_resolutions[i], this->fourier_resolutions[i + 1]); std::swap(this->fourier_locations[i], this->fourier_locations[i + 1]); } for (auto & n : this->subdomain_resolutions) { if (n == 0) { throw std::runtime_error("PFFT planning returned zero resolution. " "You may need to run on fewer processes."); } } for (auto & n : this->fourier_resolutions) { if (n == 0) { throw std::runtime_error("PFFT planning returned zero Fourier " "resolution. You may need to run on fewer " "processes."); } } for (auto && pixel : std::conditional_t, // TODO(pastewka): This should be the correct order // of dimension for a 2d process mesh, but tests // don't pass. CcoordOps::Pixels CcoordOps::Pixels>( this->fourier_resolutions, this->fourier_locations)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void PFFTEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } // Initialize parent after local resolutions have been determined and // work space has been initialized Parent::initialise(plan_flags); this->real_workspace = pfft_alloc_real(2 * this->workspace_size); // We need to check whether the workspace provided by our field is large // enough. PFFT may request a workspace size larger than the nominal size // of the complex buffer. if (static_cast(this->work.size() * this->nb_components) < this->workspace_size) { this->work.set_pad_size(this->workspace_size - this->nb_components * this->work.size()); } unsigned int flags; switch (plan_flags) { case FFT_PlanFlags::estimate: { flags = PFFT_ESTIMATE; break; } case FFT_PlanFlags::measure: { flags = PFFT_MEASURE; break; } case FFT_PlanFlags::patient: { flags = PFFT_PATIENT; break; } default: throw std::runtime_error("unknown planner flag type"); break; } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); Real * in{this->real_workspace}; pfft_complex * out{reinterpret_cast(this->work.data())}; this->plan_fft = pfft_plan_many_dft_r2c( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, in, out, this->mpi_comm, PFFT_FORWARD, PFFT_TRANSPOSED_OUT | flags); if (this->plan_fft == nullptr) { throw std::runtime_error("r2c plan failed"); } pfft_complex * i_in{reinterpret_cast(this->work.data())}; Real * i_out{this->real_workspace}; this->plan_ifft = pfft_plan_many_dft_c2r( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, i_in, i_out, this->mpi_comm, PFFT_BACKWARD, PFFT_TRANSPOSED_IN | flags); if (this->plan_ifft == nullptr) { throw std::runtime_error("c2r plan failed"); } this->initialised = true; } /* ---------------------------------------------------------------------- */ - template PFFTEngine::~PFFTEngine() noexcept { + template + PFFTEngine::~PFFTEngine() noexcept { if (this->real_workspace != nullptr) pfft_free(this->real_workspace); if (this->plan_fft != nullptr) pfft_destroy_plan(this->plan_fft); if (this->plan_ifft != nullptr) pfft_destroy_plan(this->plan_ifft); if (this->mpi_comm != this->comm.get_mpi_comm()) { MPI_Comm_free(&this->mpi_comm); } // TODO(Till): We cannot run fftw_mpi_cleanup since also calls fftw_cleanup // and any running FFTWEngine will fail afterwards. // this->nb_engines--; // if (!this->nb_engines) pfft_cleanup(); } /* ---------------------------------------------------------------------- */ template typename PFFTEngine::Workspace_t & PFFTEngine::fft(Field_t & field) { if (!this->plan_fft) { throw std::runtime_error("fft plan not allocated"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Copy field data to workspace buffer. This is necessary because workspace // buffer is larger than field buffer. std::copy(field.data(), field.data() + this->nb_components * field.size(), this->real_workspace); pfft_execute_dft_r2c(this->plan_fft, this->real_workspace, reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ - template void PFFTEngine::ifft(Field_t & field) const { + template + void PFFTEngine::ifft(Field_t & field) const { if (!this->plan_ifft) { throw std::runtime_error("ifft plan not allocated"); } if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } pfft_execute_dft_c2r(this->plan_ifft, reinterpret_cast(this->work.data()), this->real_workspace); std::copy(this->real_workspace, this->real_workspace + this->nb_components * field.size(), field.data()); } template class PFFTEngine; template class PFFTEngine; } // namespace muSpectre diff --git a/src/fft/pfft_engine.hh b/src/fft/pfft_engine.hh index d9070d3..d893469 100644 --- a/src/fft/pfft_engine.hh +++ b/src/fft/pfft_engine.hh @@ -1,106 +1,105 @@ /** * @file pfft_engine.hh * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief FFT engine using MPI-parallel PFFT * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_PFFT_ENGINE_HH_ #define SRC_FFT_PFFT_ENGINE_HH_ #include "common/communicator.hh" #include "fft/fft_engine_base.hh" #include namespace muSpectre { /** * implements the `muSpectre::FFTEngineBase` interface using the * FFTW library */ - template class PFFTEngine : public FFTEngineBase { + template + class PFFTEngine : public FFTEngineBase { public: using Parent = FFTEngineBase; //!< base class using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor PFFTEngine() = delete; //! Constructor with system resolutions PFFTEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor PFFTEngine(const PFFTEngine & other) = delete; //! Move constructor PFFTEngine(PFFTEngine && other) = default; //! Destructor virtual ~PFFTEngine() noexcept; //! Copy assignment operator PFFTEngine & operator=(const PFFTEngine & other) = delete; //! Move assignment operator PFFTEngine & operator=(PFFTEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: MPI_Comm mpi_comm; //! < MPI communicator static int nb_engines; //!< number of times this engine has been instatiated pfft_plan plan_fft{}; //!< holds the plan for forward fourier transform pfft_plan plan_ifft{}; //!< holds the plan for inverse fourier transform ptrdiff_t workspace_size{}; //!< size of workspace buffer returned by planner Real * real_workspace{}; //!< temporary real workspace that is correctly //!< padded bool initialised{false}; //!< to prevent double initialisation - - private: }; } // namespace muSpectre #endif // SRC_FFT_PFFT_ENGINE_HH_ diff --git a/src/fft/projection_base.hh b/src/fft/projection_base.hh index 68e8d25..70a0f3a 100644 --- a/src/fft/projection_base.hh +++ b/src/fft/projection_base.hh @@ -1,186 +1,188 @@ /** * @file projection_base.hh * * @author Till Junge * * @date 03 Dec 2017 * * @brief Base class for Projection operators * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_PROJECTION_BASE_HH_ #define SRC_FFT_PROJECTION_BASE_HH_ #include "common/common.hh" #include "common/field.hh" #include "common/field_collection.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 {}; + template + struct Projection_traits {}; /** * defines the interface which must be implemented by projection operators */ - template class ProjectionBase { + template + class ProjectionBase { public: //! Eigen type to replace fields using Vector_t = Eigen::Matrix; //! type of fft_engine used 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 = 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: }; } // namespace muSpectre #endif // SRC_FFT_PROJECTION_BASE_HH_ diff --git a/src/fft/projection_default.hh b/src/fft/projection_default.hh index e106cfb..2955928 100644 --- a/src/fft/projection_default.hh +++ b/src/fft/projection_default.hh @@ -1,117 +1,116 @@ + /** * @file projection_default.hh * * @author Till Junge * * @date 14 Jan 2018 * * @brief virtual base class for default projection implementation, where the * projection operator is stored as a full fourth-order tensor per * k-space point (as opposed to 'smart' faster implementations, such as * ProjectionFiniteStrainFast * * Copyright (C) 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_PROJECTION_DEFAULT_HH_ #define SRC_FFT_PROJECTION_DEFAULT_HH_ #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 = 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) final; Eigen::Map get_operator() final; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; constexpr static Dim_t NbComponents() { return ipow(DimM, 2); } protected: Proj_t & Gfield; //!< field holding the operator Proj_map Ghat; //!< iterable version of operator - - private: }; } // namespace muSpectre #endif // SRC_FFT_PROJECTION_DEFAULT_HH_ diff --git a/src/fft/projection_finite_strain_fast.hh b/src/fft/projection_finite_strain_fast.hh index cfd7aa4..f88d10b 100644 --- a/src/fft/projection_finite_strain_fast.hh +++ b/src/fft/projection_finite_strain_fast.hh @@ -1,123 +1,121 @@ /** * @file projection_finite_strain_fast.hh * * @author Till Junge * * @date 12 Dec 2017 * * @brief Faster alternative to ProjectionFinitestrain * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ #define SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ #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 = 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) void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate) final; //! apply the projection operator to a field void apply_projection(Field_t & field) final; Eigen::Map get_operator() final; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; constexpr static Dim_t NbComponents() { return ipow(DimM, 2); } protected: Proj_t & xiField; //!< field of normalised wave vectors Proj_map xis; //!< iterable normalised wave vectors - - private: }; } // namespace muSpectre #endif // SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ diff --git a/src/materials/CMakeLists.txt b/src/materials/CMakeLists.txt index 113360b..929f8d5 100644 --- a/src/materials/CMakeLists.txt +++ b/src/materials/CMakeLists.txt @@ -1,50 +1,49 @@ # ============================================================================= # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief configuration for material laws # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= set (materials_SRC ${CMAKE_CURRENT_SOURCE_DIR}/material_base.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic1.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic2.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic3.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic4.cc - ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic_generic.cc + ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic_generic1.cc + ${CMAKE_CURRENT_SOURCE_DIR}/material_linear_elastic_generic2.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_hyper_elasto_plastic1.cc ${CMAKE_CURRENT_SOURCE_DIR}/material_crystal_plasticity_finite.cc ) target_sources(muSpectre PRIVATE ${materials_SRC}) - - diff --git a/src/materials/material_base.hh b/src/materials/material_base.hh index 47e22c1..4cafe07 100644 --- a/src/materials/material_base.hh +++ b/src/materials/material_base.hh @@ -1,178 +1,177 @@ /** * @file material_base.hh * * @author Till Junge * * @date 25 Oct 2017 * * @brief Base class for materials (constitutive models) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_BASE_HH_ #define SRC_MATERIALS_MATERIAL_BASE_HH_ #include "common/common.hh" #include "common/field.hh" #include "common/field_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 { + 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 explicit MaterialBase(std::string name); //! Copy constructor MaterialBase(const MaterialBase & other) = delete; //! Move constructor MaterialBase(MaterialBase && other) = delete; //! Destructor virtual ~MaterialBase() = default; //! Copy assignment operator MaterialBase & operator=(const MaterialBase & other) = delete; //! Move assignment operator MaterialBase & operator=(MaterialBase && other) = delete; /** * take responsibility for a pixel identified by its cell coordinates * WARNING: this won't work for materials with additional info per pixel * (as, e.g. for eigenstrain), we need to pass more parameters. Materials * of this tye need to overload add_pixel */ virtual void add_pixel(const Ccoord & ccooord); //! allocate memory, etc, but also: wipe history variables! virtual void initialise() = 0; /** * for materials with state variables, these typically need to be * saved/updated an the end of each load increment, the virtual * base implementation does nothing, but materials with history * variables need to implement this */ virtual void save_history_variables() {} //! return the material's name const std::string & get_name() const; //! spatial dimension for static inheritance constexpr static Dim_t sdim() { return DimS; } //! material dimension for static inheritance constexpr static Dim_t mdim() { return DimM; } //! computes stress virtual void compute_stresses(const StrainField_t & F, StressField_t & P, Formulation form) = 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(); } //! type to return real-valued fields in using EigenMap = Eigen::Map>; /** * return an internal field identified by its name as an Eigen Array */ EigenMap get_real_field(std::string field_name); /** * list the names of all internal fields */ std::vector list_fields() const; //! gives access to internal fields inline MFieldCollection_t & get_collection() { return this->internal_fields; } protected: const std::string name; //!< material's name (for output and debugging) MFieldCollection_t internal_fields{}; //!< storage for internal variables - - private: }; } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_BASE_HH_ diff --git a/src/materials/material_evaluator.hh b/src/materials/material_evaluator.hh new file mode 100644 index 0000000..32866ce --- /dev/null +++ b/src/materials/material_evaluator.hh @@ -0,0 +1,267 @@ +/** + * @file material_evaluator.hh + * + * @author Till Junge + * + * @date 12 Dec 2018 + * + * @brief Helper to evaluate material laws + * + * Copyright © 2018 Till Junge + * + * µSpectre is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µSpectre is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µSpectre; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#ifndef SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ +#define SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ + +#include "common/common.hh" +#include "common/T4_map_proxy.hh" +#include "common/ccoord_operations.hh" +#include "materials/materials_toolbox.hh" +#include "common/field.hh" + +#include +#include +#include + +namespace muSpectre { + + /** + * forward declaration to avoid incluning material_base.hh + */ + template + class MaterialBase; + + template + class MaterialEvaluator { + public: + using T2_t = Eigen::Matrix; + using T4_t = T4Mat; + + using T2_map = Eigen::Map; + using T4_map = T4MatMap; + + using T2_const_map = Eigen::Map; + using T4_const_map = T4MatMap; + + using FieldColl_t = GlobalFieldCollection; + using T2Field_t = TensorField; + using T4Field_t = TensorField; + + //! Default constructor + MaterialEvaluator() = delete; + + /** + * constructor with a shared pointer to a Material + */ + explicit MaterialEvaluator( + std::shared_ptr> material) + : material{material}, + collection{std::make_unique()}, + strain{make_field("gradient", *this->collection)}, + stress{make_field("stress", *this->collection)}, + tangent{make_field("tangent", *this->collection)} { + this->collection->initialise(CcoordOps::get_cube(1), {0}); + } + + //! Copy constructor + MaterialEvaluator(const MaterialEvaluator & other) = delete; + + //! Move constructor + MaterialEvaluator(MaterialEvaluator && other) = default; + + //! Destructor + virtual ~MaterialEvaluator() = default; + + //! Copy assignment operator + MaterialEvaluator & operator=(const MaterialEvaluator & other) = delete; + + //! Move assignment operator + MaterialEvaluator & operator=(MaterialEvaluator && other) = default; + + /** + * for materials with state variables. See `muSpectre::MaterialBase` for + * details + */ + void save_history_variables() { this->material->save_history_variables(); } + + /** + * Evaluates the underlying materials constitutive law and returns the + * stress P or σ as a function of the placement gradient F or small strain + * tensor ε depending on the formulation + * (`muSpectre::Formulation::small_strain` for σ(ε), + * `muSpectre::Formulation::finite_strain` for P(F)) + */ + inline T2_const_map evaluate_stress(const Eigen::Ref & grad, + const Formulation & form); + + /** + * Evaluates the underlying materials constitutive law and returns the the + * stress P or σ and the tangent moduli K as a function of the placement + * gradient F or small strain tensor ε depending on the formulation + * (`muSpectre::Formulation::small_strain` for σ(ε), + * `muSpectre::Formulation::finite_strain` for P(F)) + */ + inline std::tuple + evaluate_stress_tangent(const Eigen::Ref & grad, + const Formulation & form); + + /** + * estimate the tangent using finite difference + */ + inline T4_t + estimate_tangent(const Eigen::Ref & grad, + const Formulation & form, const Real step, + const FiniteDiff diff_type = FiniteDiff::centred); + + protected: + /** + * throws a runtime error if the material's per-pixel data has not been set. + */ + void check_init() const; + + std::shared_ptr> material; + std::unique_ptr collection; + T2Field_t & strain; + T2Field_t & stress; + T4Field_t & tangent; + }; + + /* ---------------------------------------------------------------------- */ + template + auto MaterialEvaluator::evaluate_stress( + const Eigen::Ref & grad, const Formulation & form) + -> T2_const_map { + this->check_init(); + this->strain.get_map()[0] = grad; + this->material->compute_stresses(this->strain, this->stress, form); + return T2_const_map(this->stress.get_map()[0].data()); + } + + /* ---------------------------------------------------------------------- */ + template + auto MaterialEvaluator::evaluate_stress_tangent( + const Eigen::Ref & grad, const Formulation & form) + -> std::tuple { + this->check_init(); + this->strain.get_map()[0] = grad; + this->material->compute_stresses_tangent(this->strain, this->stress, + this->tangent, form); + return std::make_tuple(T2_const_map(this->stress.get_map()[0].data()), + T4_const_map(this->tangent.get_map()[0].data())); + } + + template + void MaterialEvaluator::check_init() const { + const auto & size{this->material->size()}; + if (size < 1) { + throw std::runtime_error( + "Not initialised! You have to call `add_pixel(...)` on your material " + "exactly one time before you can evaluate it."); + } else if (size > 1) { + std::stringstream error{}; + error << "The material to be evaluated should have exactly one pixel " + "added. You've added " + << size << " pixels."; + throw std::runtime_error(error.str()); + } + } + + /* ---------------------------------------------------------------------- */ + template + auto MaterialEvaluator::estimate_tangent( + const Eigen::Ref & grad, const Formulation & form, + const Real delta, const FiniteDiff diff_type) -> T4_t { + using T2_vec = Eigen::Map>; + + T4_t tangent{T4_t::Zero()}; + + const T2_t stress{this->evaluate_stress(grad, form)}; + + auto fun{[&form, this](const auto & grad_) { + return this->evaluate_stress(grad_, form); + }}; + + auto symmetrise{ + [](auto & eps) { eps = .5 * (eps + eps.transpose().eval()); }}; + + static_assert(Int(decltype(tangent.col(0))::SizeAtCompileTime) == + Int(T2_t::SizeAtCompileTime), + "wrong column size"); + + for (Dim_t i{}; i < DimM * DimM; ++i) { + T2_t strain2{grad}; + T2_vec strain2_vec{strain2.data()}; + switch (diff_type) { + case FiniteDiff::forward: { + strain2_vec(i) += delta; + if (form == Formulation::small_strain) { + symmetrise(strain2); + } + + T2_t del_f_del{(fun(strain2) - stress) / delta}; + + tangent.col(i) = T2_vec(del_f_del.data()); + break; + } + case FiniteDiff::backward: { + strain2_vec(i) -= delta; + if (form == Formulation::small_strain) { + symmetrise(strain2); + } + T2_t del_f_del{(stress - fun(strain2)) / delta}; + + tangent.col(i) = T2_vec(del_f_del.data()); + break; + } + case FiniteDiff::centred: { + T2_t strain1{grad}; + T2_vec strain1_vec{strain1.data()}; + strain1_vec(i) += delta; + strain2_vec(i) -= delta; + if (form == Formulation::small_strain) { + symmetrise(strain1); + symmetrise(strain2); + } + T2_t del_f_del{(fun(strain1).eval() - fun(strain2).eval()) / + (2 * delta)}; + + tangent.col(i) = T2_vec(del_f_del.data()); + break; + } + default: { + throw std::runtime_error("Unknown FiniteDiff value"); + break; + } + } + static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == + Int(T2_t::SizeAtCompileTime), + "wrong column size"); + } + return tangent; + } + +} // namespace muSpectre + +#endif // SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ diff --git a/src/materials/material_hyper_elasto_plastic1.hh b/src/materials/material_hyper_elasto_plastic1.hh index 93a12e2..bd3067f 100644 --- a/src/materials/material_hyper_elasto_plastic1.hh +++ b/src/materials/material_hyper_elasto_plastic1.hh @@ -1,249 +1,248 @@ /** * @file material_hyper_elasto_plastic1.hh * * @author Till Junge * * @date 20 Feb 2018 * * @brief Material for logarithmic hyperelasto-plasticity, as defined in de * Geus 2017 (https://doi.org/10.1016/j.cma.2016.12.032) and further * explained in Geers 2003 (https://doi.org/10.1016/j.cma.2003.07.014) * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ #define SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ #include "materials/material_muSpectre_base.hh" #include "materials/materials_toolbox.hh" #include "common/eigen_tools.hh" #include "common/statefield.hh" #include namespace muSpectre { - template class MaterialHyperElastoPlastic1; + 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>; /** * format in which to receive internals (previous gradient Fᵗ, * previous elastic lef Cauchy-Green deformation tensor bₑᵗ, and * the plastic flow measure εₚ */ using InternalVariables = std::tuple; }; /** * material implementation for hyper-elastoplastic constitutive law. Note for * developpers: this law is tested against a reference python implementation * in `py_comparison_test_material_hyper_elasto_plastic1.py` */ template class MaterialHyperElastoPlastic1 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre, DimS, DimM>; using T2_t = Eigen::Matrix; using T4_t = T4Mat; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! shortcut to traits using traits = MaterialMuSpectre_traits; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! type in which the previous strain state is referenced using StrainStRef_t = typename traits::LStrainMap_t::reference; //! type in which the previous plastic flow is referenced using FlowStRef_t = typename traits::LScalarMap_t::reference; //! Local FieldCollection type for field storage using LColl_t = LocalFieldCollection; //! Default constructor MaterialHyperElastoPlastic1() = delete; //! Constructor with name and material properties MaterialHyperElastoPlastic1(std::string name, Real young, Real poisson, Real tau_y0, Real H); //! Copy constructor MaterialHyperElastoPlastic1(const MaterialHyperElastoPlastic1 & other) = delete; //! Move constructor MaterialHyperElastoPlastic1(MaterialHyperElastoPlastic1 && other) = delete; //! Destructor virtual ~MaterialHyperElastoPlastic1() = default; //! Copy assignment operator MaterialHyperElastoPlastic1 & operator=(const MaterialHyperElastoPlastic1 & other) = delete; //! Move assignment operator MaterialHyperElastoPlastic1 & operator=(MaterialHyperElastoPlastic1 && other) = delete; /** * evaluates Kirchhoff stress given the current placement gradient * Fₜ, the previous Gradient Fₜ₋₁ and the cumulated plastic flow * εₚ */ T2_t evaluate_stress(const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t plast_flow); /** * evaluates Kirchhoff stress and stiffness given the current placement * gradient Fₜ, the previous Gradient Fₜ₋₁ and the cumulated plastic flow εₚ */ std::tuple evaluate_stress_tangent(const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t plast_flow); /** * The statefields need to be cycled at the end of each load increment */ void save_history_variables() override; /** * set the previous gradients to identity */ void initialise() final; /** * return the internals tuple */ typename traits::InternalVariables & get_internals() { return this->internal_variables; } //! getter for internal variable field εₚ StateField> & get_plast_flow_field() { return this->plast_flow_field; } //! getter for previous gradient field Fᵗ StateField> & get_F_prev_field() { return this->F_prev_field; } //! getterfor elastic left Cauchy-Green deformation tensor bₑᵗ StateField> & get_be_prev_field() { return this->be_prev_field; } /** * needed to accomodate the static-sized member variable C, see * http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html */ EIGEN_MAKE_ALIGNED_OPERATOR_NEW; protected: /** * worker function computing stresses and internal variables */ using Worker_t = std::tuple>; Worker_t stress_n_internals_worker(const T2_t & F, StrainStRef_t & F_prev, StrainStRef_t & be_prev, FlowStRef_t & plast_flow); //! storage for cumulated plastic flow εₚ StateField> & plast_flow_field; //! 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: }; } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ diff --git a/src/materials/material_linear_elastic1.hh b/src/materials/material_linear_elastic1.hh index 000123e..4a06a20 100644 --- a/src/materials/material_linear_elastic1.hh +++ b/src/materials/material_linear_elastic1.hh @@ -1,193 +1,188 @@ /** * @file material_linear_elastic1.hh * * @author Till Junge * * @date 13 Nov 2017 * * @brief Implementation for linear elastic reference material like in de Geus * 2017. This follows the simplest and likely not most efficient * implementation (with exception of the Python law) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ #include "common/common.hh" #include "materials/stress_transformations_PK2.hh" #include "materials/material_muSpectre_base.hh" #include "materials/materials_toolbox.hh" namespace muSpectre { - template class MaterialLinearElastic1; + template + class MaterialLinearElastic1; /** * traits for objective linear elasticity */ template struct MaterialMuSpectre_traits> { using Parent = MaterialMuSpectre_traits; //!< base for elasticity //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = MatrixFieldMap; //! 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! elasticity without internal variables using InternalVariables = std::tuple<>; }; //! DimS spatial dimension (dimension of problem //! DimM material_dimension (dimension of constitutive law) /** * implements objective linear elasticity */ template class MaterialLinearElastic1 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! this law does not have any internal variables using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic1() = delete; //! Copy constructor MaterialLinearElastic1(const MaterialLinearElastic1 & other) = delete; //! Construct by name, Young's modulus and Poisson's ratio MaterialLinearElastic1(std::string name, Real young, Real poisson); //! Move constructor MaterialLinearElastic1(MaterialLinearElastic1 && other) = delete; //! Destructor virtual ~MaterialLinearElastic1() = default; //! Copy assignment operator MaterialLinearElastic1 & operator=(const MaterialLinearElastic1 & other) = delete; //! Move assignment operator MaterialLinearElastic1 & operator=(MaterialLinearElastic1 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ - template inline decltype(auto) evaluate_stress(s_t && E); + template + inline decltype(auto) evaluate_stress(s_t && E); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(s_t && E); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } protected: const Real young; //!< Young's modulus const Real poisson; //!< Poisson's ratio const Real lambda; //!< first Lamé constant const Real mu; //!< second Lamé constant (shear modulus) const Stiffness_t C; //!< stiffness tensor //! empty tuple InternalVariables internal_variables{}; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic1::evaluate_stress(s_t && E) -> decltype(auto) { return Hooke::evaluate_stress(this->lambda, this->mu, std::move(E)); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic1::evaluate_stress_tangent(s_t && E) -> decltype(auto) { using Tangent_t = typename traits::TangentMap_t::reference; - // using mat = Eigen::Matrix; - // mat ecopy{E}; - // std::cout << "E" << std::endl << ecopy << std::endl; - // std::cout << "P1" << std::endl << mat{ - // std::get<0>(Hooke::evaluate_stress(this->lambda, this->mu, - // Tangent_t(const_cast(this->C.data())), - // std::move(E)))} << std::endl; return Hooke::evaluate_stress( this->lambda, this->mu, Tangent_t(const_cast(this->C.data())), std::move(E)); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ diff --git a/src/materials/material_linear_elastic2.hh b/src/materials/material_linear_elastic2.hh index 4b8aa2d..b9a4e6f 100644 --- a/src/materials/material_linear_elastic2.hh +++ b/src/materials/material_linear_elastic2.hh @@ -1,202 +1,201 @@ /** * @file material_linear_elastic2.hh * * @author Till Junge * * @date 03 Feb 2018 * * @brief linear elastic material with imposed eigenstrain and its * type traits. Uses the MaterialMuSpectre facilities to keep it * simple * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ #include "materials/material_linear_elastic1.hh" #include "common/field.hh" #include namespace muSpectre { - template class MaterialLinearElastic2; + template + class MaterialLinearElastic2; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = MatrixFieldMap; //! 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals using LFieldColl_t = LocalFieldCollection; //! local strain type using LStrainMap_t = MatrixFieldMap; //! elasticity with eigenstrain using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic2 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre; //! type for stiffness tensor construction using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! reference to any type that casts to a matrix - using StrainTensor = Eigen::Ref>; + using StrainTensor = Eigen::Ref>; //! Default constructor MaterialLinearElastic2() = delete; //! Construct by name, Young's modulus and Poisson's ratio MaterialLinearElastic2(std::string name, Real young, Real poisson); //! Copy constructor MaterialLinearElastic2(const MaterialLinearElastic2 & other) = delete; //! Move constructor MaterialLinearElastic2(MaterialLinearElastic2 && other) = delete; //! Destructor virtual ~MaterialLinearElastic2() = default; //! Copy assignment operator MaterialLinearElastic2 & operator=(const MaterialLinearElastic2 & other) = delete; //! Move assignment operator MaterialLinearElastic2 & operator=(MaterialLinearElastic2 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(s_t && E, eigen_s_t && E_eig); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, eigen_s_t && E_eig); /** * return the internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel, const StrainTensor & E_eig); protected: //! linear material without eigenstrain used to compute response MaterialLinearElastic1 material; //! storage for eigenstrain using Field_t = TensorField, Real, secondOrder, DimM>; Field_t & eigen_field; //!< field holding the eigen strain per pixel //! tuple for iterable eigen_field InternalVariables internal_variables; - - private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic2::evaluate_stress(s_t && E, eigen_s_t && E_eig) -> decltype(auto) { return this->material.evaluate_stress(E - E_eig); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic2::evaluate_stress_tangent( s_t && E, eigen_s_t && E_eig) -> decltype(auto) { // using mat = Eigen::Matrix; // mat ecopy{E}; // mat eig_copy{E_eig}; // mat ediff{ecopy-eig_copy}; // std::cout << "eidff - (E-E_eig)" << std::endl << ediff-(E-E_eig) << // std::endl; std::cout << "P1 " << std::endl << // mat{std::get<0>(this->material.evaluate_stress_tangent(E-E_eig))} << // "" << std::endl; std::cout << "P2" << std::endl << // mat{std::get<0>(this->material.evaluate_stress_tangent(std::move(ediff)))} // << std::endl; return this->material.evaluate_stress_tangent(E - E_eig); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ diff --git a/src/materials/material_linear_elastic3.hh b/src/materials/material_linear_elastic3.hh index 839eb80..f68e556 100644 --- a/src/materials/material_linear_elastic3.hh +++ b/src/materials/material_linear_elastic3.hh @@ -1,196 +1,197 @@ /** * @file material_linear_elastic3.hh * * @author Richard Leute * * @date 20 Feb 2018 * * @brief linear elastic material with distribution of stiffness properties. * Uses the MaterialMuSpectre facilities to keep it simple. * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ #include "materials/material_linear_elastic1.hh" #include "common/field.hh" #include "common/tensor_algebra.hh" #include namespace muSpectre { - template class MaterialLinearElastic3; + template + class MaterialLinearElastic3; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = MatrixFieldMap; //! 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals using LFieldColl_t = LocalFieldCollection; //! local stiffness tensor type using LStiffnessMap_t = T4MatrixFieldMap; //! elasticity without internal variables using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic3 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic3() = delete; //! Construct by name explicit MaterialLinearElastic3(std::string name); //! Copy constructor MaterialLinearElastic3(const MaterialLinearElastic3 & other) = delete; //! Move constructor MaterialLinearElastic3(MaterialLinearElastic3 && other) = delete; //! Destructor virtual ~MaterialLinearElastic3() = default; //! Copy assignment operator MaterialLinearElastic3 & operator=(const MaterialLinearElastic3 & other) = delete; //! Move assignment operator MaterialLinearElastic3 & operator=(MaterialLinearElastic3 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) * and the local stiffness tensor. */ template inline decltype(auto) evaluate_stress(s_t && E, stiffness_t && C); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) and the local stiffness tensor. */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, stiffness_t && C); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into loacal stiffness tensor */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into local stiffness tensor */ void add_pixel(const Ccoord_t & pixel, const Real & Young, const Real & PoissonRatio); protected: //! storage for stiffness tensor using Field_t = TensorField, Real, fourthOrder, DimM>; Field_t & C_field; //!< field of stiffness tensors //! tuple for iterable eigen_field InternalVariables internal_variables; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic3::evaluate_stress(s_t && E, stiffness_t && C) -> decltype(auto) { return Matrices::tensmult(C, E); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic3::evaluate_stress_tangent( s_t && E, stiffness_t && C) -> decltype(auto) { return std::make_tuple(evaluate_stress(E, C), C); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ diff --git a/src/materials/material_linear_elastic4.cc b/src/materials/material_linear_elastic4.cc index 73be1db..4637363 100644 --- a/src/materials/material_linear_elastic4.cc +++ b/src/materials/material_linear_elastic4.cc @@ -1,79 +1,79 @@ /** * @file material_linear_elastic4.cc * * @author Richard Leute MaterialLinearElastic4::MaterialLinearElastic4(std::string name) : Parent{name}, lambda_field{make_field( "local first Lame constant", this->internal_fields)}, mu_field{ make_field("local second Lame constant(shear modulus)", this->internal_fields)}, internal_variables{lambda_field.get_const_map(), mu_field.get_const_map()} {} /* ---------------------------------------------------------------------- */ template - void MaterialLinearElastic4::add_pixel( - const Ccoord_t & /*pixel*/) { - throw std::runtime_error( - "this material needs pixels with Youngs modulus and Poisson ratio."); + void MaterialLinearElastic4:: + add_pixel(const Ccoord_t & /*pixel*/) { + throw std::runtime_error + ("This material needs pixels with Youngs modulus and Poisson ratio."); } /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic4::add_pixel(const Ccoord_t & pixel, const Real & Young_modulus, const Real & Poisson_ratio) { this->internal_fields.add_pixel(pixel); // store the first(lambda) and second(mu) Lame constant in the field Real lambda = Hooke::compute_lambda(Young_modulus, Poisson_ratio); Real mu = Hooke::compute_mu(Young_modulus, Poisson_ratio); this->lambda_field.push_back(lambda); this->mu_field.push_back(mu); } template class MaterialLinearElastic4; template class MaterialLinearElastic4; template class MaterialLinearElastic4; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic4.hh b/src/materials/material_linear_elastic4.hh index 4ed2479..ba27004 100644 --- a/src/materials/material_linear_elastic4.hh +++ b/src/materials/material_linear_elastic4.hh @@ -1,206 +1,208 @@ /** * @file material_linear_elastic4.hh * * @author Richard Leute * * @date 15 March 2018 * * @brief linear elastic material with distribution of stiffness properties. * In difference to material_linear_elastic3 two Lame constants are * stored per pixel instead of the whole elastic matrix C. * Uses the MaterialMuSpectre facilities to keep it simple. * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ #include "materials/material_linear_elastic1.hh" #include "common/field.hh" #include "common/tensor_algebra.hh" #include namespace muSpectre { - template class MaterialLinearElastic4; + template + class MaterialLinearElastic4; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = MatrixFieldMap; //! 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals using LFieldColl_t = LocalFieldCollection; //! local Lame constant type using LLameConstantMap_t = ScalarFieldMap; //! elasticity without internal variables using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic4 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic4() = delete; //! Construct by name explicit MaterialLinearElastic4(std::string name); //! Copy constructor MaterialLinearElastic4(const MaterialLinearElastic4 & other) = delete; //! Move constructor MaterialLinearElastic4(MaterialLinearElastic4 && other) = delete; //! Destructor virtual ~MaterialLinearElastic4() = default; //! Copy assignment operator MaterialLinearElastic4 & operator=(const MaterialLinearElastic4 & other) = delete; //! Move assignment operator MaterialLinearElastic4 & operator=(MaterialLinearElastic4 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor), the first * Lame constant (lambda) and the second Lame constant (shear modulus/mu). */ template inline decltype(auto) evaluate_stress(s_t && E, const Real & lambda, const Real & mu); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor), the first Lame constant (lambda) and * the second Lame constant (shear modulus/mu). */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, const Real & lambda, const Real & mu); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into loacal stiffness tensor */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into local stiffness tensor */ - void add_pixel(const Ccoord_t & pixel, const Real & Poisson_ratio, - const Real & Youngs_modulus); + void add_pixel(const Ccoord_t & pixel, + const Real & Youngs_modulus, const Real & Poisson_ratio); protected: //! storage for first Lame constant 'lambda' //! and second Lame constant(shear modulus) 'mu' using Field_t = MatrixField, Real, oneD, oneD>; Field_t & lambda_field; Field_t & mu_field; //! tuple for iterable eigen_field InternalVariables internal_variables; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic4::evaluate_stress(s_t && E, const Real & lambda, const Real & mu) -> decltype(auto) { auto C = Hooke::compute_C_T4(lambda, mu); return Matrices::tensmult(C, E); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic4::evaluate_stress_tangent( s_t && E, const Real & lambda, const Real & mu) -> decltype(auto) { - auto C = Hooke::compute_C_T4(lambda, mu); - return std::make_tuple(Matrices::tensmult(C, E), C); + T4Mat C = Hooke::compute_C_T4(lambda, mu); + return std::make_tuple( + this->evaluate_stress(std::forward(E), lambda, mu), C); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ diff --git a/src/materials/material_linear_elastic_generic.cc b/src/materials/material_linear_elastic_generic1.cc similarity index 86% rename from src/materials/material_linear_elastic_generic.cc rename to src/materials/material_linear_elastic_generic1.cc index 54390f4..a82fdce 100644 --- a/src/materials/material_linear_elastic_generic.cc +++ b/src/materials/material_linear_elastic_generic1.cc @@ -1,71 +1,71 @@ /** - * @file material_linear_elastic_generic.cc + * @file material_linear_elastic_generic1.cc * * @author Till Junge * * @date 21 Sep 2018 * * @brief implementation for MaterialLinearElasticGeneric * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "materials/material_linear_elastic_generic.hh" +#include "materials/material_linear_elastic_generic1.hh" #include "common/voigt_conversion.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ template - MaterialLinearElasticGeneric::MaterialLinearElasticGeneric( + MaterialLinearElasticGeneric1::MaterialLinearElasticGeneric1( const std::string & name, const CInput_t & C_voigt) : Parent{name} { using VC_t = VoigtConversion; constexpr Dim_t VSize{vsize(DimM)}; if (not(C_voigt.rows() == VSize) or not(C_voigt.cols() == VSize)) { std::stringstream err_str{}; err_str << "The stiffness tensor should be input as a " << VSize << " × " << VSize << " Matrix in Voigt notation. You supplied" << " a " << C_voigt.rows() << " × " << C_voigt.cols() << " matrix"; } for (int i{0}; i < DimM; ++i) { for (int j{0}; j < DimM; ++j) { for (int k{0}; k < DimM; ++k) { for (int l{0}; l < DimM; ++l) { get(this->C, i, j, k, l) = C_voigt(VC_t::sym_mat(i, j), VC_t::sym_mat(k, l)); } } } } } - template class MaterialLinearElasticGeneric; - template class MaterialLinearElasticGeneric; - template class MaterialLinearElasticGeneric; + template class MaterialLinearElasticGeneric1; + template class MaterialLinearElasticGeneric1; + template class MaterialLinearElasticGeneric1; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic_generic.hh b/src/materials/material_linear_elastic_generic1.hh similarity index 73% rename from src/materials/material_linear_elastic_generic.hh rename to src/materials/material_linear_elastic_generic1.hh index eccb2bb..37efcfb 100644 --- a/src/materials/material_linear_elastic_generic.hh +++ b/src/materials/material_linear_elastic_generic1.hh @@ -1,187 +1,186 @@ /** - * @file material_linear_elastic_generic.hh + * @file material_linear_elastic_generic1.hh * * @author Till Junge * * @date 21 Sep 2018 * * @brief Implementation fo a generic linear elastic material that * stores the full elastic stiffness tensor. Convenient but not the * most efficient * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC_HH_ -#define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC_HH_ +#ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ +#define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ #include "common/common.hh" #include "materials/stress_transformations_PK2.hh" #include "common/T4_map_proxy.hh" #include "materials/material_muSpectre_base.hh" #include "common/tensor_algebra.hh" namespace muSpectre { /** * forward declaration */ - template class MaterialLinearElasticGeneric; + template + class MaterialLinearElasticGeneric1; /** * traits for use by MaterialMuSpectre for crtp */ template - struct MaterialMuSpectre_traits> { + 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! elasticity without internal variables using InternalVariables = std::tuple<>; }; /** * Linear elastic law defined by a full stiffness tensor. Very * generic, but not most efficient */ template - class MaterialLinearElasticGeneric - : public MaterialMuSpectre, DimS, - DimM> { + class MaterialLinearElasticGeneric1 + : public MaterialMuSpectre, + DimS, DimM> { public: //! parent type - using Parent = - MaterialMuSpectre, DimS, DimM>; + using Parent = MaterialMuSpectre, + DimS, DimM>; //! generic input tolerant to python input using CInput_t = Eigen::Ref, 0, Eigen::Stride>; //! Default constructor - MaterialLinearElasticGeneric() = delete; + MaterialLinearElasticGeneric1() = delete; /** * Constructor by name and stiffness tensor. * * @param name unique material name * @param C_voigt elastic tensor in Voigt notation */ - MaterialLinearElasticGeneric(const std::string & name, - const CInput_t & C_voigt); + MaterialLinearElasticGeneric1(const std::string & name, + const CInput_t & C_voigt); //! Copy constructor - MaterialLinearElasticGeneric(const MaterialLinearElasticGeneric & other) = + MaterialLinearElasticGeneric1(const MaterialLinearElasticGeneric1 & other) = delete; //! Move constructor - MaterialLinearElasticGeneric(MaterialLinearElasticGeneric && other) = + MaterialLinearElasticGeneric1(MaterialLinearElasticGeneric1 && other) = delete; //! Destructor - virtual ~MaterialLinearElasticGeneric() = default; + virtual ~MaterialLinearElasticGeneric1() = default; //! Copy assignment operator - MaterialLinearElasticGeneric & - operator=(const MaterialLinearElasticGeneric & other) = delete; + MaterialLinearElasticGeneric1 & + operator=(const MaterialLinearElasticGeneric1 & other) = delete; //! Move assignment operator - MaterialLinearElasticGeneric & - operator=(MaterialLinearElasticGeneric && other) = delete; + MaterialLinearElasticGeneric1 & + operator=(MaterialLinearElasticGeneric1 && other) = delete; //! see //! http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html EIGEN_MAKE_ALIGNED_OPERATOR_NEW; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(const Eigen::MatrixBase & E); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ - template - inline decltype(auto) evaluate_stress_tangent(s_t && E); + template + inline decltype(auto) + evaluate_stress_tangent(const Eigen::MatrixBase & E); /** * return the empty internals tuple */ std::tuple<> & get_internals() { return this->internal_variables; } /** - * return a reference to teh stiffness tensor + * return a reference to the stiffness tensor */ const T4Mat & get_C() const { return this->C; } protected: - T4Mat C{}; + T4Mat C{}; //! stiffness tensor //! empty tuple std::tuple<> internal_variables{}; - - private: }; /* ---------------------------------------------------------------------- */ template template - auto MaterialLinearElasticGeneric::evaluate_stress( + auto MaterialLinearElasticGeneric1::evaluate_stress( const Eigen::MatrixBase & E) -> decltype(auto) { static_assert(Derived::ColsAtCompileTime == DimM, "wrong input size"); static_assert(Derived::RowsAtCompileTime == DimM, "wrong input size"); return Matrices::tensmult(this->C, E); } /* ---------------------------------------------------------------------- */ template - template - auto - MaterialLinearElasticGeneric::evaluate_stress_tangent(s_t && E) - -> decltype(auto) { - using Stress_t = decltype(this->evaluate_stress(std::forward(E))); + template + auto MaterialLinearElasticGeneric1::evaluate_stress_tangent( + const Eigen::MatrixBase & E) -> decltype(auto) { + using Stress_t = decltype(this->evaluate_stress(E)); using Stiffness_t = Eigen::Map>; using Ret_t = std::tuple; - return Ret_t{this->evaluate_stress(std::forward(E)), + return Ret_t{this->evaluate_stress(E), Stiffness_t(this->C.data())}; } } // namespace muSpectre -#endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC_HH_ +#endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ diff --git a/src/materials/material_linear_elastic_generic2.cc b/src/materials/material_linear_elastic_generic2.cc new file mode 100644 index 0000000..fe22fb0 --- /dev/null +++ b/src/materials/material_linear_elastic_generic2.cc @@ -0,0 +1,68 @@ +/** + * @file material_linear_elastic_generic2.cc + * + * @author Till Junge + * + * @date 20 Dec 2018 + * + * @brief Implementation for generic linear elastic law with eigenstrains + * + * Copyright © 2018 Till Junge + * + * µSpectre is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µSpectre is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µSpectre; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#include "material_linear_elastic_generic2.hh" + +namespace muSpectre { + + /* ---------------------------------------------------------------------- */ + template + MaterialLinearElasticGeneric2::MaterialLinearElasticGeneric2( + const std::string & name, const CInput_t & C_voigt) + : Parent{name}, worker{name, C_voigt}, + eigen_field{make_field("Eigenstrain", this->internal_fields)}, + internal_variables(eigen_field.get_const_map()) {} + + /* ---------------------------------------------------------------------- */ + template + void MaterialLinearElasticGeneric2::add_pixel( + const Ccoord_t & /*pixel*/) { + throw std::runtime_error("this material needs pixels with and eigenstrain"); + } + + /* ---------------------------------------------------------------------- */ + template + void MaterialLinearElasticGeneric2::add_pixel( + const Ccoord_t & pixel, const StrainTensor & E_eig) { + this->internal_fields.add_pixel(pixel); + Eigen::Map> strain_array( + E_eig.data()); + this->eigen_field.push_back(strain_array); + } + + template class MaterialLinearElasticGeneric2; + template class MaterialLinearElasticGeneric2; + template class MaterialLinearElasticGeneric2; + +} // namespace muSpectre diff --git a/src/materials/material_linear_elastic2.hh b/src/materials/material_linear_elastic_generic2.hh similarity index 52% copy from src/materials/material_linear_elastic2.hh copy to src/materials/material_linear_elastic_generic2.hh index 4b8aa2d..6690d08 100644 --- a/src/materials/material_linear_elastic2.hh +++ b/src/materials/material_linear_elastic_generic2.hh @@ -1,202 +1,202 @@ /** - * @file material_linear_elastic2.hh + * @file material_linear_elastic_generic2.hh * - * @author Till Junge + * @author Till Junge * - * @date 03 Feb 2018 + * @date 20 Dec 2018 * - * @brief linear elastic material with imposed eigenstrain and its - * type traits. Uses the MaterialMuSpectre facilities to keep it - * simple + * @brief implementation of a generic linear elastic law with eigenstrains * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * * Boston, MA 02111-1307, USA. + * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ -#define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ +#ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ +#define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ -#include "materials/material_linear_elastic1.hh" -#include "common/field.hh" - -#include +#include "material_linear_elastic_generic1.hh" namespace muSpectre { - template class MaterialLinearElastic2; + /** + * forward declaration + */ + template + class MaterialLinearElasticGeneric2; /** - * traits for objective linear elasticity with eigenstrain + * traits for use by MaterialMuSpectre for crtp */ + template - struct MaterialMuSpectre_traits> { + 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::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals using LFieldColl_t = LocalFieldCollection; //! local strain type using LStrainMap_t = MatrixFieldMap; //! elasticity with eigenstrain using InternalVariables = std::tuple; }; /** - * implements objective linear elasticity with an eigenstrain per pixel + * Implementation proper of the class */ template - class MaterialLinearElastic2 - : public MaterialMuSpectre, DimS, - DimM> { - public: - //! base class - using Parent = MaterialMuSpectre; + class MaterialLinearElasticGeneric2 + : public MaterialMuSpectre, + DimS, DimM> { + //! parent type + using Parent = MaterialMuSpectre, + DimS, DimM>; + //! underlying worker class + using Law_t = MaterialLinearElasticGeneric1; + + //! generic input tolerant to python input + using CInput_t = typename Law_t::CInput_t; - //! type for stiffness tensor construction - using Stiffness_t = - Eigen::TensorFixedSize>; + //! reference to any type that casts to a matrix + using StrainTensor = Eigen::Ref>; //! traits of this material - using traits = MaterialMuSpectre_traits; + using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain - using InternalVariables = typename traits::InternalVariables; - - //! Hooke's law implementation - using Hooke = - typename MatTB::Hooke; + using InternalVariables_t = typename traits::InternalVariables; - //! reference to any type that casts to a matrix - using StrainTensor = Eigen::Ref>; + public: //! Default constructor - MaterialLinearElastic2() = delete; + MaterialLinearElasticGeneric2() = delete; - //! Construct by name, Young's modulus and Poisson's ratio - MaterialLinearElastic2(std::string name, Real young, Real poisson); + //! Construct by name and elastic stiffness tensor + MaterialLinearElasticGeneric2(const std::string & name, + const CInput_t & C_voigt); //! Copy constructor - MaterialLinearElastic2(const MaterialLinearElastic2 & other) = delete; + MaterialLinearElasticGeneric2(const MaterialLinearElasticGeneric2 & other) = + delete; //! Move constructor - MaterialLinearElastic2(MaterialLinearElastic2 && other) = delete; + MaterialLinearElasticGeneric2(MaterialLinearElasticGeneric2 && other) = + default; //! Destructor - virtual ~MaterialLinearElastic2() = default; + virtual ~MaterialLinearElasticGeneric2() = default; //! Copy assignment operator - MaterialLinearElastic2 & - operator=(const MaterialLinearElastic2 & other) = delete; + MaterialLinearElasticGeneric2 & + operator=(const MaterialLinearElasticGeneric2 & other) = delete; //! Move assignment operator - MaterialLinearElastic2 & - operator=(MaterialLinearElastic2 && other) = delete; + MaterialLinearElasticGeneric2 & + operator=(MaterialLinearElasticGeneric2 && other) = default; + + //! see + //! http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html + EIGEN_MAKE_ALIGNED_OPERATOR_NEW; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ - template - inline decltype(auto) evaluate_stress(s_t && E, eigen_s_t && E_eig); - + template + inline decltype(auto) + evaluate_stress(const Eigen::MatrixBase & E, + const Eigen::MatrixBase & E_eig); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ - template - inline decltype(auto) evaluate_stress_tangent(s_t && E, eigen_s_t && E_eig); + template + inline decltype(auto) + evaluate_stress_tangent(const Eigen::MatrixBase & E, + const Eigen::MatrixBase & E_eig); /** - * return the internals tuple + * returns tuple with only the eigenstrain field */ - InternalVariables & get_internals() { return this->internal_variables; } + InternalVariables_t & get_internals() { return this->internal_variables; } + + /** + * return a reference to the stiffness tensor + */ + const T4Mat & get_C() const { return this->worker.get_C(); } /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel, const StrainTensor & E_eig); protected: - //! linear material without eigenstrain used to compute response - MaterialLinearElastic1 material; + Law_t worker; //! underlying law to be evaluated //! storage for eigenstrain using Field_t = TensorField, Real, secondOrder, DimM>; Field_t & eigen_field; //!< field holding the eigen strain per pixel - //! tuple for iterable eigen_field - InternalVariables internal_variables; - - private: + InternalVariables_t internal_variables; }; /* ---------------------------------------------------------------------- */ template - template - auto MaterialLinearElastic2::evaluate_stress(s_t && E, - eigen_s_t && E_eig) - -> decltype(auto) { - return this->material.evaluate_stress(E - E_eig); + template + auto MaterialLinearElasticGeneric2::evaluate_stress( + const Eigen::MatrixBase & E, + const Eigen::MatrixBase & E_eig) -> decltype(auto) { + return this->worker.evaluate_stress(E - E_eig); } /* ---------------------------------------------------------------------- */ template - template - auto MaterialLinearElastic2::evaluate_stress_tangent( - s_t && E, eigen_s_t && E_eig) -> decltype(auto) { - // using mat = Eigen::Matrix; - // mat ecopy{E}; - // mat eig_copy{E_eig}; - // mat ediff{ecopy-eig_copy}; - // std::cout << "eidff - (E-E_eig)" << std::endl << ediff-(E-E_eig) << - // std::endl; std::cout << "P1 " << std::endl << - // mat{std::get<0>(this->material.evaluate_stress_tangent(E-E_eig))} << - // "" << std::endl; std::cout << "P2" << std::endl << - // mat{std::get<0>(this->material.evaluate_stress_tangent(std::move(ediff)))} - // << std::endl; - return this->material.evaluate_stress_tangent(E - E_eig); + template + auto MaterialLinearElasticGeneric2::evaluate_stress_tangent( + const Eigen::MatrixBase & E, + const Eigen::MatrixBase & E_eig) -> decltype(auto) { + return this->worker.evaluate_stress_tangent(E - E_eig); } } // namespace muSpectre -#endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ +#endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ diff --git a/src/materials/material_muSpectre_base.hh b/src/materials/material_muSpectre_base.hh index f50cc18..0cc3384 100644 --- a/src/materials/material_muSpectre_base.hh +++ b/src/materials/material_muSpectre_base.hh @@ -1,697 +1,721 @@ /** * @file material_muSpectre_base.hh * * @author Till Junge * * @date 25 Oct 2017 * * @brief Base class for materials written for µSpectre specifically. These * can take full advantage of the configuration-change utilities of * µSpectre. The user can inherit from them to define new constitutive * laws and is merely required to provide the methods for computing the * second Piola-Kirchhoff stress and Tangent. This class uses the * "curiously recurring template parameter" to avoid virtual calls. * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * * Boston, MA 02111-1307, USA. + * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ #define SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ #include "common/common.hh" #include "materials/material_base.hh" #include "materials/materials_toolbox.hh" +#include "materials/material_evaluator.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; + 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 + struct MaterialMuSpectre_traits {}; - template class MaterialMuSpectre; + 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 explicit MaterialMuSpectre(std::string name); //! Copy constructor MaterialMuSpectre(const MaterialMuSpectre & other) = delete; //! Move constructor MaterialMuSpectre(MaterialMuSpectre && other) = delete; //! Destructor virtual ~MaterialMuSpectre() = default; //! Factory template static Material & make(CellBase & cell, ConstructorArgs &&... args); + /** Factory + * takes all arguments after the name of the underlying + * Material's constructor. E.g., if the underlying material is a + * `muSpectre::MaterialLinearElastic1`, these would be Young's + * modulus and Poisson's ratio. + */ + template + static std::tuple, MaterialEvaluator> + make_evaluator(ConstructorArgs &&... args); //! Copy assignment operator MaterialMuSpectre & operator=(const MaterialMuSpectre & other) = delete; //! Move assignment operator MaterialMuSpectre & operator=(MaterialMuSpectre && other) = delete; //! allocate memory, etc void initialise() override; using Parent::compute_stresses; using Parent::compute_stresses_tangent; //! computes stress void compute_stresses(const StrainField_t & F, StressField_t & P, Formulation form) final; //! computes stress and tangent modulus void compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form) 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; + 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 + template + std::tuple, MaterialEvaluator> + MaterialMuSpectre::make_evaluator( + ConstructorArgs &&... args) { + auto mat = std::make_shared("name", args...); + using Ret_t = + std::tuple, MaterialEvaluator>; + return Ret_t(mat, MaterialEvaluator{mat}); + } + /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::initialise() { if (!this->is_initialised) { this->internal_fields.initialise(); this->is_initialised = true; } } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::compute_stresses( const StrainField_t & F, StressField_t & P, Formulation form) { 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(junge): Figure this out: I can't std::move(internals...), // because if there are no internals, compilation fails with "no // matching function for call to ‘move()’'. These are tuples of // lvalue references, so it shouldn't be too bad, but still // irksome. // 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(junge): Figure this out: I can't std::move(internals...), // because if there are no internals, compilation fails with "no // matching function for call to ‘move()’'. These are tuples of // lvalue references, so it shouldn't be too bad, but still // irksome. // 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. **/ explicit iterator(const iterable_proxy & it, bool begin = true) : it{it}, strain_map{it.strain_field}, stress_map(it.stress_tup), index{begin ? 0 : it.material.internal_fields.size()} {} //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++(); //! dereference inline value_type operator*(); //! inequality inline bool operator!=(const iterator & other) const; protected: const iterable_proxy & it; //!< ref to the proxy StrainMap_t strain_map; //!< map onto the global strain field //! map onto the global stress field and possibly tangent stiffness StressMapTup stress_map; size_t index; //!< index or pixel currently referred to - - 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< NeedTgT>::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)); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ diff --git a/src/materials/materials_toolbox.hh b/src/materials/materials_toolbox.hh index eaa0d84..383dcc6 100644 --- a/src/materials/materials_toolbox.hh +++ b/src/materials/materials_toolbox.hh @@ -1,572 +1,591 @@ /** * @file materials_toolbox.hh * * @author Till Junge * * @date 02 Nov 2017 * * @brief collection of common continuum mechanics tools * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ #define SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ #include "common/common.hh" #include "common/tensor_algebra.hh" #include "common/eigen_tools.hh" #include "common/T4_map_proxy.hh" #include #include #include #include #include #include #include namespace muSpectre { namespace MatTB { /** * thrown when generic materials-related runtime errors occur * (mostly continuum mechanics problems) */ class MaterialsToolboxError : public std::runtime_error { public: //! constructor explicit MaterialsToolboxError(const std::string & what) : std::runtime_error(what) {} //! constructor explicit MaterialsToolboxError(const char * what) : std::runtime_error(what) {} }; /* ---------------------------------------------------------------------- */ /** * Flag used to designate whether the material should compute both stress * and tangent moduli or only stress */ enum class NeedTangent { yes, //!< compute both stress and tangent moduli no //!< compute only stress }; /** * struct used to determine the exact type of a tuple of references obtained * when a bunch of iterators over fiel_maps are dereferenced and their * results are concatenated into a tuple */ - template struct ReferenceTuple { + template + struct ReferenceTuple { //! use this type using type = std::tuple; }; /** * specialisation for tuples */ // template <> - template struct ReferenceTuple> { + template + struct ReferenceTuple> { //! use this type using type = typename ReferenceTuple::type; }; /** * helper type for ReferenceTuple */ template using ReferenceTuple_t = typename ReferenceTuple::type; /* ---------------------------------------------------------------------- */ namespace internal { /** Structure for functions returning one strain measure as a * function of another **/ - template struct ConvertStrain { + template + struct ConvertStrain { static_assert((In == StrainMeasure::Gradient) || (In == StrainMeasure::Infinitesimal), "This situation makes me suspect that you are not using " "MatTb as intended. Disable this assert only if you are " "sure about what you are doing."); //! returns the converted strain template inline static decltype(auto) compute(Strain_t && input) { // transparent case, in which no conversion is required: // just a perfect forwarding static_assert((In == Out), "This particular strain conversion is not implemented"); return std::forward(input); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Green-Lagrange strain from the transformation gradient E = ¹/₂ (C - I) = ¹/₂ (Fᵀ·F - I) **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return .5 * (F.transpose() * F - Strain_t::PlainObject::Identity()); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Left Cauchy-Green strain from the transformation gradient B = F·Fᵀ = V² **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return F * F.transpose(); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Right Cauchy-Green strain from the transformation gradient C = Fᵀ·F = U² **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return F.transpose() * F; } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting logarithmic (Hencky) strain from the transformation gradient E₀ = ¹/₂ ln C = ¹/₂ ln (Fᵀ·F) **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { constexpr Dim_t dim{EigenCheck::tensor_dim::value}; return (.5 * logm(Eigen::Matrix{F.transpose() * F})) .eval(); } }; } // namespace internal /* ---------------------------------------------------------------------- */ //! set of functions returning one strain measure as a function of //! another template decltype(auto) convert_strain(Strain_t && strain) { return internal::ConvertStrain::compute(std::move(strain)); } namespace internal { //! Base template for elastic modulus conversion template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & /*in1*/, const Real & /*in2*/) { // if no return has happened until now, the conversion is not // implemented yet static_assert( (In1 == In2), "This conversion has not been implemented yet, please add " "it here below as a specialisation of this function " "template. Check " "https://en.wikipedia.org/wiki/Lam%C3%A9_parameters for " "the formula."); return 0; } }; /** * Spectialisation for when the output is the first input */ template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & A, const Real & /*B*/) { return A; } }; /** * Spectialisation for when the output is the second input */ template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & /*A*/, const Real & B) { return B; } }; /** * Specialisation μ(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E / (2 * (1 + nu)); } }; /** * Specialisation λ(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E * nu / ((1 + nu) * (1 - 2 * nu)); } }; /** * Specialisation K(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E / (3 * (1 - 2 * nu)); } }; /** * Specialisation E(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & G) { return 9 * K * G / (3 * K + G); } }; /** * Specialisation ν(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & G) { return (3 * K - 2 * G) / (2 * (3 * K + G)); } }; /** * Specialisation E(λ, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & lambda, const Real & G) { return G * (3 * lambda + 2 * G) / (lambda + G); } }; /** * Specialisation λ(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & mu) { return K - 2. * mu / 3.; } }; + /** + * Specialisation K(λ, µ) + */ + template <> + struct Converter { + //! wrapped function (raison d'être) + inline constexpr static Real compute(const Real & lambda, + const Real & G) { + return lambda + (2 * G) / 3; + } + }; + } // namespace internal /** * allows the conversion from any two distinct input moduli to a * chosen output modulus */ template inline constexpr Real convert_elastic_modulus(const Real & in1, const Real & in2) { // enforcing sanity static_assert((In1 != In2), "The input modulus types cannot be identical"); // enforcing independence from order in which moduli are supplied constexpr bool inverted{In1 > In2}; using Converter = std::conditional_t, internal::Converter>; if (inverted) { return Converter::compute(std::move(in2), std::move(in1)); } else { return Converter::compute(std::move(in1), std::move(in2)); } } //! static inline implementation of Hooke's law - template struct Hooke { + template + struct Hooke { /** * compute Lamé's first constant * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_lambda(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute Lamé's second constant (i.e., shear modulus) * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_mu(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the bulk modulus * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_K(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ inline static Eigen::TensorFixedSize> compute_C(const Real & lambda, const Real & mu) { return lambda * Tensors::outer(Tensors::I2(), Tensors::I2()) + 2 * mu * Tensors::I4S(); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ inline static T4Mat compute_C_T4(const Real & lambda, const Real & mu) { return lambda * Matrices::Itrac() + 2 * mu * Matrices::Isymm(); } /** * return stress * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, s_t && E) { return E.trace() * lambda * Strain_t::Identity() + 2 * mu * E; } /** * return stress and tangent stiffness * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor * @param C: stiffness tensor (Piola-Kirchhoff 2 (or σ) w.r.t to `E`) */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, Tangent_t && C, s_t && E) { return std::make_tuple( std::move(evaluate_stress(lambda, mu, std::move(E))), std::move(C)); } }; namespace internal { /* ---------------------------------------------------------------------- */ - template struct NumericalTangentHelper { + template + struct NumericalTangentHelper { using T4_t = T4Mat; using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; template static inline T4_t compute(FunType && fun, const Eigen::MatrixBase & strain, Real delta); }; /* ---------------------------------------------------------------------- */ template template auto NumericalTangentHelper::compute( FunType && fun, const Eigen::MatrixBase & strain, Real delta) -> T4_t { static_assert((FinDif == FiniteDiff::forward) or (FinDif == FiniteDiff::backward), "Not implemented"); T4_t tangent{T4_t::Zero()}; const T2_t fun_val{fun(strain)}; for (Dim_t i{}; i < Dim * Dim; ++i) { T2_t strain2{strain}; T2_vec strain_vec{strain2.data()}; switch (FinDif) { case FiniteDiff::forward: { strain_vec(i) += delta; T2_t del_f_del{(fun(strain2) - fun_val) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } case FiniteDiff::backward: { strain_vec(i) -= delta; T2_t del_f_del{(fun_val - fun(strain2)) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } } static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); } return tangent; } /* ---------------------------------------------------------------------- */ template struct NumericalTangentHelper { using T4_t = T4Mat; using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; template static inline T4_t compute(FunType && fun, const Eigen::MatrixBase & strain, Real delta) { T4_t tangent{T4_t::Zero()}; for (Dim_t i{}; i < Dim * Dim; ++i) { T2_t strain1{strain}; T2_t strain2{strain}; T2_vec strain1_vec{strain1.data()}; T2_vec strain2_vec{strain2.data()}; strain1_vec(i) += delta; strain2_vec(i) -= delta; T2_t del_f_del{(fun(strain1).eval() - fun(strain2).eval()) / (2 * delta)}; tangent.col(i) = T2_vec(del_f_del.data()); static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); } return tangent; } }; } // namespace internal /** * Helper function to numerically determine tangent, intended for * testing, rather than as a replacement for analytical tangents */ template inline T4Mat compute_numerical_tangent( FunType && fun, const Eigen::MatrixBase & strain, Real delta) { static_assert(Derived::RowsAtCompileTime == Dim, "can't handle dynamic matrix"); static_assert(Derived::ColsAtCompileTime == Dim, "can't handle dynamic matrix"); using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; static_assert( std::is_convertible>::value, "Function argument 'fun' needs to be a function taking " "one second-rank tensor as input and returning a " "second-rank tensor"); static_assert(Dim_t(T2_t::SizeAtCompileTime) == Dim_t(T2_vec::SizeAtCompileTime), "wrong map size"); return internal::NumericalTangentHelper::compute( std::forward(fun), strain, delta); } } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ diff --git a/src/materials/stress_transformations.hh b/src/materials/stress_transformations.hh index dfbfa0e..b7d4212 100644 --- a/src/materials/stress_transformations.hh +++ b/src/materials/stress_transformations.hh @@ -1,69 +1,68 @@ /** * @file stress_transformations.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief isolation of stress conversions for quicker compilation * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. - * */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ namespace muSpectre { namespace MatTB { /* ---------------------------------------------------------------------- */ //! set of functions returning an expression for PK2 stress based on template decltype(auto) PK1_stress(Strain_t && strain, Stress_t && stress) { constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "Stress and strain tensors have differing dimensions"); return internal::PK1_stress::compute( std::forward(strain), std::forward(stress)); } /* ---------------------------------------------------------------------- */ //! set of functions returning an expression for PK2 stress based on template decltype(auto) PK1_stress(Strain_t && strain, Stress_t && stress, Tangent_t && tangent) { constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "Stress and strain tensors have differing dimensions"); static_assert((dim == EigenCheck::tensor_4_dim::value), "Stress and tangent tensors have differing dimensions"); return internal::PK1_stress::compute( std::forward(strain), std::forward(stress), std::forward(tangent)); } } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ diff --git a/src/materials/stress_transformations_Kirchhoff_impl.hh b/src/materials/stress_transformations_Kirchhoff_impl.hh index 37c71f5..68e57f4 100644 --- a/src/materials/stress_transformations_Kirchhoff_impl.hh +++ b/src/materials/stress_transformations_Kirchhoff_impl.hh @@ -1,126 +1,113 @@ /** * @file stress_transformations_Kirchhoff_impl.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief Implementation of stress conversions for Kirchhoff stress * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ namespace muSpectre { namespace MatTB { namespace internal { /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get Kirchhoff stress (τ) */ template struct PK1_stress : public PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && F, Stress_t && tau) { return tau * F.inverse().transpose(); } }; /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get Kirchhoff stress (τ) derived * with respect to Gradient */ template struct PK1_stress : public PK1_stress { //! short-hand using Parent = PK1_stress; using Parent::compute; //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && F, Stress_t && tau, Tangent_t && C) { using T4_t = T4Mat; using Mat_t = Eigen::Matrix; Mat_t F_inv{F.inverse()}; - // T4_t K{T4_t::Zero()}; - // for (int i{0}; i < Dim; ++i) { - // for (int j{0}; j < Dim; ++j) { - // for (int k{0}; k < Dim; ++k) { - // for (int l{0}; l < Dim; ++l) { - // for (int a{0}; a < Dim; ++a) { - // get(K, i,j,k,l) += (get(C, i,a,k,l)*F_inv(j,a) - - // tau(i,a) * F_inv(l,a) * F_inv(j,k)); - // } - // } - // } - // } - // } T4_t increment{T4_t::Zero()}; for (int i{0}; i < Dim; ++i) { const int k{i}; for (int j{0}; j < Dim; ++j) { const int a{j}; for (int l{0}; l < Dim; ++l) { get(increment, i, j, k, l) -= tau(a, l); } } } T4_t Ka{C + increment}; T4_t Kb{T4_t::Zero()}; for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { for (int k{0}; k < Dim; ++k) { for (int l{0}; l < Dim; ++l) { for (int a{0}; a < Dim; ++a) { for (int b{0}; b < Dim; ++b) { get(Kb, j, i, k, l) += F_inv(i, a) * get(Ka, a, j, k, b) * F_inv(l, b); } } } } } } Mat_t P = tau * F_inv.transpose(); return std::make_tuple(std::move(P), std::move(Kb)); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ diff --git a/src/materials/stress_transformations_default_case.hh b/src/materials/stress_transformations_default_case.hh index c08d5e6..276701a 100644 --- a/src/materials/stress_transformations_default_case.hh +++ b/src/materials/stress_transformations_default_case.hh @@ -1,79 +1,79 @@ /** * @file stress_transformations_default_case.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief default structure for stress conversions * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ #include "common/common.hh" #include "common/T4_map_proxy.hh" namespace muSpectre { namespace MatTB { namespace internal { /** Structure for functions returning PK1 stress from other stress - *measures + * measures **/ template struct PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && /*strain*/, Stress_t && /*stress*/) { // the following test always fails to generate a compile-time error static_assert((StressM == StressMeasure::Cauchy) && (StressM == StressMeasure::PK1), "The requested Stress conversion is not implemented. " "You either made a programming mistake or need to " "implement it as a specialisation of this function. " "See PK2stress for an example."); } //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && /*strain*/, Stress_t && /*stress*/, Tangent_t && /*stiffness*/) { // the following test always fails to generate a compile-time error static_assert((StressM == StressMeasure::Cauchy) && (StressM == StressMeasure::PK1), "The requested Stress conversion is not implemented. " "You either made a programming mistake or need to " "implement it as a specialisation of this function. " "See PK2stress for an example."); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ diff --git a/src/solver/deprecated_solver_base.hh b/src/solver/deprecated_solver_base.hh index fa42bb4..579680f 100644 --- a/src/solver/deprecated_solver_base.hh +++ b/src/solver/deprecated_solver_base.hh @@ -1,159 +1,160 @@ /** * @file deprecated_solver_base.hh * * @author Till Junge * * @date 18 Dec 2017 * * @brief Base class for solvers * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ #include "solver/solver_common.hh" #include "common/common.hh" #include "cell/cell_base.hh" #include "common/tensor_algebra.hh" #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ /** * Virtual base class for solvers. Any implementation of this interface can be * used with the solver functions prototyped in solvers.hh */ - template class DeprecatedSolverBase { + template + class DeprecatedSolverBase { public: /** * Enum to describe in what kind the solver relies tangent stiffnesses */ enum class TangentRequirement { NoNeed, NeedEffect, NeedTangents }; using Cell_t = CellBase; //!< Cell type using Ccoord = Ccoord_t; //!< cell coordinates type //! Field collection to store temporary fields in using Collection_t = GlobalFieldCollection; //! Input vector for solvers using SolvVectorIn = Eigen::Ref; //! Input vector for solvers using SolvVectorInC = Eigen::Ref; //! Output vector for solvers using SolvVectorOut = Eigen::VectorXd; //! Default constructor DeprecatedSolverBase() = delete; //! Constructor with domain resolutions DeprecatedSolverBase(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverBase(const DeprecatedSolverBase & other) = delete; //! Move constructor DeprecatedSolverBase(DeprecatedSolverBase && other) = default; //! Destructor virtual ~DeprecatedSolverBase() = default; //! Copy assignment operator DeprecatedSolverBase & operator=(const DeprecatedSolverBase & other) = delete; //! Move assignment operator DeprecatedSolverBase & operator=(DeprecatedSolverBase && other) = default; //! Allocate fields used during the solution virtual void initialise() { this->collection.initialise(this->cell.get_subdomain_resolutions(), this->cell.get_subdomain_locations()); } //! determine whether this solver requires full tangent stiffnesses bool need_tangents() const { return (this->get_tangent_req() == TangentRequirement::NeedTangents); } //! determine whether this solver requires evaluation of directional tangent bool need_effect() const { return (this->get_tangent_req() == TangentRequirement::NeedEffect); } //! determine whether this solver has no need for tangents bool no_need_tangent() const { return (this->get_tangent_req() == TangentRequirement::NoNeed); } //! returns whether the solver has converged virtual bool has_converged() const = 0; //! reset the iteration counter to zero void reset_counter(); //! get the count of how many solve steps have been executed since //! construction of most recent counter reset Uint get_counter() const; //! executes the solver virtual SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) = 0; //! return a reference to the cell Cell_t & get_cell() { return cell; } //! read the current maximum number of iterations setting Uint get_maxiter() const { return this->maxiter; } //! set the maximum number of iterations void set_maxiter(Uint val) { this->maxiter = val; } //! read the current tolerance setting Real get_tol() const { return this->tol; } //! set the torelance setting void set_tol(Real val) { this->tol = val; } //! returns the name of the solver virtual std::string name() const = 0; protected: //! returns the tangent requirements of this solver virtual TangentRequirement get_tangent_req() const = 0; Cell_t & cell; //!< reference to the cell Real tol; //!< convergence tolerance Uint maxiter; //!< maximum number of iterations bool verbose; //!< whether or not to write information to the std output Uint counter{0}; //!< iteration counter //! storage for internal fields to avoid reallocations between calls Collection_t collection{}; private: }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ diff --git a/src/solver/deprecated_solver_cg.hh b/src/solver/deprecated_solver_cg.hh index 0af0414..2432b25 100644 --- a/src/solver/deprecated_solver_cg.hh +++ b/src/solver/deprecated_solver_cg.hh @@ -1,122 +1,120 @@ /** * @file deprecated_solver_cg.hh * * @author Till Junge * * @date 20 Dec 2017 * * @brief class for a simple implementation of a conjugate gradient * solver. This follows algorithm 5.2 in Nocedal's Numerical * Optimization (p 112) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ #include "solver/deprecated_solver_base.hh" #include "common/communicator.hh" #include "common/field.hh" #include namespace muSpectre { /** * implements the `muSpectre::DeprecatedSolverBase` interface using a * conjugate gradient solver. This particular class is useful for * trouble shooting, as it can be made very verbose, but for * production runs, it is probably better to use * `muSpectre::DeprecatedSolverCGEigen`. */ template class DeprecatedSolverCG : public DeprecatedSolverBase { public: using Parent = DeprecatedSolverBase; //!< base class //! Input vector for solvers using SolvVectorIn = typename Parent::SolvVectorIn; //! Input vector for solvers using SolvVectorInC = typename Parent::SolvVectorInC; //! Output vector for solvers using SolvVectorOut = typename Parent::SolvVectorOut; using Cell_t = typename Parent::Cell_t; //!< cell type using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! kind of tangent that is required using Tg_req_t = typename Parent::TangentRequirement; //! cg only needs to handle fields that look like strain and stress using Field_t = TensorField; //! conjugate gradient needs directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor DeprecatedSolverCG() = delete; //! Constructor with domain resolutions, etc, DeprecatedSolverCG(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverCG(const DeprecatedSolverCG & other) = delete; //! Move constructor DeprecatedSolverCG(DeprecatedSolverCG && other) = default; //! Destructor virtual ~DeprecatedSolverCG() = default; //! Copy assignment operator DeprecatedSolverCG & operator=(const DeprecatedSolverCG & other) = delete; //! Move assignment operator DeprecatedSolverCG & operator=(DeprecatedSolverCG && other) = default; bool has_converged() const final { return this->converged; } //! actual solver void solve(const Field_t & rhs, Field_t & x); // this simplistic implementation has no initialisation phase so the default // is ok SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) final; std::string name() const final { return "CG"; } protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const final; Field_t & r_k; //!< residual Field_t & p_k; //!< search direction Field_t & Ap_k; //!< effect of tangent on search direction bool converged{false}; //!< whether the solver has converged - - private: }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ diff --git a/src/solver/deprecated_solver_cg_eigen.hh b/src/solver/deprecated_solver_cg_eigen.hh index fb79d79..9102c59 100644 --- a/src/solver/deprecated_solver_cg_eigen.hh +++ b/src/solver/deprecated_solver_cg_eigen.hh @@ -1,252 +1,258 @@ /** * @file deprecated_solver_cg_eigen.hh * * @author Till Junge * * @date 19 Jan 2018 * * @brief binding to Eigen's conjugate gradient solver * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ #include "solver/deprecated_solver_base.hh" #include #include #include namespace muSpectre { template class DeprecatedSolverEigen; - template class DeprecatedSolverCGEigen; + template + class DeprecatedSolverCGEigen; - template class DeprecatedSolverGMRESEigen; + template + class DeprecatedSolverGMRESEigen; - template class DeprecatedSolverBiCGSTABEigen; + template + class DeprecatedSolverBiCGSTABEigen; - template class DeprecatedSolverDGMRESEigen; + template + class DeprecatedSolverDGMRESEigen; - template class DeprecatedSolverMINRESEigen; + template + class DeprecatedSolverMINRESEigen; namespace internal { - template struct DeprecatedSolver_traits {}; + template + struct DeprecatedSolver_traits {}; //! traits for the Eigen conjugate gradient solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::ConjugateGradient< typename DeprecatedSolverEigen, DimS, DimM>::Adaptor, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen GMRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::GMRES< typename DeprecatedSolverEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen BiCGSTAB solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::BiCGSTAB< typename DeprecatedSolverEigen< DeprecatedSolverBiCGSTABEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen DGMRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::DGMRES< typename DeprecatedSolverEigen< DeprecatedSolverDGMRESEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen MINRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::MINRES< typename DeprecatedSolverEigen< DeprecatedSolverMINRESEigen, DimS, DimM>::Adaptor, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner>; }; } // namespace internal /** * base class for iterative solvers from Eigen */ template class DeprecatedSolverEigen : public DeprecatedSolverBase { public: using Parent = DeprecatedSolverBase; //!< base class //! Input vector for solvers using SolvVectorIn = typename Parent::SolvVectorIn; //! Input vector for solvers using SolvVectorInC = typename Parent::SolvVectorInC; //! Output vector for solvers using SolvVectorOut = typename Parent::SolvVectorOut; using Cell_t = typename Parent::Cell_t; //!< cell type using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! kind of tangent that is required using Tg_req_t = typename Parent::TangentRequirement; //! handle for the cell to fit Eigen's sparse matrix interface using Adaptor = typename Cell_t::Adaptor; //! traits obtained from CRTP using DeprecatedSolver = typename internal::DeprecatedSolver_traits< DeprecatedSolverType>::DeprecatedSolver; //! All Eigen solvers need directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor DeprecatedSolverEigen() = delete; //! Constructor with domain resolutions, etc, DeprecatedSolverEigen(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverEigen(const DeprecatedSolverEigen & other) = delete; //! Move constructor DeprecatedSolverEigen(DeprecatedSolverEigen && other) = default; //! Destructor virtual ~DeprecatedSolverEigen() = default; //! Copy assignment operator DeprecatedSolverEigen & operator=(const DeprecatedSolverEigen & other) = delete; //! Move assignment operator DeprecatedSolverEigen & operator=(DeprecatedSolverEigen && other) = default; //! returns whether the solver has converged bool has_converged() const final { return this->solver.info() == Eigen::Success; } //! Allocate fields used during the solution void initialise() final; //! executes the solver SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) final; protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const final; Adaptor adaptor; //!< cell handle DeprecatedSolver solver; //!< Eigen's Iterative solver }; /** * Binding to Eigen's conjugate gradient solver */ template class DeprecatedSolverCGEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const final { return "CG"; } }; /** * Binding to Eigen's GMRES solver */ template class DeprecatedSolverGMRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const final { return "GMRES"; } }; /** * Binding to Eigen's BiCGSTAB solver */ template class DeprecatedSolverBiCGSTABEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "BiCGSTAB"; } }; /** * Binding to Eigen's DGMRES solver */ template class DeprecatedSolverDGMRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "DGMRES"; } }; /** * Binding to Eigen's MINRES solver */ template class DeprecatedSolverMINRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "MINRES"; } }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ diff --git a/src/solver/deprecated_solvers.cc b/src/solver/deprecated_solvers.cc index 349e07d..eee0b94 100644 --- a/src/solver/deprecated_solvers.cc +++ b/src/solver/deprecated_solvers.cc @@ -1,396 +1,397 @@ /** * @file solvers.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief implementation of solver functions * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" #include "common/iterators.hh" #include #include #include namespace muSpectre { template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delFs, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { using Field_t = typename MaterialBase::StrainField_t; const Communicator & comm = cell.get_communicator(); auto solver_fields{std::make_unique>()}; 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 << " =" << std::endl; for (auto && tup : akantu::enumerate(delFs)) { auto && counter{std::get<0>(tup)}; auto && grad{std::get<1>(tup)}; std::cout << "Step " << counter + 1 << ":" << std::endl << grad << std::endl; } count_width = size_t(std::log10(solver.get_maxiter())) + 1; } // initialise F = I or ε = 0 auto & F{cell.get_strain()}; switch (form) { case Formulation::finite_strain: { F.get_map() = Matrices::I2(); break; } case Formulation::small_strain: { F.get_map() = Matrices::I2().Zero(); for (const auto & delF : delFs) { if (!check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown formulation"); break; } // initialise return value std::vector ret_val{}; Grad_t previous_grad{Grad_t::Zero()}; for (const auto & delF : delFs) { // incremental loop std::string message{"Has not converged"}; Real incrNorm{2 * newton_tol}, gradNorm{1}; Real stressNorm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incrNorm, &gradNorm, &newton_tol, &stressNorm, &equil_tol, &message, &has_converged]() { bool incr_test = incrNorm / gradNorm <= newton_tol; bool stress_test = stressNorm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; (newt_iter < solver.get_maxiter()) && (!has_converged || (newt_iter == 1)); ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent(F)}; auto & P{std::get<0>(res_tup)}; auto & K{std::get<1>(res_tup)}; auto tangent_effect = [&cell, &K](const Field_t & dF, Field_t & dP) { cell.directional_stiffness(K, dF, dP); }; if (newt_iter == 0) { DeltaF.get_map() = -(delF - previous_grad); // neg sign because rhs tangent_effect(DeltaF, rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); F.eigen() -= DeltaF.eigen(); } else { rhs.eigen() = -P.eigen(); cell.project(rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigen() = 0; incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); } F.eigen() += incrF.eigen(); incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); if (verbose > 0 && comm.rank() == 0) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incrNorm / gradNorm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << F.get_map().mean() << std::endl; } } convergence_test(); } // update previous gradient previous_grad = delF; ret_val.push_back(OptimizeResult{ F.eigen(), cell.get_stress().eigen(), has_converged, - Int(has_converged), message, newt_iter, solver.get_counter()}); + Int(has_converged), message, newt_iter, solver.get_counter(), form}); // store history variables here cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); //! instantiation for three-dimensional cells template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); /* ---------------------------------------------------------------------- */ template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delFs, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { using Field_t = typename MaterialBase::StrainField_t; const Communicator & comm = cell.get_communicator(); auto solver_fields{std::make_unique>()}; 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 = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and Δ" << strain_symb << " =" << std::endl; for (auto && tup : akantu::enumerate(delFs)) { auto && counter{std::get<0>(tup)}; auto && grad{std::get<1>(tup)}; std::cout << "Step " << counter + 1 << ":" << std::endl << grad << std::endl; } count_width = size_t(std::log10(solver.get_maxiter())) + 1; } // initialise F = I or ε = 0 auto & F{cell.get_strain()}; switch (cell.get_formulation()) { case Formulation::finite_strain: { F.get_map() = Matrices::I2(); break; } case Formulation::small_strain: { F.get_map() = Matrices::I2().Zero(); for (const auto & delF : delFs) { if (!check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown formulation"); break; } // initialise return value std::vector ret_val{}; Grad_t previous_grad{Grad_t::Zero()}; for (const auto & delF : delFs) { // incremental loop // apply macroscopic strain increment for (auto && grad : F.get_map()) { grad += delF - previous_grad; } std::string message{"Has not converged"}; Real incrNorm{2 * newton_tol}, gradNorm{1}; Real stressNorm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incrNorm, &gradNorm, &newton_tol, &stressNorm, &equil_tol, &message, &has_converged]() { bool incr_test = incrNorm / gradNorm <= newton_tol; bool stress_test = stressNorm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; newt_iter < solver.get_maxiter() && !has_converged; ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent(F)}; auto & P{std::get<0>(res_tup)}; rhs.eigen() = -P.eigen(); cell.project(rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigen() = 0; incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); F.eigen() += incrF.eigen(); incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); if (verbose > 0 && comm.rank() == 0) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incrNorm / gradNorm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << F.get_map().mean() << std::endl; } } convergence_test(); } // update previous gradient previous_grad = delF; - ret_val.push_back(OptimizeResult{ - F.eigen(), cell.get_stress().eigen(), convergence_test(), - Int(convergence_test()), message, newt_iter, solver.get_counter()}); + ret_val.push_back(OptimizeResult{F.eigen(), cell.get_stress().eigen(), + convergence_test(), + Int(convergence_test()), message, + newt_iter, solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); //! instantiation for three-dimensional cells template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); } // namespace muSpectre diff --git a/src/solver/solver_cg.hh b/src/solver/solver_cg.hh index eb613fb..3813e28 100644 --- a/src/solver/solver_cg.hh +++ b/src/solver/solver_cg.hh @@ -1,107 +1,105 @@ /** * file solver_cg.hh * * @author Till Junge * * @date 24 Apr 2018 * * @brief class fo a simple implementation of a conjugate gradient solver. * This follows algorithm 5.2 in Nocedal's Numerical Optimization * (p 112) * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_SOLVER_CG_HH_ #define SRC_SOLVER_SOLVER_CG_HH_ #include "solver/solver_base.hh" 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`. */ class SolverCG : public SolverBase { public: using Parent = SolverBase; //!< standard short-hand for base class //! for storage of fields using Vector_t = Parent::Vector_t; //! Input vector for solvers using Vector_ref = Parent::Vector_ref; //! Input vector for solvers using ConstVector_ref = Parent::ConstVector_ref; //! Output vector for solvers using Vector_map = Parent::Vector_map; //! Default constructor SolverCG() = delete; //! 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; //! initialisation does not need to do anything in this case void initialise() final{}; //! returns the solver's name std::string get_name() const final { return "CG"; } //! the actual solver Vector_map solve(const ConstVector_ref rhs) final; protected: Vector_t r_k; //!< residual Vector_t p_k; //!< search direction Vector_t Ap_k; //!< directional stiffness Vector_t x_k; //!< current solution - - private: }; } // namespace muSpectre #endif // SRC_SOLVER_SOLVER_CG_HH_ diff --git a/src/solver/solver_common.hh b/src/solver/solver_common.hh index f207f0d..6744387 100644 --- a/src/solver/solver_common.hh +++ b/src/solver/solver_common.hh @@ -1,100 +1,103 @@ /** * @file solver_common.hh * * @author Till Junge * * @date 28 Dec 2017 * * @brief Errors raised by solvers and other common utilities * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_SOLVER_COMMON_HH_ #define SRC_SOLVER_SOLVER_COMMON_HH_ #include "common/common.hh" #include "common/tensor_algebra.hh" #include #include namespace muSpectre { /** * emulates scipy.optimize.OptimizeResult */ struct OptimizeResult { //! Strain ε or Gradient F at solution Eigen::ArrayXXd grad; //! Cauchy stress σ or first Piola-Kirchhoff stress P at solution Eigen::ArrayXXd stress; //! whether or not the solver exited successfully bool success; //! Termination status of the optimizer. Its value depends on the //! underlying solver. Refer to message for details. Int status; //! Description of the cause of the termination. std::string message; //! number of iterations Uint nb_it; //! number of cell evaluations Uint nb_fev; + //! continuum mechanic flag + Formulation formulation; }; /** * Field type that solvers expect gradients to be expressed in */ - template using Grad_t = Matrices::Tens2_t; + template + using Grad_t = Matrices::Tens2_t; /** * multiple increments can be submitted at once (useful for * path-dependent materials) */ template using GradIncrements = std::vector, Eigen::aligned_allocator>>; /* ---------------------------------------------------------------------- */ class SolverError : public std::runtime_error { using runtime_error::runtime_error; }; /* ---------------------------------------------------------------------- */ class ConvergenceError : public SolverError { using SolverError::SolverError; }; /* ---------------------------------------------------------------------- */ /** * check whether a strain is symmetric, for the purposes of small * strain problems */ bool check_symmetry(const Eigen::Ref & eps, Real rel_tol = 1e-8); } // namespace muSpectre #endif // SRC_SOLVER_SOLVER_COMMON_HH_ diff --git a/src/solver/solver_eigen.cc b/src/solver/solver_eigen.cc index 6aea2fd..a3d6aa7 100644 --- a/src/solver/solver_eigen.cc +++ b/src/solver/solver_eigen.cc @@ -1,89 +1,90 @@ /** * file solver_eigen.cc * * @author Till Junge * * @date 15 May 2018 * * @brief Implementations for bindings to Eigen's iterative solvers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #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() { + 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; } // namespace muSpectre diff --git a/src/solver/solver_eigen.hh b/src/solver/solver_eigen.hh index acbb4d6..d2b43ba 100644 --- a/src/solver/solver_eigen.hh +++ b/src/solver/solver_eigen.hh @@ -1,199 +1,207 @@ /** * file solver_eigen.hh * * @author Till Junge * * @date 15 May 2018 * * @brief Bindings to Eigen's iterative solvers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_SOLVER_EIGEN_HH_ #define SRC_SOLVER_SOLVER_EIGEN_HH_ #include "solver/solver_base.hh" #include "cell/cell_base.hh" #include #include namespace muSpectre { - template class SolverEigen; + template + class SolverEigen; class SolverCGEigen; class SolverGMRESEigen; class SolverBiCGSTABEigen; class SolverDGMRESEigen; class SolverMINRESEigen; namespace internal { - template struct Solver_traits {}; + template + struct Solver_traits {}; //! traits for the Eigen conjugate gradient solver - template <> struct Solver_traits { + template <> + struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::ConjugateGradient; }; //! traits for the Eigen GMRES solver - template <> struct Solver_traits { + template <> + struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::GMRES; }; //! traits for the Eigen BiCGSTAB solver - template <> struct Solver_traits { + template <> + struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::BiCGSTAB; }; //! traits for the Eigen DGMRES solver - template <> struct Solver_traits { + template <> + struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::DGMRES; }; //! traits for the Eigen MINRES solver - template <> struct Solver_traits { + template <> + struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::MINRES; }; } // namespace internal /** * base class for iterative solvers from Eigen */ - template class SolverEigen : public SolverBase { + template + class SolverEigen : public SolverBase { public: using Parent = SolverBase; //!< base class //! traits obtained from CRTP using Solver = typename internal::Solver_traits::Solver; //! Input vectors for solver using ConstVector_ref = Parent::ConstVector_ref; //! Output vector for solver using Vector_map = Parent::Vector_map; //! storage for output vector using Vector_t = Parent::Vector_t; //! Default constructor SolverEigen() = delete; //! Constructor with domain resolutions, etc, SolverEigen(Cell & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor SolverEigen(const SolverEigen & other) = delete; //! Move constructor SolverEigen(SolverEigen && other) = default; //! Destructor virtual ~SolverEigen() = default; //! Copy assignment operator SolverEigen & operator=(const SolverEigen & other) = delete; //! Move assignment operator SolverEigen & operator=(SolverEigen && other) = default; //! Allocate fields used during the solution void initialise() final; //! executes the solver Vector_map solve(const ConstVector_ref rhs) final; protected: Cell::Adaptor adaptor; //!< cell handle Solver solver; //!< Eigen's Iterative solver Vector_t result; //!< storage for result }; /** * Binding to Eigen's conjugate gradient solver */ class SolverCGEigen : public SolverEigen { public: using SolverEigen::SolverEigen; std::string get_name() const final { return "CG"; } }; /** * Binding to Eigen's GMRES solver */ class SolverGMRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; std::string get_name() const final { return "GMRES"; } }; /** * Binding to Eigen's BiCGSTAB solver */ class SolverBiCGSTABEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "BiCGSTAB"; } }; /** * Binding to Eigen's DGMRES solver */ class SolverDGMRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "DGMRES"; } }; /** * Binding to Eigen's MINRES solver */ class SolverMINRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "MINRES"; } }; } // namespace muSpectre #endif // SRC_SOLVER_SOLVER_EIGEN_HH_ diff --git a/src/solver/solvers.cc b/src/solver/solvers.cc index ae0148f..5167b25 100644 --- a/src/solver/solvers.cc +++ b/src/solver/solvers.cc @@ -1,485 +1,484 @@ /** * file solvers.cc * * @author Till Junge * * @date 24 Apr 2018 * * @brief implementation of dynamic newton-cg solver * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/solvers.hh" #include "common/iterators.hh" #include #include namespace muSpectre { Eigen::IOFormat format(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"); - //----------------------------------------------------------------------------// + //--------------------------------------------------------------------------// std::vector newton_cg(Cell & cell, const LoadSteps_t & load_steps, SolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { const Communicator & comm = cell.get_communicator(); using Vector_t = Eigen::Matrix; using Matrix_t = Eigen::Matrix; // Corresponds to symbol δF or δε Vector_t incrF(cell.get_nb_dof()); // field to store the rhs for cg calculations Vector_t rhs(cell.get_nb_dof()); solver.initialise(); size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "Newton-" << solver.get_name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and " << strain_symb << " from " << strain_symb << "₁ =" << std::endl << load_steps.front() << std::endl << " to " << strain_symb << "ₙ =" << std::endl << load_steps.back() << std::endl << "in increments of Δ" << strain_symb << " =" << std::endl << (load_steps.back() - load_steps.front()) / load_steps.size() << std::endl; count_width = size_t(std::log10(solver.get_maxiter())) + 1; } auto shape{cell.get_strain_shape()}; switch (form) { case Formulation::finite_strain: { cell.set_uniform_strain(Matrix_t::Identity(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and (delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } } break; } case Formulation::small_strain: { cell.set_uniform_strain(Matrix_t::Zero(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and (delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } if (not check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; // storage for the previous mean strain (to compute ΔF or Δε) Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; auto F{cell.get_strain_vector()}; //! incremental loop for (const auto & tup : akantu::enumerate(load_steps)) { const auto & strain_step{std::get<0>(tup)}; const auto & macro_strain{std::get<1>(tup)}; if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Load step " << std::setw(count_width) << strain_step + 1 << std::endl; } using StrainMap_t = RawFieldMap>; for (auto && strain : StrainMap_t(F, shape[0], shape[1])) { strain += macro_strain - previous_macro_strain; } std::string message{"Has not converged"}; Real incr_norm{2 * newton_tol}, grad_norm{1}; Real stress_norm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incr_norm, &grad_norm, &newton_tol, &stress_norm, &equil_tol, &message, &has_converged]() { bool incr_test = incr_norm / grad_norm <= newton_tol; bool stress_test = stress_norm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; newt_iter < solver.get_maxiter() && !has_converged; ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent()}; auto & P{std::get<0>(res_tup)}; rhs = -P; cell.apply_projection(rhs); stress_norm = std::sqrt(comm.sum(rhs.squaredNorm())); if (convergence_test()) { break; } - //! this is a potentially avoidable copy TODO: check this out try { incrF = solver.solve(rhs); } catch (ConvergenceError & error) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". In Newton-Raphson step " << newt_iter << ":" << std::endl << error.what() << std::endl - << "The applied boundary condition is " << strain_symb << " =" + << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } F += incrF; incr_norm = std::sqrt(comm.sum(incrF.squaredNorm())); grad_norm = std::sqrt(comm.sum(F.squaredNorm())); if ((verbose > 1) and (comm.rank() == 0)) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incr_norm / grad_norm << ", tol = " << newton_tol << std::endl; if (verbose > 2) { std::cout << "<" << strain_symb << "> =" << std::endl << StrainMap_t(F, shape[0], shape[1]).mean() << std::endl; } } convergence_test(); } if (newt_iter == solver.get_maxiter()) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". Newton-Raphson failed to converge. " - << "The applied boundary condition is " << strain_symb << " =" + << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } // update previous macroscopic strain previous_macro_strain = macro_strain; // store results - ret_val.emplace_back(OptimizeResult{ - F, cell.get_stress_vector(), convergence_test(), - Int(convergence_test()), message, newt_iter, solver.get_counter()}); + ret_val.emplace_back( + OptimizeResult{F, cell.get_stress_vector(), convergence_test(), + Int(convergence_test()), message, newt_iter, + solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } //----------------------------------------------------------------------------// std::vector de_geus(Cell & cell, const LoadSteps_t & load_steps, SolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { const Communicator & comm = cell.get_communicator(); using Vector_t = Eigen::Matrix; using Matrix_t = Eigen::Matrix; // Corresponds to symbol δF or δε Vector_t incrF(cell.get_nb_dof()); // Corresponds to symbol ΔF or Δε Vector_t DeltaF(cell.get_nb_dof()); // field to store the rhs for cg calculations Vector_t rhs(cell.get_nb_dof()); solver.initialise(); size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "de Geus-" << solver.get_name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and " << strain_symb << " from " << strain_symb << "₁ =" << std::endl << load_steps.front() << std::endl << " to " << strain_symb << "ₙ =" << std::endl << load_steps.back() << std::endl << "in increments of Δ" << strain_symb << " =" << std::endl << (load_steps.back() - load_steps.front()) / load_steps.size() << std::endl; count_width = size_t(std::log10(solver.get_maxiter())) + 1; } auto shape{cell.get_strain_shape()}; Matrix_t default_strain_val{}; switch (form) { case Formulation::finite_strain: { - default_strain_val = Matrix_t::Identity(shape[0], shape[1]); - cell.set_uniform_strain(default_strain_val); + 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: { - default_strain_val = Matrix_t::Zero(shape[0], shape[1]); - cell.set_uniform_strain(default_strain_val); + cell.set_uniform_strain(Matrix_t::Zero(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and (delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } if (not check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; // storage for the previous mean strain (to compute ΔF or Δε) Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; auto F{cell.get_strain_vector()}; //! incremental loop for (const auto & tup : akantu::enumerate(load_steps)) { const auto & strain_step{std::get<0>(tup)}; const auto & macro_strain{std::get<1>(tup)}; using StrainMap_t = RawFieldMap>; if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Load step " << std::setw(count_width) << strain_step + 1 << ", " << strain_symb << " =" << std::endl << (macro_strain + default_strain_val).format(format) << std::endl; } std::string message{"Has not converged"}; Real incr_norm{2 * newton_tol}, grad_norm{1}; Real stress_norm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incr_norm, &grad_norm, &newton_tol, &stress_norm, &equil_tol, &message, &has_converged]() { bool incr_test = incr_norm / grad_norm <= newton_tol; bool stress_test = stress_norm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; ((newt_iter < solver.get_maxiter()) and (!has_converged)) or (newt_iter < 2); ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent()}; auto & P{std::get<0>(res_tup)}; try { if (newt_iter == 0) { for (auto && strain : StrainMap_t(DeltaF, shape[0], shape[1])) { strain = macro_strain - previous_macro_strain; } rhs = -cell.evaluate_projected_directional_stiffness(DeltaF); F += DeltaF; stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); if (stress_norm < equil_tol) { incrF.setZero(); } else { incrF = solver.solve(rhs); } } else { rhs = -P; cell.apply_projection(rhs); stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); if (stress_norm < equil_tol) { incrF.setZero(); } else { incrF = solver.solve(rhs); } } } catch (ConvergenceError & error) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". In Newton-Raphson step " << newt_iter << ":" << std::endl << error.what() << std::endl - << "The applied boundary condition is " << strain_symb << " =" + << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } F += incrF; incr_norm = std::sqrt(comm.sum(incrF.squaredNorm())); grad_norm = std::sqrt(comm.sum(F.squaredNorm())); - if ((verbose > 1) and (comm.rank() == 0)) { + if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incr_norm / grad_norm << ", tol = " << newton_tol << std::endl; if (verbose > 2) { std::cout << "<" << strain_symb << "> =" << std::endl << StrainMap_t(F, shape[0], shape[1]).mean().format(format) << std::endl; } } convergence_test(); } if (newt_iter == solver.get_maxiter()) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". Newton-Raphson failed to converge. " - << "The applied boundary condition is " << strain_symb << " =" + << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } // update previous macroscopic strain previous_macro_strain = macro_strain; // store results - ret_val.emplace_back(OptimizeResult{ - F, cell.get_stress_vector(), convergence_test(), - Int(convergence_test()), message, newt_iter, solver.get_counter()}); + ret_val.emplace_back( + OptimizeResult{F, cell.get_stress_vector(), convergence_test(), + Int(convergence_test()), message, newt_iter, + solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } } // namespace muSpectre diff --git a/tests/header_test_fields.cc b/tests/header_test_fields.cc index e108942..509be20 100644 --- a/tests/header_test_fields.cc +++ b/tests/header_test_fields.cc @@ -1,272 +1,273 @@ /** * @file header_test_fields.cc * * @author Till Junge * * @date 20 Sep 2017 * * @brief Test Fields that are used in FieldCollections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "common/field_collection.hh" #include "common/field.hh" #include "common/ccoord_operations.hh" #include #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(field_test); - template struct FieldFixture { + template + struct FieldFixture { constexpr static bool IsGlobal{Global}; constexpr static Dim_t Order{secondOrder}; constexpr static Dim_t SDim{twoD}; constexpr static Dim_t MDim{threeD}; constexpr static Dim_t NbComponents{ipow(MDim, Order)}; using FieldColl_t = std::conditional_t, LocalFieldCollection>; using TField_t = TensorField; using MField_t = MatrixField; using DField_t = TypedField; FieldFixture() : tensor_field{make_field("TensorField", this->fc)}, matrix_field{make_field("MatrixField", this->fc)}, dynamic_field1{make_field( "Dynamically sized field with correct number of" " components", this->fc, ipow(MDim, Order))}, dynamic_field2{make_field( "Dynamically sized field with incorrect number" " of components", this->fc, NbComponents + 1)} {} ~FieldFixture() = default; FieldColl_t fc{}; TField_t & tensor_field; MField_t & matrix_field; DField_t & dynamic_field1; DField_t & dynamic_field2; }; using field_fixtures = boost::mpl::list, FieldFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE(size_check_global, FieldFixture) { // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(tensor_field.size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); // check that returned size is correct Dim_t len{2}; auto sizes{CcoordOps::get_cube(len)}; fc.initialise(sizes, {}); auto nb_pixels{CcoordOps::get_size(sizes)}; BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); constexpr Dim_t pad_size{3}; tensor_field.set_pad_size(pad_size); dynamic_field1.set_pad_size(pad_size); dynamic_field2.set_pad_size(pad_size); // check that setting pad size won't change logical size BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE(size_check_local, FieldFixture) { // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(tensor_field.size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); // check that returned size is correct Dim_t nb_pixels{3}; Eigen::Array new_elem; Eigen::Array wrong_elem; for (Dim_t i{0}; i < NbComponents; ++i) { new_elem(i) = i; wrong_elem(i) = .1 * i; } for (Dim_t i{0}; i < nb_pixels; ++i) { tensor_field.push_back(new_elem); dynamic_field1.push_back(new_elem); BOOST_CHECK_THROW(dynamic_field1.push_back(wrong_elem), FieldError); BOOST_CHECK_THROW(dynamic_field2.push_back(new_elem), FieldError); } BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); for (Dim_t i{0}; i < nb_pixels; ++i) { fc.add_pixel({i}); } fc.initialise(); BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); BOOST_CHECK_EQUAL(tensor_field.get_pad_size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.get_pad_size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.get_pad_size(), 0); constexpr Dim_t pad_size{3}; tensor_field.set_pad_size(pad_size); dynamic_field1.set_pad_size(pad_size); dynamic_field2.set_pad_size(pad_size); BOOST_CHECK_EQUAL(tensor_field.get_pad_size(), pad_size); BOOST_CHECK_EQUAL(dynamic_field1.get_pad_size(), pad_size); BOOST_CHECK_EQUAL(dynamic_field2.get_pad_size(), pad_size); // check that setting pad size won't change logical size BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); } BOOST_AUTO_TEST_CASE(simple_creation) { constexpr Dim_t sdim{twoD}; constexpr Dim_t mdim{twoD}; constexpr Dim_t order{fourthOrder}; using FC_t = GlobalFieldCollection; FC_t fc; using TF_t = TensorField; auto & field{make_field("TensorField 1", fc)}; // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(field.size(), 0); Dim_t len{2}; fc.initialise(CcoordOps::get_cube(len), {}); // check that returned size is correct BOOST_CHECK_EQUAL(field.size(), ipow(len, sdim)); // check that setting pad size won't change logical size field.set_pad_size(24); BOOST_CHECK_EQUAL(field.size(), ipow(len, sdim)); } BOOST_AUTO_TEST_CASE(dynamic_field_creation) { constexpr Dim_t sdim{threeD}; Dim_t nb_components{2}; using FC_t = GlobalFieldCollection; FC_t fc{}; make_field>("Dynamic Field", fc, nb_components); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(get_zeros_like, Fix, field_fixtures, Fix) { auto & t_clone{Fix::tensor_field.get_zeros_like("tensor clone")}; static_assert(std::is_same, typename Fix::TField_t>::value, "wrong overloaded function"); auto & m_clone{Fix::matrix_field.get_zeros_like("matrix clone")}; static_assert(std::is_same, typename Fix::MField_t>::value, "wrong overloaded function"); using FieldColl_t = typename Fix::FieldColl_t; using T = typename Fix::TField_t::Scalar; TypedField & t_ref{t_clone}; auto & typed_clone{t_ref.get_zeros_like("dynamically sized clone")}; static_assert(std::is_same, TypedField>::value, "Field type incorrectly deduced"); BOOST_CHECK_EQUAL(typed_clone.get_nb_components(), t_clone.get_nb_components()); auto & dyn_clone{Fix::dynamic_field1.get_zeros_like("dynamic clone")}; static_assert( std::is_same::value, "mismatch"); BOOST_CHECK_EQUAL(typed_clone.get_nb_components(), dyn_clone.get_nb_components()); } /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(fill_global_local) { FieldFixture global; FieldFixture local; constexpr Dim_t len{2}; constexpr auto sizes{CcoordOps::get_cube::SDim>(len)}; global.fc.initialise(sizes, {}); local.fc.add_pixel({1, 1}); local.fc.add_pixel({0, 1}); local.fc.initialise(); // fill the local matrix field and then transfer it to the global field for (auto mat : local.matrix_field.get_map()) { mat.setRandom(); } global.matrix_field.fill_from_local(local.matrix_field); for (const auto & ccoord : local.fc) { const auto & a{local.matrix_field.get_map()[ccoord]}; const auto & b{global.matrix_field.get_map()[ccoord]}; const Real error{(a - b).norm()}; BOOST_CHECK_EQUAL(error, 0.); } // fill the global tensor field and then transfer it to the global field for (auto mat : global.tensor_field.get_map()) { mat.setRandom(); } local.tensor_field.fill_from_global(global.tensor_field); for (const auto & ccoord : local.fc) { const auto & a{local.matrix_field.get_map()[ccoord]}; const auto & b{global.matrix_field.get_map()[ccoord]}; const Real error{(a - b).norm()}; BOOST_CHECK_EQUAL(error, 0.); } BOOST_CHECK_THROW(local.tensor_field.fill_from_global(global.matrix_field), std::runtime_error); BOOST_CHECK_THROW(global.tensor_field.fill_from_local(local.matrix_field), std::runtime_error); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/header_test_ref_array.cc b/tests/header_test_ref_array.cc index 2d66b1b..b11e4dd 100644 --- a/tests/header_test_ref_array.cc +++ b/tests/header_test_ref_array.cc @@ -1,52 +1,52 @@ /** - * file header_test_ref_array.cc + * @file header_test_ref_array.cc * * @author Till Junge * * @date 04 Dec 2018 * * @brief tests for the RefArray convenience struct * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with GNU Emacs; see the file COPYING. If not, write to the + * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/ref_array.hh" #include "tests.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(RefArray_tests); BOOST_AUTO_TEST_CASE(two_d_test) { std::array values{2, 3}; RefArray refs{values[0], values[1]}; BOOST_CHECK_EQUAL(values[0], refs[0]); BOOST_CHECK_EQUAL(values[1], refs[1]); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/header_test_statefields.cc b/tests/header_test_statefields.cc index 3180945..e409c2b 100644 --- a/tests/header_test_statefields.cc +++ b/tests/header_test_statefields.cc @@ -1,296 +1,299 @@ /** * file header_test_statefields.cc * * @author Till Junge * * @date 01 Mar 2018 * * @brief Test the StateField abstraction and the associated maps * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "common/field.hh" #include "common/field_collection.hh" #include "common/statefield.hh" #include "common/ccoord_operations.hh" #include "tests.hh" #include #include namespace muSpectre { - template struct SF_Fixture { + template + struct SF_Fixture { using FC_t = std::conditional_t, LocalFieldCollection>; using Field_t = TensorField; using ScalField_t = ScalarField; constexpr static size_t nb_mem{2}; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static bool global{Global}; constexpr static size_t get_nb_mem() { return nb_mem; } constexpr static Dim_t get_sdim() { return sdim; } constexpr static Dim_t get_mdim() { return mdim; } constexpr static bool get_global() { return global; } SF_Fixture() : fc{}, sf{make_statefield>("prefix", fc)}, scalar_f{ make_statefield>("scalar", fc)}, self{*this} {} FC_t fc; StateField & sf; StateField & scalar_f; SF_Fixture & self; }; using typelist = boost::mpl::list< SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture>; BOOST_AUTO_TEST_SUITE(statefield); BOOST_AUTO_TEST_CASE(old_values_test) { constexpr Dim_t Dim{twoD}; constexpr size_t NbMem{2}; constexpr bool verbose{false}; using FC_t = LocalFieldCollection; FC_t fc{}; using Field_t = ScalarField; auto & statefield{make_statefield>("name", fc)}; fc.add_pixel({}); fc.initialise(); for (size_t i{0}; i < NbMem + 1; ++i) { statefield.current().eigen() = i + 1; if (verbose) { std::cout << "current = " << statefield.current().eigen() << std::endl << "old 1 = " << statefield.old().eigen() << std::endl << "old 2 = " << statefield.template old<2>().eigen() << std::endl << "indices = " << statefield.get_indices() << std::endl << std::endl; } statefield.cycle(); } BOOST_CHECK_EQUAL(statefield.current().eigen()(0), 1); BOOST_CHECK_EQUAL(statefield.old().eigen()(0), 3); BOOST_CHECK_EQUAL(statefield.template old<2>().eigen()(0), 2); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, Fix, typelist, Fix) { const std::string ref{"prefix"}; const std::string & fix{Fix::sf.get_prefix()}; BOOST_CHECK_EQUAL(ref, fix); } namespace internal { - template struct init { + template + struct init { static void run(Fixture_t & fix) { constexpr Dim_t dim{std::remove_reference_t::sdim}; fix.fc.initialise(CcoordOps::get_cube(3), CcoordOps::get_cube(0)); } }; - template struct init { + template + struct init { static void run(Fixture_t & fix) { constexpr Dim_t dim{std::remove_reference_t::sdim}; CcoordOps::Pixels pixels(CcoordOps::get_cube(3), CcoordOps::get_cube(0)); for (auto && pix : pixels) { fix.fc.add_pixel(pix); } fix.fc.initialise(); } }; } // namespace internal BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_iteration, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr Dim_t mdim{Fix::mdim}; constexpr bool verbose{false}; using StateFMap = StateFieldMap, Fix::nb_mem>; StateFMap matrix_map(Fix::sf); for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : matrix_map) { wrapper.current() += (i + 1) * wrapper.current().Identity(); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::sf.cycle(); } for (auto && wrapper : matrix_map) { auto I{wrapper.current().Identity()}; Real error{(wrapper.current() - I).norm()}; BOOST_CHECK_LT(error, tol); error = (wrapper.old() - 3 * I).norm(); BOOST_CHECK_LT(error, tol); error = (wrapper.template old<2>() - 2 * I).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_default_map, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr bool verbose{false}; auto matrix_map{Fix::sf.get_map()}; for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : matrix_map) { wrapper.current() += (i + 1) * wrapper.current().Identity(); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::sf.cycle(); } auto matrix_const_map{Fix::sf.get_const_map()}; for (auto && wrapper : matrix_const_map) { auto I{wrapper.current().Identity()}; Real error{(wrapper.current() - I).norm()}; BOOST_CHECK_LT(error, tol); error = (wrapper.old() - 3 * I).norm(); BOOST_CHECK_LT(error, tol); error = (wrapper.template old<2>() - 2 * I).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_scalar_map, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr bool verbose{false}; auto scalar_map{Fix::scalar_f.get_map()}; for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : scalar_map) { wrapper.current() += (i + 1); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::scalar_f.cycle(); } auto scalar_const_map{Fix::scalar_f.get_const_map()}; BOOST_CHECK_EQUAL(scalar_const_map[0].current(), scalar_const_map[1].current()); for (auto wrapper : scalar_const_map) { Real error{wrapper.current() - 1}; BOOST_CHECK_LT(error, tol); error = wrapper.old() - 3; BOOST_CHECK_LT(error, tol); error = wrapper.template old<2>() - 2; BOOST_CHECK_LT(error, tol); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Polymorphic_access_by_name, Fix, typelist, Fix) { internal::init::run(Fix::self); // constexpr bool verbose{true}; auto & tensor_field = Fix::fc.get_statefield("prefix"); BOOST_CHECK_EQUAL(tensor_field.get_nb_memory(), Fix::get_nb_mem()); auto & field = Fix::fc.template get_current("prefix"); BOOST_CHECK_EQUAL(field.get_nb_components(), ipow(Fix::get_mdim(), secondOrder)); BOOST_CHECK_THROW(Fix::fc.template get_current("prefix"), std::runtime_error); auto & old_field = Fix::fc.template get_old("prefix"); BOOST_CHECK_EQUAL(old_field.get_nb_components(), field.get_nb_components()); BOOST_CHECK_THROW( Fix::fc.template get_old("prefix", Fix::get_nb_mem() + 1), std::out_of_range); auto & statefield{Fix::fc.get_statefield("prefix")}; auto & typed_statefield{ Fix::fc.template get_typed_statefield("prefix")}; auto map{ArrayFieldMap( typed_statefield.get_current_field())}; for (auto arr : map) { arr.setConstant(1); } Eigen::ArrayXXd field_copy{field.eigen()}; statefield.cycle(); auto & alt_old_field{typed_statefield.get_old_field()}; Real err{(field_copy - alt_old_field.eigen()).matrix().norm() / field_copy.matrix().norm()}; BOOST_CHECK_LT(err, tol); if (not(err < tol)) { std::cout << field_copy << std::endl << std::endl << typed_statefield.get_current_field().eigen() << std::endl << std::endl << typed_statefield.get_old_field(1).eigen() << std::endl << std::endl << typed_statefield.get_old_field(2).eigen() << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/header_test_t4_map.cc b/tests/header_test_t4_map.cc index b9c3df9..2c082e4 100644 --- a/tests/header_test_t4_map.cc +++ b/tests/header_test_t4_map.cc @@ -1,200 +1,201 @@ /** * @file header_test_t4_map.cc * * @author Till Junge * * @date 20 Nov 2017 * * @brief Test the fourth-order map on second-order tensor implementation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include #include "common/common.hh" #include "tests.hh" #include "test_goodies.hh" #include "common/T4_map_proxy.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(T4map_tests); /** * Test fixture for construction of T4Map for the time being, symmetry is not * exploited */ - template struct T4_fixture { + template + struct T4_fixture { T4_fixture() : matrix{}, tensor(matrix.data()) {} EIGEN_MAKE_ALIGNED_OPERATOR_NEW; using M4 = T4Mat; using T4 = T4MatMap; constexpr static Dim_t dim{Dim}; M4 matrix; T4 tensor; }; using fix_collection = boost::mpl::list, T4_fixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(Simple_construction_test, F, fix_collection, F) { BOOST_CHECK_EQUAL(F::tensor.cols(), F::dim * F::dim); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(write_access_test, F, fix_collection, F) { auto & t4 = F::tensor; constexpr Dim_t dim{F::dim}; Eigen::TensorFixedSize> t4c; Eigen::Map t4c_map(t4c.data()); for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; t4c(i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } for (Dim_t i = 0; i < ipow(dim, 4); ++i) { BOOST_CHECK_EQUAL(F::matrix.data()[i], t4c.data()[i]); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(numpy_compatibility, F, fix_collection, F) { auto & t4 = F::tensor; typename F::M4 numpy_ref{}; if (F::dim == twoD) { numpy_ref << 1111., 1112., 1121., 1122., 1211., 1212., 1221., 1222., 2111., 2112., 2121., 2122., 2211., 2212., 2221., 2222.; } else { numpy_ref << 1111., 1112., 1113., 1121., 1122., 1123., 1131., 1132., 1133., 1211., 1212., 1213., 1221., 1222., 1223., 1231., 1232., 1233., 1311., 1312., 1313., 1321., 1322., 1323., 1331., 1332., 1333., 2111., 2112., 2113., 2121., 2122., 2123., 2131., 2132., 2133., 2211., 2212., 2213., 2221., 2222., 2223., 2231., 2232., 2233., 2311., 2312., 2313., 2321., 2322., 2323., 2331., 2332., 2333., 3111., 3112., 3113., 3121., 3122., 3123., 3131., 3132., 3133., 3211., 3212., 3213., 3221., 3222., 3223., 3231., 3232., 3233., 3311., 3312., 3313., 3321., 3322., 3323., 3331., 3332., 3333.; } for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } Real error{(t4 - testGoodies::from_numpy(numpy_ref)).norm()}; BOOST_CHECK_EQUAL(error, 0); if (error != 0) { std::cout << "T4:" << std::endl << t4 << std::endl; std::cout << "reshuffled np:" << std::endl << testGoodies::from_numpy(numpy_ref) << std::endl; std::cout << "original np:" << std::endl << numpy_ref << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(numpy_right_trans, F, fix_collection, F) { auto & t4 = F::tensor; typename F::M4 numpy_ref{}; if (F::dim == twoD) { numpy_ref << 1111., 1121., 1112., 1122., 1211., 1221., 1212., 1222., 2111., 2121., 2112., 2122., 2211., 2221., 2212., 2222.; } else { numpy_ref << 1111., 1121., 1131., 1112., 1122., 1132., 1113., 1123., 1133., 1211., 1221., 1231., 1212., 1222., 1232., 1213., 1223., 1233., 1311., 1321., 1331., 1312., 1322., 1332., 1313., 1323., 1333., 2111., 2121., 2131., 2112., 2122., 2132., 2113., 2123., 2133., 2211., 2221., 2231., 2212., 2222., 2232., 2213., 2223., 2233., 2311., 2321., 2331., 2312., 2322., 2332., 2313., 2323., 2333., 3111., 3121., 3131., 3112., 3122., 3132., 3113., 3123., 3133., 3211., 3221., 3231., 3212., 3222., 3232., 3213., 3223., 3233., 3311., 3321., 3331., 3312., 3322., 3332., 3313., 3323., 3333.; } for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } Real error{(t4 - testGoodies::right_transpose(numpy_ref)).norm()}; BOOST_CHECK_EQUAL(error, 0); if (error != 0) { std::cout << "T4:" << std::endl << t4 << std::endl; std::cout << "reshuffled np:" << std::endl << testGoodies::from_numpy(numpy_ref) << std::endl; std::cout << "original np:" << std::endl << numpy_ref << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(assign_matrix_test, F, fix_collection, F) { decltype(F::matrix) matrix; matrix.setRandom(); F::tensor = matrix; for (Dim_t i = 0; i < ipow(F::dim, 4); ++i) { BOOST_CHECK_EQUAL(F::matrix.data()[i], matrix.data()[i]); } } BOOST_AUTO_TEST_CASE(Return_ref_from_const_test) { constexpr Dim_t dim{2}; using T = int; using M4 = Eigen::Matrix; using M4c = const Eigen::Matrix; using T4 = T4MatMap; using T4c = T4MatMap; M4 mat; mat.setRandom(); M4c cmat{mat}; T4 tensor{mat.data()}; T4c ctensor{mat.data()}; T a = get(tensor, 0, 0, 0, 1); T b = get(ctensor, 0, 0, 0, 1); BOOST_CHECK_EQUAL(a, b); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/mpi_test_fft_engine.cc b/tests/mpi_test_fft_engine.cc index 3a7479c..3658a73 100644 --- a/tests/mpi_test_fft_engine.cc +++ b/tests/mpi_test_fft_engine.cc @@ -1,181 +1,182 @@ /** * @file mpi_test_fft_engine.cc * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief tests for MPI-parallel fft engine implementations * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #define BOOST_MPL_LIMIT_LIST_SIZE 50 #include #include "tests.hh" #include "mpi_context.hh" #include "fft/fftw_engine.hh" #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 nb_components{sdim * sdim}; constexpr static Ccoord_t res() { return CcoordOps::get_cube(box_resolution); } FFTW_fixture() : engine(res(), nb_components, MPIContext::get_context().comm) {} Engine engine; }; - template struct FFTW_fixture_python_segfault { + 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, 4>, FFTW_fixture, 4>, FFTW_fixture_python_segfault>, #endif #ifdef WITH_PFFT FFTW_fixture, 3>, FFTW_fixture, 3>, FFTW_fixture, 4>, FFTW_fixture, 4>, FFTW_fixture_python_segfault>, #endif FFTW_fixture, 3, true>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Constructor_test, Fix, fixlist, Fix) { Communicator & comm = MPIContext::get_context().comm; if (Fix::serial_engine && comm.size() > 1) { return; } else { BOOST_CHECK_NO_THROW(Fix::engine.initialise(FFT_PlanFlags::estimate)); } BOOST_CHECK_EQUAL(comm.sum(Fix::engine.size()), CcoordOps::get_size(Fix::res())); } /* ---------------------------------------------------------------------- */ 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)}; fc.initialise(Fix::engine.get_subdomain_resolutions(), Fix::engine.get_subdomain_locations()); 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::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(); } // namespace muSpectre diff --git a/tests/mpi_test_projection.hh b/tests/mpi_test_projection.hh index 17053bb..f2cb487 100644 --- a/tests/mpi_test_projection.hh +++ b/tests/mpi_test_projection.hh @@ -1,101 +1,107 @@ /** * @file test_projection.hh * * @author Till Junge * * @date 16 Jan 2018 * * @brief common declarations for testing both the small and finite strain * projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "mpi_context.hh" #include #include #ifndef TESTS_MPI_TEST_PROJECTION_HH_ #define TESTS_MPI_TEST_PROJECTION_HH_ namespace muSpectre { /* ---------------------------------------------------------------------- */ - template struct Sizes {}; - template <> struct Sizes { + 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 { + 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 { + 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 { + 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; }; } // namespace muSpectre #endif // TESTS_MPI_TEST_PROJECTION_HH_ diff --git a/tests/py_comparison_test_material_hyper_elasto_plastic1.cc b/tests/py_comparison_test_material_hyper_elasto_plastic1.cc index d65b08f..52c6c73 100644 --- a/tests/py_comparison_test_material_hyper_elasto_plastic1.cc +++ b/tests/py_comparison_test_material_hyper_elasto_plastic1.cc @@ -1,125 +1,132 @@ /** * @file test_material_hyper_elasto_plastic1_comparison.cc * * @author Till Junge * * @date 30 Oct 2018 * * @brief simple wrapper around the MaterialHyperElastoPlastic1 to test it * with arbitrary input * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. */ #include "materials/stress_transformations_Kirchhoff.hh" #include "materials/material_hyper_elasto_plastic1.hh" #include "materials/materials_toolbox.hh" #include #include #include +using pybind11::literals::operator""_a; namespace py = pybind11; -using namespace pybind11::literals; // NOLINT recommended use namespace muSpectre { template decltype(auto) material_wrapper(Real K, Real mu, Real H, Real tau_y0, py::EigenDRef F, py::EigenDRef F_prev, py::EigenDRef be_prev, Real eps_prev) { const Real Young{MatTB::convert_elastic_modulus< ElasticModulus::Young, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; const Real Poisson{MatTB::convert_elastic_modulus< ElasticModulus::Poisson, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; using Mat_t = MaterialHyperElastoPlastic1; Mat_t mat("Name", Young, Poisson, tau_y0, H); auto & coll{mat.get_collection()}; coll.add_pixel({0}); coll.initialise(); auto & F_{mat.get_F_prev_field()}; auto & be_{mat.get_be_prev_field()}; auto & eps_{mat.get_plast_flow_field()}; F_.get_map()[0].current() = F_prev; be_.get_map()[0].current() = be_prev; eps_.get_map()[0].current() = eps_prev; mat.save_history_variables(); return mat.evaluate_stress_tangent(F, F_.get_map()[0], be_.get_map()[0], eps_.get_map()[0]); } template py::tuple kirchhoff_fun(Real K, Real mu, Real H, Real tau_y0, py::EigenDRef F, py::EigenDRef F_prev, py::EigenDRef be_prev, Real eps_prev) { auto && tup{ material_wrapper(K, mu, H, tau_y0, F, F_prev, be_prev, eps_prev)}; auto && tau{std::get<0>(tup)}; auto && C{std::get<1>(tup)}; return py::make_tuple(std::move(tau), std::move(C)); } template py::tuple PK1_fun(Real K, Real mu, Real H, Real tau_y0, py::EigenDRef F, py::EigenDRef F_prev, py::EigenDRef be_prev, Real eps_prev) { auto && tup{ material_wrapper(K, mu, H, tau_y0, F, F_prev, be_prev, eps_prev)}; auto && tau{std::get<0>(tup)}; auto && C{std::get<1>(tup)}; using Mat_t = MaterialHyperElastoPlastic1; constexpr auto StrainM{Mat_t::traits::strain_measure}; constexpr auto StressM{Mat_t::traits::stress_measure}; auto && PK_tup{MatTB::PK1_stress( Eigen::Matrix{F}, tau, C)}; auto && P{std::get<0>(PK_tup)}; auto && K_{std::get<1>(PK_tup)}; return py::make_tuple(std::move(P), std::move(K_)); } PYBIND11_MODULE(material_hyper_elasto_plastic1, mod) { mod.doc() = "Comparison provider for MaterialHyperElastoPlastic1"; auto adder{[&mod](auto name, auto & fun) { mod.def(name, &fun, "K"_a, "mu"_a, "H"_a, "tau_y0"_a, "F"_a, "F_prev"_a, "be_prev"_a, "eps_prev"_a); }}; adder("kirchhoff_fun_2d", kirchhoff_fun); adder("kirchhoff_fun_3d", kirchhoff_fun); adder("PK1_fun_2d", PK1_fun); adder("PK1_fun_3d", PK1_fun); } } // namespace muSpectre diff --git a/tests/py_comparison_test_material_hyper_elasto_plastic1.py b/tests/py_comparison_test_material_hyper_elasto_plastic1.py index ea630d1..003c476 100755 --- a/tests/py_comparison_test_material_hyper_elasto_plastic1.py +++ b/tests/py_comparison_test_material_hyper_elasto_plastic1.py @@ -1,279 +1,287 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file py_comparison_test_material_hyper_elasto_plastic1.py @author Till Junge @date 14 Nov 2018 @brief compares MaterialHyperElastoPlastic1 to de Geus's python implementation @section LICENSE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. """ from material_hyper_elasto_plastic1 import * import itertools import numpy as np np.set_printoptions(linewidth=180) import unittest ##################### dyad22 = lambda A2,B2: np.einsum('ij ,kl ->ijkl',A2,B2) dyad11 = lambda A1,B1: np.einsum('i ,j ->ij ',A1,B1) dot22 = lambda A2,B2: np.einsum('ij ,jk ->ik ',A2,B2) dot24 = lambda A2,B4: np.einsum('ij ,jkmn->ikmn',A2,B4) dot42 = lambda A4,B2: np.einsum('ijkl,lm ->ijkm',A4,B2) inv2 = np.linalg.inv ddot22 = lambda A2,B2: np.einsum('ij ,ji -> ',A2,B2) ddot42 = lambda A4,B2: np.einsum('ijkl,lk ->ij ',A4,B2) ddot44 = lambda A4,B4: np.einsum('ijkl,lkmn->ijmn',A4,B4) class MatTest(unittest.TestCase): def constitutive(self, F,F_t,be_t,ep_t, dim): I = np.eye(dim) II = dyad22(I,I) I4 = np.einsum('il,jk',I,I) I4rt = np.einsum('ik,jl',I,I) I4s = (I4+I4rt)/2. def ln2(A2): vals,vecs = np.linalg.eig(A2) return sum( [np.log(vals[i])*dyad11(vecs[:,i],vecs[:,i]) for i in range(dim)]) def exp2(A2): vals,vecs = np.linalg.eig(A2) return sum( [np.exp(vals[i])*dyad11(vecs[:,i],vecs[:,i]) for i in range(dim)]) # function to compute linearization of the logarithmic Finger tensor def dln2_d2(A2): vals,vecs = np.linalg.eig(A2) K4 = np.zeros([dim, dim, dim, dim]) for m, n in itertools.product(range(dim),repeat=2): if vals[n]==vals[m]: gc = (1.0/vals[m]) else: gc = (np.log(vals[n])-np.log(vals[m]))/(vals[n]-vals[m]) K4 += gc*dyad22(dyad11(vecs[:,m],vecs[:,n]),dyad11(vecs[:,m],vecs[:,n])) return K4 # elastic stiffness tensor C4e = self.K*II+2.*self.mu*(I4s-1./3.*II) # trial state Fdelta = dot22(F,inv2(F_t)) be_s = dot22(Fdelta,dot22(be_t,Fdelta.T)) lnbe_s = ln2(be_s) tau_s = ddot42(C4e,lnbe_s)/2. taum_s = ddot22(tau_s,I)/3. taud_s = tau_s-taum_s*I taueq_s = np.sqrt(3./2.*ddot22(taud_s,taud_s)) div = np.where(taueq_s < 1e-12, np.ones_like(taueq_s), taueq_s) N_s = 3./2.*taud_s/div phi_s = taueq_s-(self.tauy0+self.H*ep_t) phi_s = 1./2.*(phi_s+np.abs(phi_s)) # return map dgamma = phi_s/(self.H+3.*self.mu) ep = ep_t + dgamma tau = tau_s -2.*dgamma*N_s*self.mu lnbe = lnbe_s-2.*dgamma*N_s be = exp2(lnbe) P = dot22(tau,inv2(F).T) # consistent tangent operator a0 = dgamma*self.mu/taueq_s a1 = self.mu/(self.H+3.*self.mu) C4ep = (((self.K-2./3.*self.mu)/2.+a0*self.mu)*II+(1.-3.*a0)*self.mu* I4s+2.*self.mu*(a0-a1)*dyad22(N_s,N_s)) dlnbe4_s = dln2_d2(be_s) dbe4_s = 2.*dot42(I4s,be_s) #K4a = ((C4e/2.)*(phi_s<=0.).astype(np.float)+ # C4ep*(phi_s>0.).astype(np.float)) K4a = np.where(phi_s<=0, C4e/2., C4ep) K4b = ddot44(K4a,ddot44(dlnbe4_s,dbe4_s)) K4c = dot42(-I4rt,tau)+K4b K4 = dot42(dot24(inv2(F),K4c),inv2(F).T) return P,tau,K4,be,ep, dlnbe4_s, dbe4_s, K4a, K4b, K4c def setUp(self): pass def prep(self, dimension): self.dim=dimension self.K=2.+ np.random.rand() self.mu=2.+ np.random.rand() self.H=.1 + np.random.rand()/100 self.tauy0=4. + np.random.rand()/10 self.F_prev=np.eye(self.dim) + (np.random.random((self.dim, self.dim))-.5)/10 self.F = self.F_prev + (np.random.random((self.dim, self.dim))-.5)/10 - self.be_prev=.5*(self.F_prev + self.F_prev.T) + noise = np.random.random((self.dim, self.dim))*1e-2 + self.be_prev=.5*(self.F_prev + self.F_prev.T + noise + noise.T) self.eps_prev=.5+ np.random.rand()/10 self.tol = 1e-13 self.verbose=True def test_specific_case(self): self.dim = 3 self.K = 0.833 self.mu = 0.386 self.tauy0 = .003 self.H = 0.004 self.F_prev = np.eye(self.dim) self.F = np.array([[ 1.00357938, 0.0012795, 0. ], [-0.00126862, 0.99643366, 0. ], [ 0., 0., 0.99999974]]) self.be_prev = np.eye(self.dim) self.eps_prev = 0.0 self.tol = 1e-13 self.verbose = True τ_µ, C_µ_s = kirchhoff_fun_3d(self.K, self.mu, self.H, self.tauy0, self.F, self.F_prev, self.be_prev, self.eps_prev) shape = (self.dim, self.dim, self.dim, self.dim) C_µ = C_µ_s.reshape(shape).transpose((0,1,3,2)) P_µ, K_µ_s = PK1_fun_3d(self.K, self.mu, self.H, self.tauy0, self.F, self.F_prev, self.be_prev, self.eps_prev) K_µ = K_µ_s.reshape(shape).transpose((0,1,3,2)) response_p = self.constitutive(self.F, self.F_prev, self.be_prev, self.eps_prev, self.dim) τ_p, C_p = response_p[1], response_p[8] P_p, K_p = response_p[0], response_p[2] τ_error = np.linalg.norm(τ_µ- τ_p)/np.linalg.norm(τ_µ) if not τ_error < self.tol: print("Error(τ) = {}".format(τ_error)) print("τ_µ:\n{}".format(τ_µ)) print("τ_p:\n{}".format(τ_p)) self.assertLess(τ_error, self.tol) C_error = np.linalg.norm(C_µ- C_p)/np.linalg.norm(C_µ) if not C_error < self.tol: print("Error(C) = {}".format(C_error)) flat_shape = (self.dim**2, self.dim**2) print("C_µ:\n{}".format(C_µ.reshape(flat_shape))) print("C_p:\n{}".format(C_p.reshape(flat_shape))) self.assertLess(C_error, self.tol) P_error = np.linalg.norm(P_µ- P_p)/np.linalg.norm(P_µ) if not P_error < self.tol: print("Error(P) = {}".format(P_error)) print("P_µ:\n{}".format(P_µ)) print("P_p:\n{}".format(P_p)) self.assertLess(P_error, self.tol) K_error = np.linalg.norm(K_µ- K_p)/np.linalg.norm(K_µ) if not K_error < self.tol: print("Error(K) = {}".format(K_error)) flat_shape = (self.dim**2, self.dim**2) print("K_µ:\n{}".format(K_µ.reshape(flat_shape))) print("K_p:\n{}".format(K_p.reshape(flat_shape))) print("diff:\n{}".format(K_p.reshape(flat_shape)- K_µ.reshape(flat_shape))) self.assertLess(K_error, self.tol) def test_equivalence_tau_C(self): for dim in (2, 3): self.runner_equivalence_τ_C(dim) def runner_equivalence_τ_C(self, dimension): self.prep(dimension) fun = kirchhoff_fun_2d if self.dim == 2 else kirchhoff_fun_3d τ_µ, C_µ_s = fun(self.K, self.mu, self.H, self.tauy0, self.F, self.F_prev, self.be_prev, self.eps_prev) shape = (self.dim, self.dim, self.dim, self.dim) C_µ = C_µ_s.reshape(shape).transpose((0,1,3,2)) response_p = self.constitutive(self.F, self.F_prev, self.be_prev, self.eps_prev, self.dim) τ_p, C_p = response_p[1], response_p[8] τ_error = np.linalg.norm(τ_µ- τ_p)/np.linalg.norm(τ_µ) if not τ_error < self.tol: print("Error(τ) = {}".format(τ_error)) print("τ_µ:\n{}".format(τ_µ)) print("τ_p:\n{}".format(τ_p)) self.assertLess(τ_error, self.tol) C_error = np.linalg.norm(C_µ- C_p)/np.linalg.norm(C_µ) if not C_error < self.tol: print("Error(C) = {}".format(C_error)) flat_shape = (self.dim**2, self.dim**2) print("C_µ:\n{}".format(C_µ.reshape(flat_shape))) print("C_p:\n{}".format(C_p.reshape(flat_shape))) self.assertLess(C_error, self.tol) def test_equivalence_P_K(self): for dim in (2, 3): self.runner_equivalence_P_K(dim) def runner_equivalence_P_K(self, dimension): self.prep(dimension) fun = PK1_fun_2d if self.dim == 2 else PK1_fun_3d P_µ, K_µ_s = fun(self.K, self.mu, self.H, self.tauy0, self.F, self.F_prev, self.be_prev, self.eps_prev) shape = (self.dim, self.dim, self.dim, self.dim) K_µ = K_µ_s.reshape(shape).transpose((0,1,3,2)) response_p = self.constitutive(self.F, self.F_prev, self.be_prev, self.eps_prev, self.dim) P_p, K_p = response_p[0], response_p[2] P_error = np.linalg.norm(P_µ- P_p)/np.linalg.norm(P_µ) if not P_error < self.tol: print("Error(P) = {}".format(P_error)) print("P_µ:\n{}".format(P_µ)) print("P_p:\n{}".format(P_p)) self.assertLess(P_error, self.tol) K_error = np.linalg.norm(K_µ- K_p)/np.linalg.norm(K_µ) if not K_error < self.tol: print("Error(K) = {}".format(K_error)) flat_shape = (self.dim**2, self.dim**2) print("K_µ:\n{}".format(K_µ.reshape(flat_shape))) print("K_p:\n{}".format(K_p.reshape(flat_shape))) print("diff:\n{}".format(K_p.reshape(flat_shape)- K_µ.reshape(flat_shape))) self.assertLess(K_error, self.tol) if __name__ == "__main__": unittest.main() diff --git a/tests/python_binding_tests.py b/tests/python_binding_tests.py index 5a8ca7f..5a201bd 100755 --- a/tests/python_binding_tests.py +++ b/tests/python_binding_tests.py @@ -1,210 +1,224 @@ #!/usr/bin/env python3 """ file python_binding_tests.py @author Till Junge @date 09 Jan 2018 @brief Unit tests for python bindings @section LICENCE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from python_test_imports import µ from python_fft_tests import FFT_Check from python_projection_tests import * from python_material_linear_elastic3_test import MaterialLinearElastic3_Check from python_material_linear_elastic4_test import MaterialLinearElastic4_Check +from python_material_linear_elastic_generic1_test import MaterialLinearElasticGeneric1_Check +from python_material_linear_elastic_generic2_test import MaterialLinearElasticGeneric2_Check +from python_comparison_test_material_linear_elastic1 import MatTest as MatTest1 from python_field_tests import FieldCollection_Check from python_material_crystal_plasticity_finite1 import \ MaterialCrystalPlasticityFinite1_Check from python_exact_reference_elastic_test import LinearElastic_Check from python_field_tests import FieldCollection_Check +from python_muSpectre_gradient_integration_test import \ + MuSpectre_gradient_integration_Check +from python_material_evaluator_test import MaterialEvaluator_Check class CellCheck(unittest.TestCase): def test_Construction(self): """ Simple check for cell constructors """ resolution = [5,7] lengths = [5.2, 8.3] formulation = µ.Formulation.small_strain try: sys = µ.Cell(resolution, lengths, formulation) mat = µ.material.MaterialLinearElastic1_2d.make(sys, "material", 210e9, .33) except Exception as err: print(err) raise err class MaterialLinearElastic1_2dCheck(unittest.TestCase): def setUp(self): self.resolution = [5,7] self.lengths = [5.2, 8.3] self.formulation = µ.Formulation.small_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) self.mat = µ.material.MaterialLinearElastic1_2d.make( self.sys, "material", 210e9, .33) def test_add_material(self): self.mat.add_pixel([2,1]) class SolverCheck(unittest.TestCase): def setUp(self): self.resolution = [3, 3]#[5,7] self.lengths = [3., 3.]#[5.2, 8.3] self.formulation = µ.Formulation.finite_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) self.hard = µ.material.MaterialLinearElastic1_2d.make( self.sys, "hard", 210e9, .33) self.soft = µ.material.MaterialLinearElastic1_2d.make( self.sys, "soft", 70e9, .33) def test_solve(self): for i, pixel in enumerate(self.sys): if i < 3: self.hard.add_pixel(pixel) else: self.soft.add_pixel(pixel) self.sys.initialise() tol = 1e-6 Del0 = np.array([[0, .1], [0, 0]]) maxiter = 100 verbose = 0 solver=µ.solvers.SolverCG(self.sys, tol, maxiter, verbose) r = µ.solvers.de_geus(self.sys, Del0, solver,tol, verbose) #print(r) class EigenStrainCheck(unittest.TestCase): def setUp(self): self.resolution = [3, 3]#[5,7] self.lengths = [3., 3.]#[5.2, 8.3] self.formulation = µ.Formulation.small_strain self.cell1 = µ.Cell(self.resolution, self.lengths, self.formulation) self.cell2 = µ.Cell(self.resolution, self.lengths, self.formulation) self.mat1 = µ.material.MaterialLinearElastic1_2d.make( self.cell1, "simple", 210e9, .33) self.mat2 = µ.material.MaterialLinearElastic2_2d.make( self.cell2, "eigen", 210e9, .33) self.mat3 = µ.material.MaterialLinearElastic2_2d.make( self.cell2, "eigen2", 120e9, .33) def test_globalisation(self): for pixel in self.cell2: self.mat2.add_pixel(pixel, np.random.rand(2,2)) loc_eigenstrain = self.mat2.collection.get_real_field("Eigenstrain").array glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") error = np.linalg.norm(loc_eigenstrain-glo_eigenstrain) self.assertEqual(error, 0) def test_globalisation_constant(self): for i, pixel in enumerate(self.cell2): if i%2 == 0: self.mat2.add_pixel(pixel, np.ones((2,2))) else: self.mat3.add_pixel(pixel, np.ones((2,2))) glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") error = np.linalg.norm(glo_eigenstrain-1) self.assertEqual(error, 0) + def test_globalisation(self): + for pixel in self.cell2: + self.mat2.add_pixel(pixel, np.random.rand(2,2)) + loc_eigenstrain = self.mat2.collection.get_real_field("Eigenstrain").array + glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") + error = np.linalg.norm(loc_eigenstrain-glo_eigenstrain) + self.assertEqual(error, 0) + def test_solve(self): verbose_test = False if verbose_test: print("start test_solve") grad = np.array([[1.1, .2], [ .3, 1.5]]) gl_strain = -0.5*(grad.T.dot(grad) - np.eye(2)) gl_strain = -0.5*(grad.T + grad - 2*np.eye(2)) grad = -gl_strain if verbose_test: print("grad =\n{}\ngl_strain =\n{}".format(grad, gl_strain)) for i, pixel in enumerate(self.cell1): self.mat1.add_pixel(pixel) self.mat2.add_pixel(pixel, gl_strain) self.cell1.initialise() self.cell2.initialise() tol = 1e-6 Del0_1 = grad Del0_2 = np.zeros_like(grad) maxiter = 2 verbose = 0 def solve(cell, grad): solver=µ.solvers.SolverCG(cell, tol, maxiter, verbose) r = µ.solvers.newton_cg(cell, grad, solver, tol, tol, verbose) return r results = [solve(cell, del0) for (cell, del0) in zip((self.cell1, self.cell2), (Del0_1, Del0_2))] P1 = results[0].stress P2 = results[1].stress error = np.linalg.norm(P1-P2)/np.linalg.norm(.5*(P1+P2)) if verbose_test: print("cell 1, no eigenstrain") print("P1:\n{}".format(P1[:,0])) print("F1:\n{}".format(results[0].grad[:,0])) print("cell 2, with eigenstrain") print("P2:\n{}".format(P2[:,0])) print("F2:\n{}".format(results[1].grad[:,0])) print("end test_solve") self.assertLess(error, tol) if __name__ == '__main__': unittest.main() diff --git a/tests/python_comparison_test_material_linear_elastic1.py b/tests/python_comparison_test_material_linear_elastic1.py new file mode 100644 index 0000000..59b02c3 --- /dev/null +++ b/tests/python_comparison_test_material_linear_elastic1.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file py_comparison_test_material_linear_elastic1.py + +@author Till Junge + +@date 25 Jan 2019 + +@brief compares MaterialLinearElastic1 to the Geus's python implementation + +Copyright © 2019 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + +import itertools +import numpy as np +np.set_printoptions(linewidth=180) +import unittest + +from python_test_imports import µ +LinMat2 = µ.material.MaterialLinearElastic1_2d +LinMat3 = µ.material.MaterialLinearElastic1_3d +LinMats = {2: LinMat2, 3: LinMat3} + +##################### +dyad22 = lambda A2,B2: np.einsum('ij ,kl ->ijkl',A2,B2) +dyad11 = lambda A1,B1: np.einsum('i ,j ->ij ',A1,B1) +dot22 = lambda A2,B2: np.einsum('ij ,jk ->ik ',A2,B2) +dot24 = lambda A2,B4: np.einsum('ij ,jkmn->ikmn',A2,B4) +dot42 = lambda A4,B2: np.einsum('ijkl,lm ->ijkm',A4,B2) +inv2 = np.linalg.inv +trans2 = np.transpose +ddot22 = lambda A2,B2: np.einsum('ij ,ji -> ',A2,B2) +ddot42 = lambda A4,B2: np.einsum('ijkl,lk ->ij ',A4,B2) +ddot44 = lambda A4,B4: np.einsum('ijkl,lkmn->ijmn',A4,B4) + +class MatTest(unittest.TestCase): + def constitutive(self, F, dim): + I = np.eye(dim) + II = dyad22(I,I) + I4 = np.einsum('il,jk',I,I) + I4rt = np.einsum('ik,jl',I,I) + I4s = (I4+I4rt)/2. + + C4 = self.K*II+2.*self.mu*(I4s-1./3.*II) + S = ddot42(C4,.5*(dot22(trans2(F),F)-I)) + P = dot22(F,S) + K4 = dot24(S,I4)+ddot44(ddot44(I4rt,dot42(dot24(F,C4),trans2(F))),I4rt) + return P, S, K4, C4 + + def setUp(self): + pass + + def prep(self, dimension): + self.dim=dimension + self.Young = 200e9+100*np.random.rand() + self.Poisson = .3 + .1*(np.random.rand()-.5) + self.K = self.Young/(3*(1-2*self.Poisson)) + self.mu = self.Young/(2*(1+self.Poisson)) + self.F = (np.eye(self.dim) + + (np.random.random((self.dim, self.dim))-.5)/10) + self.E = .5*(self.F.T.dot(self.F)-np.eye(self.dim)) + self.tol = 1e-13 + self.verbose=True + + self.linmat, self.evaluator = LinMats[self.dim].make_evaluator( + self.Young, self.Poisson) + self.linmat.add_pixel([0]*self.dim) + + def test_equivalence_S_C(self): + for dim in (2, 3): + self.runner_equivalence_S_C(dim) + + def runner_equivalence_S_C(self, dimension): + self.prep(dimension) + S_μ, C_µ_s = self.evaluator.evaluate_stress_tangent( + self.E, µ.Formulation.small_strain) + S_μ = S_μ.copy() + S_μ2 = self.evaluator.evaluate_stress( + self.E, µ.Formulation.small_strain) + shape = (self.dim, self.dim, self.dim, self.dim) + C_µ = C_µ_s.reshape(shape).transpose((0,1,3,2)) + + response_p = self.constitutive(self.F, self.dim) + S_p, C_p = response_p[1], response_p[3] + + S_error = np.linalg.norm(S_µ- S_p)/np.linalg.norm(S_µ) + if not S_error < self.tol: + print("Error(S) = {}".format(S_error)) + print("S_µ:\n{}".format(S_µ)) + print("S_µ2:\n{}".format(S_µ2)) + print("S_p:\n{}".format(S_p)) + C_error = np.linalg.norm(C_µ- C_p)/np.linalg.norm(C_µ) + if not C_error < self.tol: + print("Error(C) = {}".format(C_error)) + flat_shape = (self.dim**2, self.dim**2) + print("C_µ:\n{}".format(C_µ.reshape(flat_shape))) + print("C_p:\n{}".format(C_p.reshape(flat_shape))) + + self.assertLess(S_error, + self.tol) + + self.assertLess(C_error, + self.tol) + + def test_equivalence_P_K(self): + for dim in (2, 3): + self.runner_equivalence_P_K(dim) + + def runner_equivalence_P_K(self, dimension): + self.prep(dimension) + P_µ, K_µ_s = self.evaluator.evaluate_stress_tangent( + self.F, µ.Formulation.finite_strain) + shape = (self.dim, self.dim, self.dim, self.dim) + K_µ = K_µ_s.reshape(shape).transpose((0,1,3,2)) + + response_p = self.constitutive(self.F, self.dim) + P_p, K_p = response_p[0], response_p[2] + + P_error = np.linalg.norm(P_µ- P_p)/np.linalg.norm(P_µ) + if not P_error < self.tol: + print("Error(P) = {}".format(P_error)) + print("P_µ:\n{}".format(P_µ)) + print("P_p:\n{}".format(P_p)) + K_error = np.linalg.norm(K_µ- K_p)/np.linalg.norm(K_µ) + if not K_error < self.tol: + print("Error(K) = {}".format(K_error)) + flat_shape = (self.dim**2, self.dim**2) + print("K_µ:\n{}".format(K_µ.reshape(flat_shape))) + print("K_p:\n{}".format(K_p.reshape(flat_shape))) + print("diff:\n{}".format(K_p.reshape(flat_shape)- + K_µ.reshape(flat_shape))) + self.assertLess(P_error, + self.tol) + + self.assertLess(K_error, + self.tol) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/python_exact_reference_elastic_test.py b/tests/python_exact_reference_elastic_test.py index f723e34..0f9c61e 100644 --- a/tests/python_exact_reference_elastic_test.py +++ b/tests/python_exact_reference_elastic_test.py @@ -1,434 +1,440 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file python_exact_reference_test.py @author Till Junge @date 18 Jun 2018 @brief Tests exactness of each iterate with respect to python reference implementation from GooseFFT for elasticity 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. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from numpy.linalg import norm from python_test_imports import µ import scipy.sparse.linalg as sp import itertools np.set_printoptions(linewidth=180) comparator_nb_cols=9 # ----------------------------------- GRID ------------------------------------ ndim = 3 # number of dimensions N = 3 # number of voxels (assumed equal for all directions) Nx = Ny = Nz = N def deserialise_t4(t4): turnaround = np.arange(ndim**2).reshape(ndim,ndim).T.reshape(-1) retval = np.zeros([ndim*ndim, ndim*ndim]) for i,j in itertools.product(range(ndim**2), repeat=2): retval[i,j] = t4[:ndim, :ndim, :ndim, :ndim, 0,0].reshape(ndim**2, ndim**2)[turnaround[i], turnaround[j]] pass return retval def scalar_to_goose(s_msp): s_goose = np.zeros((Nx, Ny, Nz)) for i in range(Nx): for j in range(Ny): for k in range(Nz): s_goose[i,j,k] = s_msp[Nz*Ny*i + Nz*j + k] pass pass return s_goose def t2_to_goose(t2_msp): t2_goose = np.zeros((ndim, ndim, Nx, Ny, Nz)) for i in range(Nx): for j in range(Ny): for k in range(Nz): t2_goose[:,:,i,j,k] = t2_msp[:, Nz*Ny*i + Nz*j + k].reshape(ndim, ndim).T pass pass return t2_goose def t2_vec_to_goose(t2_msp_vec): return t2_to_goose(t2_msp_vec.reshape(ndim*ndim, Nx*Ny*Nz)).reshape(-1) def scalar_vec_to_goose(s_msp_vec): return scalar_to_goose(s_msp_vec.reshape(Nx*Ny*N)).reshape(-1) def t4_to_goose(t4_msp, right_transposed=True): t4_goose = np.zeros((ndim, ndim, ndim, ndim, Nx, Ny, Nz)) turnaround = np.arange(ndim**2).reshape(ndim,ndim).T.reshape(-1) for i in range(Nx): for j in range(Ny): for k in range(Nz): tmp = t4_msp[:, Nz*Ny*i + Nz*j + k].reshape(ndim**2, ndim**2) goose_view = t4_goose[:,:,:,:,i,j,k].reshape(ndim**2, ndim**2) for a,b in itertools.product(range(ndim**2), repeat=2): a_id = a if right_transposed else turnaround[a] goose_view[a,b] = tmp[a_id, turnaround[b]] pass pass return t4_goose def t4_vec_to_goose(t4_msp_vec): return t4_to_goose(t4_msp_vec.reshape(ndim**4, Nx*Ny*Nz)).reshape(-1) def t2_from_goose(t2_goose): nb_pix = Nx*Ny*Nz t2_msp = np.zeros((ndim**2, nb_pix), order='F') for i in range(Nx): for j in range(Ny): for k in range(Nz): view = t2_msp[:, i + Nx*j + Nx*Ny*k].reshape(ndim, ndim).T view = t2goose[:,:,i,j,k].T pass pass return t2_msp # ---------------------- PROJECTION, TENSORS, OPERATIONS ---------------------- # tensor operations/products: np.einsum enables index notation, avoiding loops # e.g. ddot42 performs $C_ij = A_ijkl B_lk$ for the entire grid trans2 = lambda A2 : np.einsum('ijxyz ->jixyz ',A2 ) ddot42 = lambda A4,B2: np.einsum('ijklxyz,lkxyz ->ijxyz ',A4,B2) ddot44 = lambda A4,B4: np.einsum('ijklxyz,lkmnxyz->ijmnxyz',A4,B4) dot22 = lambda A2,B2: np.einsum('ijxyz ,jkxyz ->ikxyz ',A2,B2) dot24 = lambda A2,B4: np.einsum('ijxyz ,jkmnxyz->ikmnxyz',A2,B4) dot42 = lambda A4,B2: np.einsum('ijklxyz,lmxyz ->ijkmxyz',A4,B2) dyad22 = lambda A2,B2: np.einsum('ijxyz ,klxyz ->ijklxyz',A2,B2) # identity tensor [single tensor] i = np.eye(ndim) # identity tensors [grid of tensors] I = np.einsum('ij,xyz' , i ,np.ones([N,N,N])) I4 = np.einsum('ijkl,xyz->ijklxyz',np.einsum('il,jk',i,i),np.ones([N,N,N])) I4rt = np.einsum('ijkl,xyz->ijklxyz',np.einsum('ik,jl',i,i),np.ones([N,N,N])) I4s = (I4+I4rt)/2. II = dyad22(I,I) # projection operator [grid of tensors] # NB can be vectorized (faster, less readable), see: "elasto-plasticity.py" # - support function / look-up list / zero initialize delta = lambda i,j: np.float(i==j) # Dirac delta function freq = np.arange(-(N-1)/2.,+(N+1)/2.) # coordinate axis -> freq. axis Ghat4 = np.zeros([ndim,ndim,ndim,ndim,N,N,N]) # zero initialize # - compute for i,j,l,m in itertools.product(range(ndim),repeat=4): for x,y,z in itertools.product(range(N), repeat=3): q = np.array([freq[x], freq[y], freq[z]]) # frequency vector if not q.dot(q) == 0: # zero freq. -> mean Ghat4[i,j,l,m,x,y,z] = delta(i,m)*q[j]*q[l]/(q.dot(q)) # (inverse) Fourier transform (for each tensor component in each direction) fft = lambda x : np.fft.fftshift(np.fft.fftn (np.fft.ifftshift(x),[N,N,N])) ifft = lambda x : np.fft.fftshift(np.fft.ifftn(np.fft.ifftshift(x),[N,N,N])) # functions for the projection 'G', and the product 'G : K^LT : (delta F)^T' G = lambda A2 : np.real( ifft( ddot42(Ghat4,fft(A2)) ) ).reshape(-1) K_dF = lambda dFm: trans2(ddot42(K4,trans2(dFm.reshape(ndim,ndim,N,N,N)))) G_K_dF = lambda dFm: G(K_dF(dFm)) # ------------------- PROBLEM DEFINITION / CONSTITIVE MODEL ------------------- # phase indicator: cubical inclusion of volume fraction (9**3)/(31**3) phase = np.zeros([N,N,N]); phase[:2,:2,:2] = 1. # material parameters + function to convert to grid of scalars param = lambda M0,M1: M0*np.ones([N,N,N])*(1.-phase)+M1*np.ones([N,N,N])*phase K = param(0.833,8.33) # bulk modulus [grid of scalars] mu = param(0.386,3.86) # shear modulus [grid of scalars] # constitutive model: grid of "F" -> grid of "P", "K4" [grid of tensors] def constitutive(F): C4 = K*II+2.*mu*(I4s-1./3.*II) S = ddot42(C4,.5*(dot22(trans2(F),F)-I)) P = dot22(F,S) K4 = dot24(S,I4)+ddot44(ddot44(I4rt,dot42(dot24(F,C4),trans2(F))),I4rt) return P,K4 F = np.array(I,copy=True) P,K4 = constitutive(F) class Counter(object): def __init__(self): self.count = self.reset() def reset(self): self.count = 0 return self.count def get(self): return self.count def __call__(self, dummy): self.count += 1 class LinearElastic_Check(unittest.TestCase): def t2_comparator(self, µT2, gT2): err_sum = 0. err_max = 0. for counter, (i, j, k) in enumerate(self.rve): print((i,j,k)) µ_arr = µT2[:, counter].reshape(ndim, ndim).T g_arr = gT2[:,:,i,j,k] self.assertEqual(Nz*Ny*i+Nz*j + k, counter) print("µSpectre:") print(µ_arr) print("Goose:") print(g_arr) print(µ_arr-g_arr) err = norm(µ_arr-g_arr) print("error norm for pixel {} = {}".format((i, j, k), err)) err_sum += err err_max = max(err_max, err) pass print("∑(err) = {}, max(err) = {}".format (err_sum, err_max)) return err_sum def t4_comparator(self, µT4, gT4, right_transposed=True): """ right_transposed: in de Geus's notation, e.g., stiffness tensors have the last two dimensions inverted """ err_sum = 0. err_max = 0. errs = dict() turnaround = np.arange(ndim**2).reshape(ndim,ndim).T.reshape(-1) def zero_repr(arr): arrcopy = arr.copy() arrcopy[abs(arr)<1e-13] = 0. return arrcopy for counter, (i, j, k) in enumerate(self.rve): µ_arr_tmp = µT4[:, counter].reshape(ndim**2, ndim**2).T µ_arr = np.empty((ndim**2, ndim**2)) for a,b in itertools.product(range(ndim**2), repeat=2): a = a if right_transposed else turnaround[a] µ_arr[a,b] = µ_arr_tmp[a, turnaround[b]] g_arr = gT4[:,:,:,:,i,j,k].reshape(ndim**2, ndim**2) self.assertEqual(Nz*Ny*i+Nz*j + k, counter) print("µSpectre:") print(zero_repr(µ_arr[:, :comparator_nb_cols])) print("Goose:") print(zero_repr(g_arr[:, :comparator_nb_cols])) print("Diff") print(zero_repr((µ_arr-g_arr)[:, :comparator_nb_cols])) err = norm(µ_arr-g_arr)/norm(g_arr) print("error norm for pixel {} = {}".format((i, j, k), err)) err_sum += err errs[(i,j,k)] = err err_max = max(err_max, err) print("count {:>2}: err_norm = {:.5f}, err_sum = {:.5f}".format( counter, err, err_sum)) pass print("∑(err) = {}, max(err) = {}".format (err_sum, err_max)) return err_sum, errs def setUp(self): #---------------------------- µSpectre init ----------------------------------- resolution = list(phase.shape) dim = len(resolution) self.dim=dim center = np.array([r//2 for r in resolution]) incl = resolution[0]//5 ## Domain dimensions lengths = [float(r) for r in resolution] ## formulation (small_strain or finite_strain) formulation = µ.Formulation.finite_strain ## build a computational domain self.rve = µ.Cell(resolution, lengths, formulation) def get_E_nu(bulk, shear): Young = 9*bulk*shear/(3*bulk + shear) Poisson = Young/(2*shear) - 1 return Young, Poisson mat = µ.material.MaterialLinearElastic1_3d E, nu = get_E_nu(.833, .386) hard = mat.make(self.rve, 'hard', 10*E, nu) soft = mat.make(self.rve, 'soft', E, nu) for pixel in self.rve: if pixel[0] < 2 and pixel[1] < 2 and pixel[2] < 2: hard.add_pixel(pixel) else: soft.add_pixel(pixel) def test_solve(self): before_cg_tol = 1e-11 cg_tol = 1e-11 after_cg_tol = 1e-9 newton_tol = 1e-4 # ----------------------------- NEWTON ITERATIONS --------------------- # initialize deformation gradient, and stress/stiffness [tensor grid] global K4, P, F F = np.array(I,copy=True) F2 = np.array(I,copy=True)*1.1 P2,K42 = constitutive(F2) P,K4 = constitutive(F) self.rve.set_uniform_strain(np.array(np.eye(ndim))) µF = self.rve.get_strain() self.assertLess(norm(t2_vec_to_goose(µF) - F.reshape(-1))/norm(F), before_cg_tol) # set macroscopic loading DbarF = np.zeros([ndim,ndim,N,N,N]); DbarF[0,1] += 1.0 # initial residual: distribute "barF" over grid using "K4" b = -G_K_dF(DbarF) F += DbarF Fn = np.linalg.norm(F) iiter = 0 # µSpectre inits µbarF = np.zeros_like(µF) µbarF[ndim, :] += 1. µF2 = µF.copy()*1.1 µP2, µK2 = self.rve.evaluate_stress_tangent(µF2) err = norm(t2_vec_to_goose(µP2) - P2.reshape(-1))/norm(P2) if not (err < before_cg_tol): self.t2_comparator(µP2, µK2) self.assertLess(err, before_cg_tol) self.rve.set_uniform_strain(np.array(np.eye(ndim))) µP, µK = self.rve.evaluate_stress_tangent(µF) err = norm(t2_vec_to_goose(µP) - P.reshape(-1)) if not (err < before_cg_tol): print(µF) self.t2_comparator(µP, P) self.assertLess(err, before_cg_tol) err = norm(t4_vec_to_goose(µK) - K4.reshape(-1))/norm(K4) if not (err < before_cg_tol): print ("err = {}".format(err)) self.assertLess(err, before_cg_tol) µF += µbarF µFn = norm(µF) self.assertLess(norm(t2_vec_to_goose(µF) - F.reshape(-1))/norm(F), before_cg_tol) µG_K_dF = lambda x: self.rve.directional_stiffness(x.reshape(µF.shape)).reshape(-1) µG = lambda x: self.rve.project(x).reshape(-1) µb = -µG_K_dF(µbarF) err = (norm(t2_vec_to_goose(µb.reshape(µF.shape)) - b) / norm(b)) if not (err < before_cg_tol): print("|µb| = {}".format(norm(µb))) print("|b| = {}".format(norm(b))) print("total error = {}".format(err)) self.t2_comparator(µb.reshape(µF.shape), b.reshape(F.shape)) self.assertLess(err, before_cg_tol) # iterate as long as the iterative update does not vanish while True: # solve linear system using CG g_counter = Counter() dFm,_ = sp.cg(tol=cg_tol, A = sp.LinearOperator(shape=(F.size,F.size), matvec=G_K_dF,dtype='float'), b = b, callback=g_counter ) µ_counter = Counter() µdFm,_ = sp.cg(tol=cg_tol, A = sp.LinearOperator(shape=(F.size,F.size), matvec=µG_K_dF,dtype='float'), b = µb, callback=µ_counter) err = g_counter.get()-µ_counter.get() if err != 0: print("n_iter(g) = {}, n_iter(µ) = {}".format(g_counter.get(), µ_counter.get())) pass - #self.assertEqual(g_counter.get(), µ_counter.get()) # in the last iteration, the increment is essentially # zero, so we don't care about relative error anymore err = norm(t2_vec_to_goose(µdFm) - dFm)/norm(dFm) if norm(dFm)/Fn > newton_tol and norm(µdFm)/Fn > newton_tol: if not (err < after_cg_tol): self.t2_comparator(µdFm.reshape(µF.shape), dFm.reshape(F.shape)) print("µdFm.shape = {}".format(µdFm.shape)) print("|µdFm| = {}".format(norm(µdFm))) print("|dFm| = {}".format(norm(dFm))) print("|µdFm - dFm| = {}".format(norm(µdFm-dFm))) print("AssertionWarning: {} is not less than {}".format(err, after_cg_tol)) self.assertLess(err, after_cg_tol) # update DOFs (array -> tens.grid) F += dFm.reshape(ndim,ndim,N,N,N) µF += µdFm.reshape(µF.shape) # new residual stress and tangent P,K4 = constitutive(F) µP, µK = self.rve.evaluate_stress_tangent(µF) err = norm(t2_vec_to_goose(µP) - P.reshape(-1))/norm(P) self.assertLess(err, before_cg_tol) err = norm(t4_vec_to_goose(µK) - K4.reshape(-1))/norm(K4) if not (err < before_cg_tol): print ("err = {}".format(err)) self.t4_comparator(µK, K4) self.assertLess(err, before_cg_tol) # convert res.stress to residual b = -G(P) µb = -µG(µP) # in the last iteration, the rhs is essentianly zero, # leading to large relative errors, which are ok. So we # want either the relative error for the rhs to be small, # or their absolute error to be small compared to unity diff_norm = norm(t2_vec_to_goose(µb) - b.reshape(-1)) err = diff_norm/norm(b) if not ((err < after_cg_tol) or (diff_norm < before_cg_tol)): self.t2_comparator(µb.reshape(µF.shape), b.reshape(F.shape)) print("|µb| = {}".format(norm(µb))) print("|b| = {}".format(norm(b))) print("err = {}".format(err)) print("|µb-b| = {}".format(norm(t2_vec_to_goose(µb) - b.reshape(-1)))) print("AssertionWarning: {} is not less than {}".format(err, before_cg_tol)) self.assertTrue((err < after_cg_tol) or (diff_norm < after_cg_tol)) # print residual to the screen print('Goose: %10.15e'%(np.linalg.norm(dFm)/Fn)) print('µSpectre: %10.15e'%(np.linalg.norm(µdFm)/µFn)) if np.linalg.norm(dFm)/Fn0: break # check convergence iiter += 1 if __name__ == '__main__': unittest.main() diff --git a/tests/python_exact_reference_plastic_test.py b/tests/python_exact_reference_plastic_test.py index 17206b0..72e747e 100644 --- a/tests/python_exact_reference_plastic_test.py +++ b/tests/python_exact_reference_plastic_test.py @@ -1,690 +1,784 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- +from python_exact_reference_elastic_test import ndim, N, Nx, Ny, Nz +from material_hyper_elasto_plastic1 import PK1_fun_3d +import python_exact_reference_elastic_test as elastic_ref +from python_exact_reference_elastic_test import Counter +from python_exact_reference_elastic_test import t2_from_goose +from python_exact_reference_elastic_test import t4_vec_to_goose +from python_exact_reference_elastic_test import t4_to_goose +from python_exact_reference_elastic_test import scalar_vec_to_goose +from python_exact_reference_elastic_test import t2_vec_to_goose +from python_exact_reference_elastic_test import deserialise_t4, t2_to_goose +import sys +import itertools +import scipy.sparse.linalg as sp """ file python_exact_reference_plastic_test.py @author Till Junge @date 22 Jun 2018 @brief Tests exactness of each iterate with respect to python reference implementation from GooseFFT for plasticity 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. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np import numpy.linalg as linalg from python_test_imports import µ # turn of warning for zero division # (which occurs in the linearization of the logarithmic strain) np.seterr(divide='ignore', invalid='ignore') -import scipy.sparse.linalg as sp -import itertools -import sys - -from python_exact_reference_elastic_test import deserialise_t4, t2_to_goose -from python_exact_reference_elastic_test import t2_vec_to_goose -from python_exact_reference_elastic_test import scalar_vec_to_goose -from python_exact_reference_elastic_test import t4_to_goose -from python_exact_reference_elastic_test import t4_vec_to_goose -from python_exact_reference_elastic_test import t2_from_goose -from python_exact_reference_elastic_test import Counter -import python_exact_reference_elastic_test as elastic_ref -from material_hyper_elasto_plastic1 import PK1_fun_3d # ----------------------------------- GRID ------------------------------------ -from python_exact_reference_elastic_test import ndim, N, Nx, Ny, Nz shape = [Nx, Ny, Nz] -standalone_dyad22 = lambda A2,B2: np.einsum('ij ,kl ->ijkl',A2,B2) -standalone_dyad11 = lambda A1,B1: np.einsum('i ,j ->ij ',A1,B1) -standalone_dot22 = lambda A2,B2: np.einsum('ij ,jk ->ik ',A2,B2) -standalone_dot24 = lambda A2,B4: np.einsum('ij ,jkmn->ikmn',A2,B4) -standalone_dot42 = lambda A4,B2: np.einsum('ijkl,lm ->ijkm',A4,B2) + +def standalone_dyad22(A2, B2): return np.einsum('ij ,kl ->ijkl', A2, B2) + + +def standalone_dyad11(A1, B1): return np.einsum('i ,j ->ij ', A1, B1) + + +def standalone_dot22(A2, B2): return np.einsum('ij ,jk ->ik ', A2, B2) + + +def standalone_dot24(A2, B4): return np.einsum('ij ,jkmn->ikmn', A2, B4) + + +def standalone_dot42(A4, B2): return np.einsum('ijkl,lm ->ijkm', A4, B2) + + standalone_inv2 = np.linalg.inv -standalone_ddot22 = lambda A2,B2: np.einsum('ij ,ji -> ',A2,B2) -standalone_ddot42 = lambda A4,B2: np.einsum('ijkl,lk ->ij ',A4,B2) -standalone_ddot44 = lambda A4,B4: np.einsum('ijkl,lkmn->ijmn',A4,B4) - -def constitutive_standalone(K, mu, H, tauy0, F,F_t,be_t,ep_t, dim): - I = np.eye(dim) - II = standalone_dyad22(I,I) - I4 = np.einsum('il,jk',I,I) - I4rt = np.einsum('ik,jl',I,I) - I4s = (I4+I4rt)/2. - - def ln2(A2): - vals,vecs = np.linalg.eig(A2) - return sum( - [np.log(vals[i])*standalone_dyad11(vecs[:,i],vecs[:,i]) for i in range(dim)]) - - def exp2(A2): - vals,vecs = np.linalg.eig(A2) - return sum( - [np.exp(vals[i])*standalone_dyad11(vecs[:,i],vecs[:,i]) for i in range(dim)]) - - # function to compute linearization of the logarithmic Finger tensor - def dln2_d2(A2): - vals,vecs = np.linalg.eig(A2) - K4 = np.zeros([dim, dim, dim, dim]) - for m, n in itertools.product(range(dim),repeat=2): - - if vals[n]==vals[m]: - gc = (1.0/vals[m]) - else: - gc = (np.log(vals[n])-np.log(vals[m]))/(vals[n]-vals[m]) - K4 += gc*standalone_dyad22(standalone_dyad11(vecs[:,m],vecs[:,n]),standalone_dyad11(vecs[:,m],vecs[:,n])) - return K4 - - # elastic stiffness tensor - C4e = K*II+2.*mu*(I4s-1./3.*II) - - # trial state - Fdelta = standalone_dot22(F,standalone_inv2(F_t)) - be_s = standalone_dot22(Fdelta,standalone_dot22(be_t,Fdelta.T)) - lnbe_s = ln2(be_s) - tau_s = standalone_ddot42(C4e,lnbe_s)/2. - taum_s = standalone_ddot22(tau_s,I)/3. - taud_s = tau_s-taum_s*I - taueq_s = np.sqrt(3./2.*standalone_ddot22(taud_s,taud_s)) - div = np.where(taueq_s < 1e-12, np.ones_like(taueq_s), taueq_s) - N_s = 3./2.*taud_s/div - phi_s = taueq_s-(tauy0+H*ep_t) - phi_s = 1./2.*(phi_s+np.abs(phi_s)) - - # return map - dgamma = phi_s/(H+3.*mu) - ep = ep_t + dgamma - tau = tau_s -2.*dgamma*N_s*mu - lnbe = lnbe_s-2.*dgamma*N_s - be = exp2(lnbe) - P = standalone_dot22(tau,standalone_inv2(F).T) - - # consistent tangent operator - a0 = dgamma*mu/taueq_s - a1 = mu/(H+3.*mu) - C4ep = (((K-2./3.*mu)/2.+a0*mu)*II+(1.-3.*a0)*mu* - I4s+2.*mu*(a0-a1)*standalone_dyad22(N_s,N_s)) - dlnbe4_s = dln2_d2(be_s) - dbe4_s = 2.*standalone_dot42(I4s,be_s) - #K4a = ((C4e/2.)*(phi_s<=0.).astype(np.float)+ - # C4ep*(phi_s>0.).astype(np.float)) - K4a = np.where(phi_s<=0, C4e/2., C4ep) - K4b = standalone_ddot44(K4a,standalone_ddot44(dlnbe4_s,dbe4_s)) - K4c = standalone_dot42(-I4rt,tau)+K4b - K4 = standalone_dot42(standalone_dot24(standalone_inv2(F),K4c),standalone_inv2(F).T) - - return P,tau,K4,be,ep, dlnbe4_s, dbe4_s, K4a, K4b, K4c +def standalone_ddot22(A2, B2): return np.einsum('ij ,ji -> ', A2, B2) + + +def standalone_ddot42(A4, B2): return np.einsum('ijkl,lk ->ij ', A4, B2) + + +def standalone_ddot44(A4, B4): return np.einsum('ijkl,lkmn->ijmn', A4, B4) + + +def constitutive_standalone(K, mu, H, tauy0, F, F_t, be_t, ep_t, dim): + I = np.eye(dim) + II = standalone_dyad22(I, I) + I4 = np.einsum('il,jk', I, I) + I4rt = np.einsum('ik,jl', I, I) + I4s = (I4+I4rt)/2. + + def ln2(A2): + vals, vecs = np.linalg.eig(A2) + return sum( + [np.log(vals[i])*standalone_dyad11(vecs[:, i], vecs[:, i]) + for i in range(dim)]) + + def exp2(A2): + vals, vecs = np.linalg.eig(A2) + return sum( + [np.exp(vals[i])*standalone_dyad11(vecs[:, i], vecs[:, i]) + for i in range(dim)]) + + # function to compute linearization of the logarithmic Finger tensor + def dln2_d2(A2): + vals, vecs = np.linalg.eig(A2) + K4 = np.zeros([dim, dim, dim, dim]) + for m, n in itertools.product(range(dim), repeat=2): + + if vals[n] == vals[m]: + gc = (1.0/vals[m]) + else: + gc = (np.log(vals[n])-np.log(vals[m]))/(vals[n]-vals[m]) + K4 += gc*standalone_dyad22(standalone_dyad11( + vecs[:, m], vecs[:, n]), standalone_dyad11(vecs[:, m], + vecs[:, n])) + return K4 + + # elastic stiffness tensor + C4e = K*II+2.*mu*(I4s-1./3.*II) + + # trial state + Fdelta = standalone_dot22(F, standalone_inv2(F_t)) + be_s = standalone_dot22(Fdelta, standalone_dot22(be_t, Fdelta.T)) + lnbe_s = ln2(be_s) + tau_s = standalone_ddot42(C4e, lnbe_s)/2. + taum_s = standalone_ddot22(tau_s, I)/3. + taud_s = tau_s-taum_s*I + taueq_s = np.sqrt(3./2.*standalone_ddot22(taud_s, taud_s)) + div = np.where(taueq_s < 1e-12, np.ones_like(taueq_s), taueq_s) + N_s = 3./2.*taud_s/div + phi_s = taueq_s-(tauy0+H*ep_t) + phi_s = 1./2.*(phi_s+np.abs(phi_s)) + + # return map + dgamma = phi_s/(H+3.*mu) + ep = ep_t + dgamma + tau = tau_s - 2.*dgamma*N_s*mu + lnbe = lnbe_s-2.*dgamma*N_s + be = exp2(lnbe) + P = standalone_dot22(tau, standalone_inv2(F).T) + + # consistent tangent operator + a0 = dgamma*mu/taueq_s + a1 = mu/(H+3.*mu) + C4ep = (((K-2./3.*mu)/2.+a0*mu)*II+(1.-3.*a0)*mu * + I4s+2.*mu*(a0-a1)*standalone_dyad22(N_s, N_s)) + dlnbe4_s = dln2_d2(be_s) + dbe4_s = 2.*standalone_dot42(I4s, be_s) + # K4a = ((C4e/2.)*(phi_s<=0.).astype(np.float)+ + # C4ep*(phi_s>0.).astype(np.float)) + K4a = np.where(phi_s <= 0, C4e/2., C4ep) + K4b = standalone_ddot44(K4a, standalone_ddot44(dlnbe4_s, dbe4_s)) + K4c = standalone_dot42(-I4rt, tau)+K4b + K4 = standalone_dot42(standalone_dot24( + standalone_inv2(F), K4c), standalone_inv2(F).T) + + return P, tau, K4, be, ep, dlnbe4_s, dbe4_s, K4a, K4b, K4c + # ----------------------------- TENSOR OPERATIONS ----------------------------- # tensor operations / products: np.einsum enables index notation, avoiding loops # e.g. ddot42 performs $C_ij = A_ijkl B_lk$ for the entire grid -trans2 = lambda A2 : np.einsum('ijxyz ->jixyz ',A2 ) -ddot22 = lambda A2,B2: np.einsum('ijxyz ,jixyz ->xyz ',A2,B2) -ddot42 = lambda A4,B2: np.einsum('ijklxyz,lkxyz ->ijxyz ',A4,B2) -ddot44 = lambda A4,B4: np.einsum('ijklxyz,lkmnxyz->ijmnxyz',A4,B4) -dot11 = lambda A1,B1: np.einsum('ixyz ,ixyz ->xyz ',A1,B1) -dot22 = lambda A2,B2: np.einsum('ijxyz ,jkxyz ->ikxyz ',A2,B2) -dot24 = lambda A2,B4: np.einsum('ijxyz ,jkmnxyz->ikmnxyz',A2,B4) -dot42 = lambda A4,B2: np.einsum('ijklxyz,lmxyz ->ijkmxyz',A4,B2) -dyad22 = lambda A2,B2: np.einsum('ijxyz ,klxyz ->ijklxyz',A2,B2) -dyad11 = lambda A1,B1: np.einsum('ixyz ,jxyz ->ijxyz ',A1,B1) +def trans2(A2): return np.einsum('ijxyz ->jixyz ', A2) + + +def ddot22(A2, B2): return np.einsum('ijxyz ,jixyz ->xyz ', A2, B2) + + +def ddot42(A4, B2): return np.einsum('ijklxyz,lkxyz ->ijxyz ', A4, B2) + + +def ddot44(A4, B4): return np.einsum('ijklxyz,lkmnxyz->ijmnxyz', A4, B4) + + +def dot11(A1, B1): return np.einsum('ixyz ,ixyz ->xyz ', A1, B1) + + +def dot22(A2, B2): return np.einsum('ijxyz ,jkxyz ->ikxyz ', A2, B2) + + +def dot24(A2, B4): return np.einsum('ijxyz ,jkmnxyz->ikmnxyz', A2, B4) + + +def dot42(A4, B2): return np.einsum('ijklxyz,lmxyz ->ijkmxyz', A4, B2) + + +def dyad22(A2, B2): return np.einsum('ijxyz ,klxyz ->ijklxyz', A2, B2) + + +def dyad11(A1, B1): return np.einsum('ixyz ,jxyz ->ijxyz ', A1, B1) # eigenvalue decomposition of 2nd-order tensor: return in convention i,j,x,y,z # NB requires to swap default order of NumPy (in in/output) def eig2(A2): - swap1i = lambda A1: np.einsum('xyzi ->ixyz ',A1) - swap2 = lambda A2: np.einsum('ijxyz->xyzij',A2) - swap2i = lambda A2: np.einsum('xyzij->ijxyz',A2) - vals,vecs = np.linalg.eig(swap2(A2)) - vals = swap1i(vals) - vecs = swap2i(vecs) - return vals,vecs + def swap1i(A1): return np.einsum('xyzi ->ixyz ', A1) + + def swap2(A2): return np.einsum('ijxyz->xyzij', A2) + + def swap2i(A2): return np.einsum('xyzij->ijxyz', A2) + vals, vecs = np.linalg.eig(swap2(A2)) + vals = swap1i(vals) + vecs = swap2i(vecs) + return vals, vecs # logarithm of grid of 2nd-order tensors + + def ln2(A2): - vals,vecs = eig2(A2) - return sum([np.log(vals[i])*dyad11(vecs[:,i],vecs[:,i]) for i in range(3)]) + vals, vecs = eig2(A2) + return sum([np.log(vals[i])*dyad11(vecs[:, i], vecs[:, i]) + for i in range(3)]) # exponent of grid of 2nd-order tensors + + def exp2(A2): - vals,vecs = eig2(A2) - return sum([np.exp(vals[i])*dyad11(vecs[:,i],vecs[:,i]) for i in range(3)]) + vals, vecs = eig2(A2) + return sum([np.exp(vals[i])*dyad11(vecs[:, i], vecs[:, i]) + for i in range(3)]) # determinant of grid of 2nd-order tensors + + def det2(A2): - return (A2[0,0]*A2[1,1]*A2[2,2]+A2[0,1]*A2[1,2]*A2[2,0]+A2[0,2]*A2[1,0]*A2[2,1])-\ - (A2[0,2]*A2[1,1]*A2[2,0]+A2[0,1]*A2[1,0]*A2[2,2]+A2[0,0]*A2[1,2]*A2[2,1]) + return (A2[0, 0]*A2[1, 1]*A2[2, 2]+A2[0, 1]*A2[1, 2]*A2[2, 0] + + A2[0, 2]*A2[1, 0]*A2[2, 1]) -\ + (A2[0, 2]*A2[1, 1]*A2[2, 0]+A2[0, 1]*A2[1, 0] + * A2[2, 2]+A2[0, 0]*A2[1, 2]*A2[2, 1]) # inverse of grid of 2nd-order tensors + + def inv2(A2): A2det = det2(A2) - A2inv = np.empty([3,3,Nx,Ny,Nz]) - A2inv[0,0] = (A2[1,1]*A2[2,2]-A2[1,2]*A2[2,1])/A2det - A2inv[0,1] = (A2[0,2]*A2[2,1]-A2[0,1]*A2[2,2])/A2det - A2inv[0,2] = (A2[0,1]*A2[1,2]-A2[0,2]*A2[1,1])/A2det - A2inv[1,0] = (A2[1,2]*A2[2,0]-A2[1,0]*A2[2,2])/A2det - A2inv[1,1] = (A2[0,0]*A2[2,2]-A2[0,2]*A2[2,0])/A2det - A2inv[1,2] = (A2[0,2]*A2[1,0]-A2[0,0]*A2[1,2])/A2det - A2inv[2,0] = (A2[1,0]*A2[2,1]-A2[1,1]*A2[2,0])/A2det - A2inv[2,1] = (A2[0,1]*A2[2,0]-A2[0,0]*A2[2,1])/A2det - A2inv[2,2] = (A2[0,0]*A2[1,1]-A2[0,1]*A2[1,0])/A2det + A2inv = np.empty([3, 3, Nx, Ny, Nz]) + A2inv[0, 0] = (A2[1, 1]*A2[2, 2]-A2[1, 2]*A2[2, 1])/A2det + A2inv[0, 1] = (A2[0, 2]*A2[2, 1]-A2[0, 1]*A2[2, 2])/A2det + A2inv[0, 2] = (A2[0, 1]*A2[1, 2]-A2[0, 2]*A2[1, 1])/A2det + A2inv[1, 0] = (A2[1, 2]*A2[2, 0]-A2[1, 0]*A2[2, 2])/A2det + A2inv[1, 1] = (A2[0, 0]*A2[2, 2]-A2[0, 2]*A2[2, 0])/A2det + A2inv[1, 2] = (A2[0, 2]*A2[1, 0]-A2[0, 0]*A2[1, 2])/A2det + A2inv[2, 0] = (A2[1, 0]*A2[2, 1]-A2[1, 1]*A2[2, 0])/A2det + A2inv[2, 1] = (A2[0, 1]*A2[2, 0]-A2[0, 0]*A2[2, 1])/A2det + A2inv[2, 2] = (A2[0, 0]*A2[1, 1]-A2[0, 1]*A2[1, 0])/A2det return A2inv # ------------------------ INITIATE (IDENTITY) TENSORS ------------------------ + # identity tensor (single tensor) -i = np.eye(3) +i = np.eye(3) # identity tensors (grid) -I = np.einsum('ij,xyz' , i ,np.ones([Nx,Ny,Nz])) -I4 = np.einsum('ijkl,xyz->ijklxyz',np.einsum('il,jk',i,i),np.ones([Nx,Ny,Nz])) -I4rt = np.einsum('ijkl,xyz->ijklxyz',np.einsum('ik,jl',i,i),np.ones([Nx,Ny,Nz])) -I4s = (I4+I4rt)/2. -II = dyad22(I,I) +I = np.einsum('ij,xyz', i, np.ones([Nx, Ny, Nz])) +I4 = np.einsum('ijkl,xyz->ijklxyz', np.einsum('il,jk', i, i), + np.ones([Nx, Ny, Nz])) +I4rt = np.einsum('ijkl,xyz->ijklxyz', np.einsum('ik,jl', i, i), + np.ones([Nx, Ny, Nz])) +I4s = (I4+I4rt)/2. +II = dyad22(I, I) # ------------------------------------ FFT ------------------------------------ # projection operator (only for non-zero frequency, associated with the mean) # NB: vectorized version of "hyper-elasticity.py" # - allocate / support function -Ghat4 = np.zeros([3,3,3,3,Nx,Ny,Nz]) # projection operator -x = np.zeros([3 ,Nx,Ny,Nz],dtype='int64') # position vectors -q = np.zeros([3 ,Nx,Ny,Nz],dtype='int64') # frequency vectors -delta = lambda i,j: np.float(i==j) # Dirac delta function +Ghat4 = np.zeros([3, 3, 3, 3, Nx, Ny, Nz]) # projection operator +x = np.zeros([3, Nx, Ny, Nz], dtype='int64') # position vectors +q = np.zeros([3, Nx, Ny, Nz], dtype='int64') # frequency vectors + + +# Dirac delta function +def delta(i, j): return np.float(i == j) + + # - set "x" as position vector of all grid-points [grid of vector-components] -x[0],x[1],x[2] = np.mgrid[:Nx,:Ny,:Nz] +x[0], x[1], x[2] = np.mgrid[:Nx, :Ny, :Nz] # - convert positions "x" to frequencies "q" [grid of vector-components] for i in range(3): - freq = np.arange(-(shape[i]-1)/2,+(shape[i]+1)/2,dtype='int64') + freq = np.arange(-(shape[i]-1)/2, +(shape[i]+1)/2, dtype='int64') q[i] = freq[x[i]] # - compute "Q = ||q||", and "norm = 1/Q" being zero for the mean (Q==0) # NB: avoid zero division -q = q.astype(np.float) -Q = dot11(q,q) -Z = Q==0 -Q[Z] = 1. -norm = 1./Q +q = q.astype(np.float) +Q = dot11(q, q) +Z = Q == 0 +Q[Z] = 1. +norm = 1./Q norm[Z] = 0. # - set projection operator [grid of tensors] for i, j, l, m in itertools.product(range(3), repeat=4): - Ghat4[i,j,l,m] = norm*delta(i,m)*q[j]*q[l] + Ghat4[i, j, l, m] = norm*delta(i, m)*q[j]*q[l] # (inverse) Fourier transform (for each tensor component in each direction) -fft = lambda x: np.fft.fftshift(np.fft.fftn (np.fft.ifftshift(x),[Nx,Ny,Nz])) -ifft = lambda x: np.fft.fftshift(np.fft.ifftn(np.fft.ifftshift(x),[Nx,Ny,Nz])) + + +def fft(x): return np.fft.fftshift( + np.fft.fftn(np.fft.ifftshift(x), [Nx, Ny, Nz])) + + +def ifft(x): return np.fft.fftshift( + np.fft.ifftn(np.fft.ifftshift(x), [Nx, Ny, Nz])) + # functions for the projection 'G', and the product 'G : K^LT : (delta F)^T' -G = lambda A2 : np.real( ifft( ddot42(Ghat4,fft(A2)) ) ).reshape(-1) -K_dF = lambda dFm: trans2(ddot42(K4,trans2(dFm.reshape(3,3,Nx,Ny,Nz)))) -G_K_dF = lambda dFm: G(K_dF(dFm)) +def G(A2): return np.real(ifft(ddot42(Ghat4, fft(A2)))).reshape(-1) + + +def K_dF(dFm): return trans2(ddot42(K4, trans2(dFm.reshape(3, 3, Nx, Ny, Nz)))) + + +def G_K_dF(dFm): return G(K_dF(dFm)) # --------------------------- CONSTITUTIVE RESPONSE --------------------------- # constitutive response to a certain loading and history # NB: completely uncoupled from the FFT-solver, but implemented as a regular # grid of quadrature points, to have an efficient code; # each point is completely independent, just evaluated at the same time -def constitutive(F,F_t,be_t,ep_t): + + +def constitutive(F, F_t, be_t, ep_t): # function to compute linearization of the logarithmic Finger tensor def dln2_d2(A2): - vals,vecs = eig2(A2) - K4 = np.zeros([3,3,3,3,Nx,Ny,Nz]) - for m, n in itertools.product(range(3),repeat=2): - gc = (np.log(vals[n])-np.log(vals[m]))/(vals[n]-vals[m]) - gc[vals[n]==vals[m]] = (1.0/vals[m])[vals[n]==vals[m]] - K4 += gc*dyad22(dyad11(vecs[:,m],vecs[:,n]),dyad11(vecs[:,m],vecs[:,n])) + vals, vecs = eig2(A2) + K4 = np.zeros([3, 3, 3, 3, Nx, Ny, Nz]) + for m, n in itertools.product(range(3), repeat=2): + gc = (np.log(vals[n])-np.log(vals[m]))/(vals[n]-vals[m]) + gc[vals[n] == vals[m]] = (1.0/vals[m])[vals[n] == vals[m]] + K4 += gc*dyad22(dyad11(vecs[:, m], vecs[:, n]), + dyad11(vecs[:, m], vecs[:, n])) return K4 # elastic stiffness tensor - C4e = K*II+2.*mu*(I4s-1./3.*II) + C4e = K*II+2.*mu*(I4s-1./3.*II) # trial state - Fdelta = dot22(F,inv2(F_t)) - be_s = dot22(Fdelta,dot22(be_t,trans2(Fdelta))) - lnbe_s = ln2(be_s) - tau_s = ddot42(C4e,lnbe_s)/2. - taum_s = ddot22(tau_s,I)/3. - taud_s = tau_s-taum_s*I - taueq_s = np.sqrt(3./2.*ddot22(taud_s,taud_s)) + Fdelta = dot22(F, inv2(F_t)) + be_s = dot22(Fdelta, dot22(be_t, trans2(Fdelta))) + lnbe_s = ln2(be_s) + tau_s = ddot42(C4e, lnbe_s)/2. + taum_s = ddot22(tau_s, I)/3. + taud_s = tau_s-taum_s*I + taueq_s = np.sqrt(3./2.*ddot22(taud_s, taud_s)) div = np.where(taueq_s < 1e-12, np.ones_like(taueq_s), taueq_s) - N_s = 3./2.*taud_s/div - phi_s = taueq_s-(tauy0+H*ep_t) - phi_s = 1./2.*(phi_s+np.abs(phi_s)) + N_s = 3./2.*taud_s/div + phi_s = taueq_s-(tauy0+H*ep_t) + phi_s = 1./2.*(phi_s+np.abs(phi_s)) # return map - dgamma = phi_s/(H+3.*mu) - ep = ep_t + dgamma - tau = tau_s -2.*dgamma*N_s*mu - lnbe = lnbe_s-2.*dgamma*N_s - be = exp2(lnbe) - P = dot22(tau,trans2(inv2(F))) + dgamma = phi_s/(H+3.*mu) + ep = ep_t + dgamma + tau = tau_s - 2.*dgamma*N_s*mu + lnbe = lnbe_s-2.*dgamma*N_s + be = exp2(lnbe) + P = dot22(tau, trans2(inv2(F))) # consistent tangent operator - a0 = dgamma*mu/taueq_s - a1 = mu/(H+3.*mu) - C4ep = ((K-2./3.*mu)/2.+a0*mu)*II+(1.-3.*a0)*mu*I4s+2.*mu*(a0-a1)*dyad22(N_s,N_s) + a0 = dgamma*mu/taueq_s + a1 = mu/(H+3.*mu) + C4ep = ((K-2./3.*mu)/2.+a0*mu)*II+(1.-3.*a0) * \ + mu*I4s+2.*mu*(a0-a1)*dyad22(N_s, N_s) dlnbe4_s = dln2_d2(be_s) - dbe4_s = 2.*dot42(I4s,be_s) - #K4a = (C4e/2.)*(phi_s<=0.).astype(np.float)+C4ep*(phi_s>0.).astype(np.float) - K4a = np.where(phi_s<=0, C4e/2., C4ep) - K4b = ddot44(K4a,ddot44(dlnbe4_s,dbe4_s)) - K4c = dot42(-I4rt,tau)+K4b - K4 = dot42(dot24(inv2(F),K4c),trans2(inv2(F))) + dbe4_s = 2.*dot42(I4s, be_s) + + K4a = np.where(phi_s <= 0, C4e/2., C4ep) + K4b = ddot44(K4a, ddot44(dlnbe4_s, dbe4_s)) + K4c = dot42(-I4rt, tau)+K4b + K4 = dot42(dot24(inv2(F), K4c), trans2(inv2(F))) + + return P, K4, be, ep, dlnbe4_s, dbe4_s, K4a, K4b, K4c - return P,K4,be,ep, dlnbe4_s, dbe4_s, K4a, K4b, K4c # phase indicator: square inclusion of volume fraction (3*3*15)/(11*13*15) -phase = np.zeros([Nx,Ny,Nz]); phase[0,0,0] = 1. +phase = np.zeros([Nx, Ny, Nz]) +phase[0, 0, 0] = 1. # function to convert material parameters to grid of scalars -param = lambda M0,M1: M0*np.ones([Nx,Ny,Nz])*(1.-phase)+\ - M1*np.ones([Nx,Ny,Nz])* phase + + +def param(M0, M1): return M0*np.ones([Nx, Ny, Nz])*(1.-phase) +\ + M1*np.ones([Nx, Ny, Nz]) * phase + + # material parameters -K = param(0.833,0.833) # bulk modulus +K = param(0.833, 0.833) # bulk modulus Kmat = K -mu = param(0.386,0.386) # shear modulus -H = param(0.004,0.008) # hardening modulus -tauy0 = param(0.003,0.006) # initial yield stress +mu = param(0.386, 0.386) # shear modulus +H = param(0.004, 0.008) # hardening modulus +tauy0 = param(0.003, 0.006) # initial yield stress # ---------------------------------- LOADING ---------------------------------- # stress, deformation gradient, plastic strain, elastic Finger tensor # NB "_t" signifies that it concerns the value at the previous increment -ep_t = np.zeros([ Nx,Ny,Nz]) -P = np.zeros([3,3,Nx,Ny,Nz]) -F = np.array(I,copy=True) -F_t = np.array(I,copy=True) -be_t = np.array(I,copy=True) +ep_t = np.zeros([Nx, Ny, Nz]) +P = np.zeros([3, 3, Nx, Ny, Nz]) +F = np.array(I, copy=True) +F_t = np.array(I, copy=True) +be_t = np.array(I, copy=True) # initialize macroscopic incremental loading -ninc = 50 -lam = 0.0 -barF = np.array(I,copy=True) -barF_t = np.array(I,copy=True) +ninc = 50 +lam = 0.0 +barF = np.array(I, copy=True) +barF_t = np.array(I, copy=True) # initial tangent operator: the elastic tangent -K4 = K*II+2.*mu*(I4s-1./3.*II) +K4 = K*II+2.*mu*(I4s-1./3.*II) + class ElastoPlastic_Check(unittest.TestCase): t2_comparator = elastic_ref.LinearElastic_Check.t2_comparator t4_comparator = elastic_ref.LinearElastic_Check.t4_comparator def scalar_comparator(self, µ, g): err_sum = 0. err_max = 0. for counter, (i, j, k) in enumerate(self.rve): - print((i,j,k)) + print((i, j, k)) µ_arr = µ[counter] - g_arr = g[i,j,k] + g_arr = g[i, j, k] self.assertEqual(Nz*Ny*i+Nz*j + k, counter) print("µSpectre:") print(µ_arr) print("Goose:") print(g_arr) print(µ_arr-g_arr) err = linalg.norm(µ_arr-g_arr) print("error norm = {}".format(err)) err_sum += err err_max = max(err_max, err) pass - print("∑(err) = {}, max(err) = {}".format (err_sum, err_max)) + print("∑(err) = {}, max(err) = {}".format(err_sum, err_max)) return err_sum - def setUp(self): - #---------------------------- µSpectre init ----------------------------------- + # ---------------------------- µSpectre init -------------------------- resolution = list(phase.shape) dim = len(resolution) - self.dim=dim + self.dim = dim center = np.array([r//2 for r in resolution]) incl = resolution[0]//5 - - ## Domain dimensions + # Domain dimensions lengths = [float(r) for r in resolution] ## formulation (small_strain or finite_strain) formulation = µ.Formulation.finite_strain - ## build a computational domain + # build a computational domain self.rve = µ.Cell(resolution, lengths, formulation) + def get_E_nu(bulk, shear): Young = 9*bulk*shear/(3*bulk + shear) Poisson = Young/(2*shear) - 1 return Young, Poisson mat = µ.material.MaterialHyperElastoPlastic1_3d E, nu = get_E_nu(.833, .386) H = 0.004 tauy0 = .003 self.hard = mat.make(self.rve, 'hard', E, nu, 2*tauy0, 2*H) self.soft = mat.make(self.rve, 'soft', E, nu, tauy0, H) for pixel in self.rve: if pixel[0] == 0 and pixel[1] == 0 and pixel[2] == 0: self.hard.add_pixel(pixel) else: self.soft.add_pixel(pixel) pass pass return def test_solve(self): strict_tol = 1e-11 cg_tol = 1e-11 after_cg_tol = 1e-10 newton_tol = 1e-5 self.rve.set_uniform_strain(np.array(np.eye(ndim))) µF = self.rve.get_strain() µF_t = µF.copy() µbarF_t = µF.copy() # incremental deformation - for inc in range(1,ninc): + for inc in range(1, ninc): print('=============================') print('inc: {0:d}'.format(inc)) # set macroscopic deformation gradient (pure-shear) global lam, F, F_t, barF_t, K4, be_t, ep_t - lam += 0.2/float(ninc) - barF = np.array(I,copy=True) - barF[0,0] = (1.+lam) - barF[1,1] = 1./(1.+lam) + lam += 0.2/float(ninc) + barF = np.array(I, copy=True) + barF[0, 0] = (1.+lam) + barF[1, 1] = 1./(1.+lam) def rel_error_scalar(µ, g, tol, do_assert=True): err = (linalg.norm(scalar_vec_to_goose(µ) - g.reshape(-1)) / linalg.norm(g)) if not (err < tol): self.scalar_comparator(µ.reshape(-1), g) if do_assert: self.assertLess(err, tol) else: print("AssertionWarning: {} is not less than {}".format( err, tol)) pass return err def rel_error_t2(µ, g, tol, do_assert=True): - err = linalg.norm(t2_vec_to_goose(µ) - g.reshape(-1)) / linalg.norm(g) + err = linalg.norm(t2_vec_to_goose( + µ) - g.reshape(-1)) / linalg.norm(g) if not (err < tol): self.t2_comparator(µ.reshape(µF.shape), g.reshape(F.shape)) if do_assert: self.assertLess(err, tol) else: print("AssertionWarning: {} is not less than {}".format( err, tol)) pass return err - def rel_error_t4(µ, g, tol, right_transposed=True, do_assert=True, pixel_tol=1e-4): - err = linalg.norm(t4_vec_to_goose(µ) - g.reshape(-1)) / linalg.norm(g) + def rel_error_t4(µ, g, tol, right_transposed=True, do_assert=True, + pixel_tol=1e-4): + err = linalg.norm(t4_vec_to_goose( + µ) - g.reshape(-1)) / linalg.norm(g) errors = None if not (err < tol): err_sum, errors = self.t4_comparator(µ.reshape(µK.shape), g.reshape(K4.shape), right_transposed) if do_assert: self.assertLess(err, tol) else: print("AssertionWarning: {} is not less than {}".format( err, tol)) pass return err, errors def abs_error_t2(µ, g, tol, do_assert=True): ref_norm = linalg.norm(g) if ref_norm > 1: return rel_error_t2(µ, g, tol, do_assert) else: err = linalg.norm(t2_vec_to_goose(µ) - g.reshape(-1)) if not (err < tol): - self.t2_comparator(µ.reshape(µF.shape), g.reshape(F.shape)) + self.t2_comparator( + µ.reshape(µF.shape), g.reshape(F.shape)) if do_assert: self.assertLess(err, tol) else: - print("AssertionWarning: {} is not less than {}".format( + print(("AssertionWarning: {} is not less than {}" + + "").format( err, tol)) return err rel_error_t2(µF, F, strict_tol) # store normalization Fn = np.linalg.norm(F) # first iteration residual: distribute "barF" over grid using "K4" - b = -G_K_dF(barF-barF_t) - F += barF-barF_t + b = -G_K_dF(barF-barF_t) + F += barF-barF_t - # parameters for Newton iterations: normalization and iteration counter - Fn = np.linalg.norm(F) + # parameters for Newton iterations: normalization and iteration + # counter + Fn = np.linalg.norm(F) iiter = 0 # µSpectre inits µbarF = np.zeros_like(µF) - µbarF[0, :] = 1. + lam + µbarF[0, :] = 1. + lam µbarF[ndim + 1, :] = 1./(1. + lam) - µbarF[-1, :] = 1. + µbarF[-1, :] = 1. rel_error_t2(µbarF, barF, strict_tol) if inc == 1: µP, µK = self.rve.evaluate_stress_tangent(µF) rel_error_t4(µK, K4, strict_tol) µF += µbarF - µbarF_t rel_error_t2(µF, F, strict_tol) µFn = linalg.norm(µF) self.assertLess((µFn-Fn)/Fn, strict_tol) - µG_K_dF = lambda x: self.rve.directional_stiffness(x.reshape(µF.shape)).reshape(-1) - µG = lambda x: self.rve.project(x).reshape(-1) + def µG_K_dF(x): return self.rve.directional_stiffness( + x.reshape(µF.shape)).reshape(-1) + + def µG(x): return self.rve.project(x).reshape(-1) µb = -µG_K_dF(µbarF-µbarF_t) abs_error_t2(µb, b, strict_tol) # because of identical elastic properties, µb has got to # be zero before plasticity kicks in print("inc = {}".format(inc)) if inc == 1: self.assertLess(linalg.norm(µb), strict_tol) - #print(self.hard.list_fields()) - #print(self.hard.collection.statefield_names) - #sys.exit() - global_be_t = self.rve.get_globalised_current_real_array( "Previous left Cauchy-Green deformation bₑᵗ") # iterate as long as the iterative update does not vanish while True: - # solve linear system using the Conjugate Gradient iterative solver + # solve linear system using the Conjugate Gradient iterative + # solver g_counter = Counter() - dFm,_ = sp.cg(tol=cg_tol, - atol=1e-10, - A = sp.LinearOperator(shape=(F.size,F.size),matvec=G_K_dF,dtype='float'), - b = b, - callback=g_counter - ) - µ_counter = Counter() - µdFm,_ = sp.cg(tol=cg_tol, + dFm, _ = sp.cg(tol=cg_tol, atol=1e-10, - A = sp.LinearOperator(shape=(F.size,F.size), - matvec=µG_K_dF,dtype='float'), - b = µb, - callback=µ_counter) + A=sp.LinearOperator( + shape=(F.size, F.size), matvec=G_K_dF, + dtype='float'), + b=b, + callback=g_counter + ) + µ_counter = Counter() + µdFm, _ = sp.cg(tol=cg_tol, + atol=1e-10, + A=sp.LinearOperator(shape=(F.size, F.size), + matvec=µG_K_dF, + dtype='float'), + b=µb, + callback=µ_counter) err = g_counter.get()-µ_counter.get() if err != 0: - print("n_iter(g) = {}, n_iter(µ) = {}".format(g_counter.get(), - µ_counter.get())) + print( + "n_iter(g) = {}, n_iter(µ) = {}".format( + g_counter.get(), µ_counter.get())) print("AssertionWarning: {} != {}".format(g_counter.get(), µ_counter.get())) - - #self.assertEqual(g_counter.get(), µ_counter.get()) - try: err = abs_error_t2(µdFm, dFm, after_cg_tol, do_assert=True) except Exception as err: raise err # add solution of linear system to DOFs - F += dFm.reshape(3,3,Nx,Ny,Nz) + F += dFm.reshape(3, 3, Nx, Ny, Nz) µF += µdFm.reshape(µF.shape) err = rel_error_t2(µF, F, strict_tol, do_assert=True) # compute residual stress and tangent, convert to residual - P,K4,be,ep,dln, dbe4_s, K4a, K4b, K4c = constitutive(F,F_t,be_t,ep_t) + P, K4, be, ep, dln, dbe4_s, K4a, K4b, K4c = constitutive( + F, F_t, be_t, ep_t) µP, µK = self.rve.evaluate_stress_tangent(µF) err = rel_error_t2(µP, P, strict_tol) µbe = self.rve.get_globalised_current_real_array( "Previous left Cauchy-Green deformation bₑᵗ") err = rel_error_t2(µbe, be, strict_tol) µep = self.rve.get_globalised_current_real_array( "cumulated plastic flow εₚ") err = rel_error_scalar(µep, ep, strict_tol) - #µK4b = self.rve.get_globalised_internal_real_array( - # "debug-T4") - #err = rel_error_t4(µK4c, K4c, strict_tol, do_assert=True) err, errors = rel_error_t4(µK, K4, strict_tol, do_assert=False) if not err < strict_tol: - def t2_disp(name, µ, g, i,j,k, index): - g_v = g[:,:,i,j,k].copy() - µ_v = µ[:,index].reshape(3,3).T + def t2_disp(name, µ, g, i, j, k, index): + g_v = g[:, :, i, j, k].copy() + µ_v = µ[:, index].reshape(3, 3).T print("{}_g =\n{}".format(name, g_v)) print("{}_µ =\n{}".format(name, µ_v)) - print("{}_err = {}".format(name, np.linalg.norm(g_v-µ_v))) + print("{}_err = {}".format( + name, np.linalg.norm(g_v-µ_v))) return g_v, µ_v - def t0_disp(name, µ, g, i,j,k, index): - g_v = g[i,j,k].copy() - µ_v = µ[:,index] + + def t0_disp(name, µ, g, i, j, k, index): + g_v = g[i, j, k].copy() + µ_v = µ[:, index] print("{}_g =\n{}".format(name, g_v)) print("{}_µ =\n{}".format(name, µ_v)) print("{}_err = {}".format(name, abs(g_v-µ_v))) return g_v, µ_v for pixel, error in errors.items(): - for index, (ir,jr,kr) in enumerate(self.rve): - i,j,k = pixel - if (i,j,k) == (ir,jr,kr): + for index, (ir, jr, kr) in enumerate(self.rve): + i, j, k = pixel + if (i, j, k) == (ir, jr, kr): break if error > 1e-4: - i,j,k = pixel + i, j, k = pixel print("error for pixel {} ({}) = {}".format( pixel, index, error)) t2_disp("F", µF, F, i, j, k, index) t2_disp("be", µbe, be, i, j, k, index) - F_t_n, dummy = t2_disp("F_t", µF_t, F_t, i,j,k,index) + F_t_n, dummy = t2_disp( + "F_t", µF_t, F_t, i, j, k, index) print("ep.shape = {}".format(µep.shape)) t0_disp("ep", µep, ep, i, j, k, index) - K_comp_g = K4[:,:,:,:,i,j,k].reshape(9,9) + K_comp_g = K4[:, :, :, :, i, j, k].reshape(9, 9) K_comp_µ = µK[:, index].reshape( - 3,3,3,3).transpose( - 1,0,3,2).reshape(9,9) - F_n = F[:,:,i,j,k] - be_n = be_t[:,:,i,j,k] - ep_n = ep_t[i,j,k] + 3, 3, 3, 3).transpose( + 1, 0, 3, 2).reshape(9, 9) + F_n = F[:, :, i, j, k] + be_n = be_t[:, :, i, j, k] + ep_n = ep_t[i, j, k] response = constitutive_standalone(Kmat[pixel], mu[pixel], H[pixel], tauy0[pixel], F_n, F_t_n, be_n, ep_n, 3) P_gn, K_gn = response[0], response[2] P_µn, K_µn = PK1_fun_3d(Kmat[pixel], mu[pixel], H[pixel], tauy0[pixel], F_n, F_t_n, be_n, ep_n) - K_µn = K_µn.reshape(3,3,3,3).transpose(1,0,3,2).reshape(9,9) + K_µn = K_µn.reshape(3, 3, 3, 3).transpose( + 1, 0, 3, 2).reshape(9, 9) print("P_µn =\n{}".format(P_µn)) print("P_gn =\n{}".format(P_gn)) P_comp_gn, P_comp_µn = t2_disp( "P_comp", µP, P, i, j, k, index) print("|P_µn - P_comp_µn| = {}".format( np.linalg.norm(P_µn-P_comp_µn))) print("|P_gn - P_comp_gn| = {}".format( np.linalg.norm(P_gn-P_comp_gn))) print("|P_gn - P_µn| = {}".format( np.linalg.norm(P_gn-P_µn))) print("|P_comp_gn - P_comp_µn| = {}".format( np.linalg.norm(P_comp_gn-P_comp_µn))) print() K_gn.shape = 9, 9 print("K_µn.shape = {}".format(K_µn.shape)) print("K_gn.shape = {}".format(K_gn.shape)) print("K_comp_g =\n{}".format(K_comp_g)) print("K_comp_µ =\n{}".format(K_comp_µ)) print("K_µn=\n{}".format(K_µn)) print("K_gn=\n{}".format(K_gn)) print("|K_µn - K_comp_µ| = {}".format( np.linalg.norm(K_µn-K_comp_µ))) print("|K_gn - K_comp_g| = {}".format( np.linalg.norm(K_gn-K_comp_g))) print("|K_gn - K_µn| = {}".format( np.linalg.norm(K_gn-K_µn))) print("|K_comp_g - K_comp_µ| = {}".format( np.linalg.norm(K_comp_g-K_comp_µ))) break raise AssertionError( "at iiter = {}, inc = {}, caught this: '{}'".format( iiter, inc, err)) - b = -G(P) + b = -G(P) µb = -µG(µP) - err = abs_error_t2(µb, b, strict_tol)#after_cg_tol) - #print("inc, iiter, err: {}".format((inc, iiter, err))) - #print() - + err = abs_error_t2(µb, b, strict_tol) # after_cg_tol) # check for convergence, print convergence info to screen - #print('{0:10.2e}'.format(np.linalg.norm(dFm)/Fn)) - print('Goose: rel_residual {:10.15e}, |rhs|: {:10.15e}'.format( - np.linalg.norm(dFm)/Fn, linalg.norm(b))) - print('µSpectre:rel_residual {:10.15e}, |rhs|: {:10.15e}'.format( - np.linalg.norm(µdFm)/µFn, linalg.norm(µb))) - if np.linalg.norm(dFm)/Fn<1.e-5 and iiter>0: break + print( + 'Goose: rel_residual {:10.15e}, |rhs|: {:10.15e}'.format( + np.linalg.norm(dFm)/Fn, linalg.norm(b))) + print( + 'µSpectre:rel_residual {:10.15e}, |rhs|: {:10.15e}'.format( + np.linalg.norm(µdFm)/µFn, linalg.norm(µb))) + if np.linalg.norm(dFm)/Fn < 1.e-5 and iiter > 0: + break # update Newton iteration counter print("reached end of iiter = {}".format(iiter)) iiter += 1 # end-of-increment: update history - barF_t = np.array(barF,copy=True) + barF_t = np.array(barF, copy=True) µbarF_t[:] = µbarF - F_t = np.array(F ,copy=True) - be_t = np.array(be ,copy=True) - ep_t = np.array(ep ,copy=True) + F_t = np.array(F, copy=True) + be_t = np.array(be, copy=True) + ep_t = np.array(ep, copy=True) µF_t[:] = µF self.rve.save_history_variables() - - if __name__ == '__main__': unittest.main() diff --git a/tests/python_material_evaluator_test.py b/tests/python_material_evaluator_test.py new file mode 100644 index 0000000..e0fef76 --- /dev/null +++ b/tests/python_material_evaluator_test.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_material_evaluator_test.py + +@author Till Junge + +@date 17 Jan 2019 + +@brief tests the python bindings of the material evaluator + +Copyright © 2019 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + + +import unittest +import numpy as np + +from python_test_imports import µ +LinMat = µ.material.MaterialLinearElastic1_2d + +def errfun(a, b): + return np.linalg.norm(a-b)/np.linalg.norm(a+b) + +class MaterialEvaluator_Check(unittest.TestCase): + def test_linear_elasticity(self): + young, poisson = 210e9, .33 + material, evaluator = LinMat.make_evaluator(young, poisson) + material.add_pixel([0,0]) + stress = evaluator.evaluate_stress(np.array([[1., 0],[0, 1]]), + µ.Formulation.finite_strain) + stress=stress.copy() + self.assertEqual(np.linalg.norm(stress), 0) + + stress2, tangent = evaluator.evaluate_stress_tangent( + np.array([[1., .0],[0, 1.0]]), + µ.Formulation.finite_strain) + + tangent = tangent.copy() + + self.assertEqual(np.linalg.norm(stress-stress2), 0) + + num_tangent = evaluator.estimate_tangent( + np.array([[1., .0],[0, 1.0]]), + µ.Formulation.finite_strain, + 1e-6, µ.FiniteDiff.centred) + tol = 1e-8 + err = errfun(num_tangent, tangent) + if not err < tol: + print("tangent:\n{}".format(tangent)) + print("num_tangent:\n{}".format(num_tangent)) + self.assertLess(err, tol) + num_tangent = evaluator.estimate_tangent( + np.array([[1., .0],[0, 1.0]]), + µ.Formulation.finite_strain, + 1e-6) + + numlin_tangent= evaluator.estimate_tangent( + np.array([[1, .0],[0, 1.0]]), + µ.Formulation.small_strain, + 1e-6, µ.FiniteDiff.centred) + + lin_stress, lin_tangent = evaluator.evaluate_stress_tangent( + np.array([[0, .0],[0, .0]]), + µ.Formulation.small_strain) + + + err = errfun(numlin_tangent, lin_tangent) + self.assertLess(err, tol) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/python_material_linear_elastic_generic1_test.py b/tests/python_material_linear_elastic_generic1_test.py new file mode 100644 index 0000000..34aed91 --- /dev/null +++ b/tests/python_material_linear_elastic_generic1_test.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_material_linear_elastic_generic.py + +@author Till Junge + +@date 20 Dec 2018 + +@brief tests the python bindings of the generic linear elastic material + +Copyright © 2018 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + + +import unittest +import numpy as np + +from python_test_imports import µ + +class MaterialLinearElasticGeneric1_Check(unittest.TestCase): + def setUp(self): + self.resolution = [5,7,5] + self.dim = len(self.resolution) + self.lengths = [5.2, 8.3, 2.7] + self.formulation = µ.Formulation.small_strain + self.cell1 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + self.Young = 210e9 + self.Poisson = .33 + self.mat1 = µ.material.MaterialLinearElastic1_3d.make( + self.cell1, "material", self.Young, self.Poisson) + self.matO1 = µ.material.MaterialLinearElastic1_3d.make( + self.cell1, "material", 2* self.Young, self.Poisson) + + E, nu = self.Young, self.Poisson + lam, mu = E*nu/((1+nu)*(1-2*nu)), E/(2*(1+nu)) + + C = np.array([[2 * mu + lam, lam, lam, 0, 0, 0], + [ lam, 2 * mu + lam, lam, 0, 0, 0], + [ lam, lam, 2 * mu + lam, 0, 0, 0], + [ 0, 0, 0, mu, 0, 0], + [ 0, 0, 0, 0, mu, 0], + [ 0, 0, 0, 0, 0, mu]]) + + self.cell2 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + self.mat2 = µ.material.MaterialLinearElasticGeneric1_3d.make( + self.cell2, "material", C) + self.matO2 = µ.material.MaterialLinearElastic1_3d.make( + self.cell2, "material", 2* self.Young, self.Poisson) + + def test_equivalence(self): + sym = lambda x: .5*(x + x.T) + Del0 = sym((np.random.random((self.dim, self.dim))-.5)/10) + for pixel in self.cell1: + if pixel[0] == 0: + self.matO1.add_pixel(pixel) + self.matO2.add_pixel(pixel) + else: + self.mat1.add_pixel(pixel) + self.mat2.add_pixel(pixel) + + tol = 1e-6 + equil_tol = tol + maxiter = 100 + verbose = 0 + + solver1 = µ.solvers.SolverCG(self.cell1, tol, maxiter, verbose) + solver2 = µ.solvers.SolverCG(self.cell2, tol, maxiter, verbose) + + + r1 = µ.solvers.de_geus(self.cell1, Del0, + solver1, tol, equil_tol, verbose) + + + r2 = µ.solvers.de_geus(self.cell2, Del0, + solver2, tol, equil_tol, verbose) + + error = (np.linalg.norm(r1.stress - r2.stress) / + np.linalg.norm(r1.stress + r2.stress)) + + self.assertLess(error, 1e-13) + diff --git a/tests/python_material_linear_elastic_generic2_test.py b/tests/python_material_linear_elastic_generic2_test.py new file mode 100644 index 0000000..b2f8707 --- /dev/null +++ b/tests/python_material_linear_elastic_generic2_test.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_material_linear_elastic_generic2_test.py + +@author Till Junge + +@date 20 Dec 2018 + +@brief tests the bindings for the generic linear law with eigenstrains + +Copyright © 2018 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + + +import unittest +import numpy as np + +from python_test_imports import µ +class MaterialLinearElasticGeneric2_Check(unittest.TestCase): + def setUp(self): + self.resolution = [3, 3]#[5,7] + self.lengths = [3., 3.]#[5.2, 8.3] + self.formulation = µ.Formulation.small_strain + self.cell1 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + self.cell2 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + E, nu = 210e9, .33 + lam, mu = E*nu/((1+nu)*(1-2*nu)), E/(2*(1+nu)) + + C = np.array([[2 * mu + lam, lam, lam, 0, 0, 0], + [ lam, 2 * mu + lam, lam, 0, 0, 0], + [ lam, lam, 2 * mu + lam, 0, 0, 0], + [ 0, 0, 0, mu, 0, 0], + [ 0, 0, 0, 0, mu, 0], + [ 0, 0, 0, 0, 0, mu]]) + + self.mat1 = µ.material.MaterialLinearElasticGeneric1_2d.make( + self.cell1, "simple", C) + self.mat2 = µ.material.MaterialLinearElasticGeneric2_2d.make( + self.cell2, "eigen", C) + self.mat3 = µ.material.MaterialLinearElastic2_2d.make( + self.cell2, "eigen2", 120e9, .33) + + + def test_solve(self): + verbose_test = False + if verbose_test: + print("start test_solve") + grad = np.array([[1.1, .2], + [ .3, 1.5]]) + gl_strain = -0.5*(grad.T.dot(grad) - np.eye(2)) + gl_strain = -0.5*(grad.T + grad - 2*np.eye(2)) + grad = -gl_strain + if verbose_test: + print("grad =\n{}\ngl_strain =\n{}".format(grad, gl_strain)) + for i, pixel in enumerate(self.cell1): + self.mat1.add_pixel(pixel) + self.mat2.add_pixel(pixel, gl_strain) + self.cell1.initialise() + self.cell2.initialise() + tol = 1e-6 + Del0_1 = grad + Del0_2 = np.zeros_like(grad) + maxiter = 2 + verbose = 0 + + def solve(cell, grad): + solver=µ.solvers.SolverCG(cell, tol, maxiter, verbose) + r = µ.solvers.newton_cg(cell, grad, + solver, tol, tol, verbose) + return r + results = [solve(cell, del0) for (cell, del0) + in zip((self.cell1, self.cell2), + (Del0_1, Del0_2))] + P1 = results[0].stress + P2 = results[1].stress + error = np.linalg.norm(P1-P2)/np.linalg.norm(.5*(P1+P2)) + + if verbose_test: + print("cell 1, no eigenstrain") + print("P1:\n{}".format(P1[:,0])) + print("F1:\n{}".format(results[0].grad[:,0])) + + print("cell 2, with eigenstrain") + print("P2:\n{}".format(P2[:,0])) + print("F2:\n{}".format(results[1].grad[:,0])) + print("end test_solve") + self.assertLess(error, tol) + + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/python_material_linear_elastic_generic_test.py b/tests/python_material_linear_elastic_generic_test.py new file mode 100644 index 0000000..7b8754c --- /dev/null +++ b/tests/python_material_linear_elastic_generic_test.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_material_linear_elastic_generic.py + +@author Till Junge + +@date 20 Dec 2018 + +@brief tests the python bindings of the generic linear elastic material + +Copyright © 2018 Till Junge + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Lesser Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + + +import unittest +import numpy as np + +from python_test_imports import µ + +class MaterialLinearElasticGeneric_Check(unittest.TestCase): + def setUp(self): + self.resolution = [5,7,5] + self.dim = len(self.resolution) + self.lengths = [5.2, 8.3, 2.7] + self.formulation = µ.Formulation.small_strain + self.cell1 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + self.Young = 210e9 + self.Poisson = .33 + self.mat1 = µ.material.MaterialLinearElastic1_3d.make( + self.cell1, "material", self.Young, self.Poisson) + self.matO1 = µ.material.MaterialLinearElastic1_3d.make( + self.cell1, "material", 2* self.Young, self.Poisson) + + E, nu = self.Young, self.Poisson + lam, mu = E*nu/((1+nu)*(1-2*nu)), E/(2*(1+nu)) + + C = np.array([[2 * mu + lam, lam, lam, 0, 0, 0], + [ lam, 2 * mu + lam, lam, 0, 0, 0], + [ lam, lam, 2 * mu + lam, 0, 0, 0], + [ 0, 0, 0, mu, 0, 0], + [ 0, 0, 0, 0, mu, 0], + [ 0, 0, 0, 0, 0, mu]]) + + self.cell2 = µ.Cell(self.resolution, + self.lengths, + self.formulation) + self.mat2 = µ.material.MaterialLinearElasticGeneric_3d.make( + self.cell2, "material", C) + self.matO2 = µ.material.MaterialLinearElastic1_3d.make( + self.cell2, "material", 2* self.Young, self.Poisson) + + def test_equivalence(self): + sym = lambda x: .5*(x + x.T) + Del0 = sym((np.random.random((self.dim, self.dim))-.5)/10) + for pixel in self.cell1: + if pixel[0] == 0: + self.matO1.add_pixel(pixel) + self.matO2.add_pixel(pixel) + else: + self.mat1.add_pixel(pixel) + self.mat2.add_pixel(pixel) + + tol = 1e-6 + equil_tol = tol + maxiter = 100 + verbose = 0 + + solver1 = µ.solvers.SolverCG(self.cell1, tol, maxiter, verbose) + solver2 = µ.solvers.SolverCG(self.cell2, tol, maxiter, verbose) + + + r1 = µ.solvers.de_geus(self.cell1, Del0, + solver1, tol, equil_tol, verbose) + + + r2 = µ.solvers.de_geus(self.cell2, Del0, + solver2, tol, equil_tol, verbose) + + error = (np.linalg.norm(r1.stress - r2.stress) / + np.linalg.norm(r1.stress + r2.stress)) + + self.assertLess(error, 1e-13) + diff --git a/tests/python_mpi_material_linear_elastic4_test.py b/tests/python_mpi_material_linear_elastic4_test.py index f9b88cb..e2677b9 100644 --- a/tests/python_mpi_material_linear_elastic4_test.py +++ b/tests/python_mpi_material_linear_elastic4_test.py @@ -1,103 +1,103 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file python_mpi_material_linear_elastic4_test.py @author Richard Leute @date 27 Mar 2018 @brief test MPI-parallel linear elastic material @section LICENSE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ try: from mpi4py import MPI except ImportError: MPI = None import unittest import numpy as np from python_test_imports import µ def build_test_classes(fft): 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, fft=fft, communicator=MPI.COMM_WORLD) 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 - + 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) return MaterialLinearElastic4_Check linear_elastic4 = {} for fft, is_parallel in µ.fft.fft_engines: if is_parallel: linear_elastic4[fft] = build_test_classes(fft) if __name__ == "__main__": unittest.main() diff --git a/tests/python_muSpectre_gradient_integration_test.py b/tests/python_muSpectre_gradient_integration_test.py new file mode 100644 index 0000000..3811fa1 --- /dev/null +++ b/tests/python_muSpectre_gradient_integration_test.py @@ -0,0 +1,661 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_muSpectre_gradient_integration_test.py + +@author Richard Leute + +@date 23 Nov 2018 + +@brief test the functionality of gradient_integration.py + +@section LICENSE + +Copyright © 2018 Till Junge, Richard Leute + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + +import unittest +import numpy as np +import scipy.misc as sm +import itertools +from python_test_imports import µ + +### Helper functions +def init_X_F_Chi(lens, res, rank=2): + """ + Setup all the needed parameters for initialization of the deformation + gradient F and the corresponding deformation map/field Chi_X. + + Keyword Arguments: + lens -- list [Lx, Ly, ...] of box lengths in each direction (dtype=float) + res -- list [Nx, Ny, ...] of grid resoultions (dtype = int) + rank -- int (default=2), rank of the deformation gradient tensor F. + (dtype = int) + + Returns: + d : np.array of grid spacing for each spatial direction (dtype = float) + dim : int dimension of the structure, derived from len(res). + x_n : np.ndarray shape=(res.shape+1, dim) initial nodal/corner positions + as created by gradient_integration.compute_grid (dtype = float) + x_c : np.ndarray shape=(res.shape+1, dim) initial cell center positions + as created by gradient_integration.compute_grid (dtype = float) + F : np.zeros shape=(res.shape, dim*rank) initialise deformation gradient + (dtype = float) + Chi_n: np.zeros shape=((res+1).shape, dim) initialise deformation field + (dtype = float) + Chi_c: np.zeros shape=(res.shape, dim) initialise deformation field + (dtype = float) + freqs: np.ndarray as returned by compute_wave_vectors(). (dtype = float) + """ + lens = np.array(lens) + res = np.array(res) + d = lens / res + dim = len(res) + x_n, x_c = µ.gradient_integration.compute_grid(lens, res) + F = np.zeros(x_c.shape + (dim,)*(rank-1)) + Chi_n = np.zeros(x_n.shape) + Chi_c = np.zeros(x_c.shape) + freqs = µ.gradient_integration.compute_wave_vectors(lens, res) + + return d, dim, x_n, x_c, F, Chi_n, Chi_c, freqs + +def correct_to_zero_mean(Chi, d, nodal=False): + """ + corrects the displacement field such that it's integral is zero. By this one + can get rid of a constant factor in the deformation gradient. This function + is specialized for this file and should not be used somewhere else. + + Keywords: + Chi : np.ndarray of the uncorrected analytic placements (dtype = float) + d : np.array of the gridspacing in each spatial direction (dtype = float) + nodal : bool (default False) specifies if the input are nodal or cell/center + values. Default interpretation are cell/center values. + + Returns: + Chi : np.ndarray of zero mean corrected analytic placements (dtype = float) + """ + Chi_zm = np.copy(Chi) + res = np.array(Chi_zm.shape[:-1]) + dim = res.size + Chi_zm -= (Chi_zm.sum(axis=tuple(range(dim)))/np.prod(res))\ + .reshape((1,)*dim + (dim,)) + return Chi_zm + +def test_integrate(order, F, Chi_n, Chi_c, tol): + """ + make the convergence tests for the integration + + Keywords: + order : list of integration orders which are tested (dtype = int) + F : np.ndarray applied deformation gradient (dtype = float) + Chi_n : np.ndarray expected node positions (dtype = float) + Chi_c : np.ndarray expected cell positions (dtype = float) + tol : list of tolerances for each order. If it is a single value the same + tolerance is used for each order. (dtype = float) + """ + print('Maybe implement a function like this...') + +def central_diff_derivative(data, d, order, rank=1): + """ + Compute the first derivative of a function with values 'data' with the + central difference approximation to the order 'order'. The function values + are on a rectangualar grid with constant grid spacing 'd' in each direction. + + CAUTION: + The function is assumed to be periodic (pbc)! + Thus, if there is a discontinuity at the boundaries you have to expect + errors in the derivative at the vicinity close to the discontinuity. + + Keyword Arguments: + data -- np.ndarray of shape=(resolution, dim*rank) function values on an + equally spaced grid, with grid spacing 'd' (dtype = float) + d -- scalar or np.array of grid spacing in each direction. Scalar is + interpreted as equal spacing in each direction (dtype = float) + order -- int >= 1, gives the accuracy order of the central difference + approximation (dtype = int) + rank -- int, rank of the data tensor + + Returns: + deriv: np.ndarray of shape=(resolution, dim, dim) central difference + derivative of given order (dtype = float) + """ + dim = len(data.shape)-rank + weights = sm.central_diff_weights(2*order + 1) + deriv = np.zeros(data.shape + (dim,)) + for ax in range(dim): + for i in range(2*order + 1): + deriv[...,ax] += weights[i]*np.roll(data, order-i, axis=ax) / d[ax] + + return deriv + + +class MuSpectre_gradient_integration_Check(unittest.TestCase): + """ + Check the implementation of all muSpectre.gradient_integration functions. + """ + + def setUp(self): + self.lengths = np.array([2.4, 3.7, 4.1]) + self.resolution = np.array([5, 3, 5]) + + self.norm_tol = 1e-8 + + def test_central_diff_derivative(self): + """ + Test of the central difference approximation by central_diff_derivative + of the first derivative of a function on a grid. + """ + res = self.resolution * 15 + lens = self.lengths + for j in range(1, len(res)): + d, dim, x_n, x_c, deriv, f_n, f_c, freqs = init_X_F_Chi(lens[:j], + res[:j]) + f_c = np.sin(2*np.pi/lens[:j] * x_c) + for i in range(j): + deriv[...,i,i] =2*np.pi/lens[i]*np.cos(2*np.pi* + x_c[...,i]/lens[i]) + approx_deriv = central_diff_derivative(f_c, d[:j+1], order=5) + self.assertLess(np.linalg.norm(deriv-approx_deriv), + self.norm_tol) + + def test_compute_wave_vectors(self): + """ + Test the construction of a wave vector grid by compute_wave_vectors + for an arbitrary dimension. + """ + lens = [4, 6, 7] + res = [3, 4, 5] + Nx, Ny, Nz = res + q_1d = lambda i: 2*np.pi/lens[i] * \ + np.append(np.arange(res[i]-res[i]//2), + -np.arange(1, res[i]//2 + 1)[::-1]) + qx = q_1d(0) + qy = q_1d(1) + qz = q_1d(2) + q = np.zeros(tuple(res) + (3,)) + for i,j,k in itertools.product(range(Nx), range(Ny), range(Nz)): + q[i,j,k,:] = np.array([qx[i], qy[j], qz[k]]) + for n in range(1,4): + comp_q = µ.gradient_integration.compute_wave_vectors(lens[:n], + res[:n]) + s = (np.s_[:],)*n + (0,)*(3-n) + (np.s_[:n],) + self.assertLess(np.linalg.norm(comp_q - q[s]), self.norm_tol) + + def test_compute_grid(self): + """ + Test the function compute_grid which creates an orthogonal + equally spaced grid of the given resolution and lengths. + """ + lens = self.lengths + res = self.resolution + d = np.array(lens)/np.array(res) + grid_n = np.zeros(tuple(res+1) + (len(res),)) + Nx, Ny, Nz = res+1 + for i,j,k in itertools.product(range(Nx), range(Ny), range(Nz)): + grid_n[i,j,k,:] = np.array([i*d[0], j*d[1], k*d[2]]) + grid_c = (grid_n - d/2)[1:,1:,1:,:] + for n in range(1,4): + x_n, x_c = µ.gradient_integration.compute_grid(lens[:n], res[:n]) + s = (np.s_[:],)*n + (0,)*(3-n) + (np.s_[:n],) + self.assertLess(np.linalg.norm(x_c - grid_c[s]), self.norm_tol) + self.assertLess(np.linalg.norm(x_n - grid_n[s]), self.norm_tol) + + def test_reshape_gradient(self): + """ + Test if reshape gradient transforms a flattend second order tensor in + the right way to a shape resolution + [dim, dim]. + """ + lens = list(self.lengths) + res = list(self.resolution) + tol = 1e-5 + formulation = µ.Formulation.finite_strain + DelF = np.array([[0 , 0.01, 0.02], + [0.03, 0 , 0.04], + [0.05, 0.06, 0 ]]) + one = np.eye(3,3) + for n in range(2,4): + sys = µ.Cell(res[:n], lens[:n], formulation) + if n == 2: + mat = µ.material.MaterialLinearElastic1_2d.make(sys, "material", + 10, 0.3) + if n == 3: + mat = µ.material.MaterialLinearElastic1_3d.make(sys, "material", + 10, 0.3) + for pixel in sys: + mat.add_pixel(pixel) + solver = µ.solvers.SolverCG(sys, tol, maxiter=100, verbose=0) + r = µ.solvers.newton_cg(sys, DelF[:n, :n], + solver, tol, tol , verbose=0) + grad = µ.gradient_integration.reshape_gradient(r.grad,list(res[:n])) + grad_theo = (DelF[:n, :n] + one[:n, :n]).reshape((1,)*n+(n,n,)) + self.assertEqual(grad.shape, tuple(res[:n])+(n,n,)) + self.assertLess(np.linalg.norm(grad - grad_theo), self.norm_tol) + + def test_complement_periodically(self): + """ + Test the periodic reconstruction of an array. Lower left entries are + added into the upper right part of the array. + """ + #1D grid scalars + x_test = np.array([0,1,2,3]) + x_test_p = np.array([0,1,2,3, 0]) + x_p = µ.gradient_integration.complement_periodically(x_test, 1) + self.assertLess(np.linalg.norm(x_p-x_test_p), self.norm_tol) + + #2D grid scalars + x_test = np.array([[1,2,3,4], + [5,6,7,8]]) + x_test_p = np.array([[1,2,3,4,1], + [5,6,7,8,5], + [1,2,3,4,1]]) + x_p = µ.gradient_integration.complement_periodically(x_test, 2) + self.assertLess(np.linalg.norm(x_p-x_test_p), self.norm_tol) + + #2D grid vectors + x_test = np.array([[[1,2,3] , [3,4,5]] , + [[6,7,8] , [9,10,11]], + [[12,13,14], [15,6,17]] ]) + x_test_p = np.array([[[1,2,3] , [3,4,5] , [1,2,3]] , + [[6,7,8] , [9,10,11], [6,7,8]] , + [[12,13,14], [15,6,17], [12,13,14]], + [[1,2,3] , [3,4,5] , [1,2,3]] ]) + x_p = µ.gradient_integration.complement_periodically(x_test, 2) + self.assertLess(np.linalg.norm(x_p-x_test_p), self.norm_tol) + + def test_get_integrator(self): + """ + Test if the right integrator is computed. + """ + #even grid + lens_e = np.array([1,1,1]) + res_e = np.array([2,2,2]) + x_n_e, x_c_e = µ.gradient_integration.compute_grid(lens_e, res_e) + freqs_e = µ.gradient_integration.compute_wave_vectors(lens_e, res_e) + #odd grid + lens_o = np.array([1,1]) + res_o = np.array([3,3]) + x_n_o, x_c_o = µ.gradient_integration.compute_grid(lens_o, res_o) + delta_x = 1/3 + freqs_o = µ.gradient_integration.compute_wave_vectors(lens_o, res_o) + + ### order=0 + int_ana = 1j/(2*np.pi)*np.array([[[[ 0 , 0 , 0], [ 0 , 0 ,-1 ]] , + [[ 0 ,-1 , 0], [ 0 ,-1/2,-1/2]]], + [[[-1 , 0 , 0], [-1/2, 0 ,-1/2]] , + [[-1/2,-1/2, 0], [-1/3,-1/3,-1/3]]] ]) + dim,shape,integrator = µ.gradient_integration.\ + get_integrator(x_c_e, freqs_e, order=0) + self.assertEqual(dim, len(res_e)) + self.assertEqual(shape, tuple(res_e)) + self.assertLess(np.linalg.norm(integrator-int_ana), self.norm_tol) + + ### order=1 + #even grid + int_ana = np.zeros(res_e.shape) + dim,shape,integrator = µ.gradient_integration.\ + get_integrator(x_c_e, freqs_e, order=1) + self.assertEqual(dim, len(res_e)) + self.assertEqual(shape, tuple(res_e)) + self.assertLess(np.linalg.norm(integrator-int_ana), self.norm_tol) + + #odd grid + s = lambda q: np.sin(2*np.pi*q*delta_x) + sq = lambda q: (np.sin(2*np.pi*np.array(q)*delta_x)**2).sum() + int_ana = 1j * delta_x *\ + np.array([[[ 0 , 0 ], + [ 0 , s(1)/sq([0,1]) ], + [ 0 , s(-1)/sq([0,-1]) ]], + [[ s(1)/sq([1,0]) , 0 ], + [ s(1)/sq([1,1]) , s(1)/sq([1,1]) ], + [ s(1)/sq([1,-1]) , s(-1)/sq([1,-1]) ]], + [[ s(-1)/sq([-1,0]) , 0 ], + [ s(-1)/sq([-1,1]) , s(1)/sq([-1,1]) ], + [ s(-1)/sq([-1,-1]) , s(-1)/sq([-1,-1]) ]]]) + + dim,shape,integrator = µ.gradient_integration.\ + get_integrator(x_c_o, freqs_o, order=1) + self.assertEqual(dim, len(res_o)) + self.assertEqual(shape, tuple(res_o)) + self.assertLess(np.linalg.norm(integrator-int_ana), self.norm_tol) + + ### order=2 + #even grid + int_ana = np.zeros(res_e.shape) + dim,shape,integrator = µ.gradient_integration.\ + get_integrator(x_c_e, freqs_e, order=2) + self.assertEqual(dim, len(res_e)) + self.assertEqual(shape, tuple(res_e)) + self.assertLess(np.linalg.norm(integrator-int_ana), self.norm_tol) + + #odd grid + lens_o = np.array([1,1]) + res_o = np.array([3,3]) + x_n, x_c = µ.gradient_integration.compute_grid(lens_o, res_o) + delta_x = 1/3 + freqs = µ.gradient_integration.compute_wave_vectors(lens_o, res_o) + s = lambda q: 8*np.sin(2*np.pi*q*delta_x) + np.sin(2*2*np.pi*q*delta_x) + sq = lambda q: ( (64*np.sin(2*np.pi*np.array(q)*delta_x)**2).sum() - + (np.sin(2*2*np.pi*np.array(q)*delta_x)**2).sum() ) + int_ana = 6 * 1j * delta_x *\ + np.array([[[ 0 , 0 ], + [ 0 , s(1)/sq([0,1]) ], + [ 0 , s(-1)/sq([0,-1]) ]], + [[ s(1)/sq([1,0]) , 0 ], + [ s(1)/sq([1,1]) , s(1)/sq([1,1]) ], + [ s(1)/sq([1,-1]) , s(-1)/sq([1,-1]) ]], + [[ s(-1)/sq([-1,0]) , 0 ], + [ s(-1)/sq([-1,1]) , s(1)/sq([-1,1]) ], + [ s(-1)/sq([-1,-1]) , s(-1)/sq([-1,-1]) ]]]) + + dim,shape,integrator = µ.gradient_integration.\ + get_integrator(x_c_o, freqs_o, order=2) + self.assertEqual(dim, len(res_o)) + self.assertEqual(shape, tuple(res_o)) + self.assertLess(np.linalg.norm(integrator-int_ana), self.norm_tol) + + def test_integrate_tensor_2(self): + """ + Test the correct integration of a second-rank tensor gradient field, + like the deformation gradient. + """ + order = [1, 2] #list of higher order finite difference integration which + #will be checked. + + ### cosinus, diagonal deformation gradient + res = [15, 15, 14] + lens = [7, 1.4, 3] + d, dim, x_n, x_c, F, Chi_n, Chi_c, freqs = init_X_F_Chi(lens, res) + for i in range(dim): + F[:,:,:,i,i] = 0.8*np.pi/lens[i]*np.cos(4*np.pi* + x_c[:,:,:,i]/lens[i]) + Chi_n = 0.2 * np.sin(4*np.pi*x_n/lens) + Chi_c = 0.2 * np.sin(4*np.pi*x_c/lens) + # zeroth order correction + placement_n = µ.gradient_integration.integrate_tensor_2(F, x_n, freqs, + staggered_grid=True, order=0) + placement_c = µ.gradient_integration.integrate_tensor_2(F, x_c, freqs, + staggered_grid=False, order=0) + self.assertLess(np.linalg.norm(Chi_n - placement_n), self.norm_tol) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + # higher order correction + for n in order: + tol_n = [1.334, 0.2299] #adjusted tolerances for node points + F_c = central_diff_derivative(Chi_c, d, order=n) + placement_n = µ.gradient_integration.integrate_tensor_2(F_c, x_n, + freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_tensor_2(F_c, x_c, + freqs, staggered_grid=False,order=n) + self.assertLess(np.linalg.norm(Chi_n - placement_n), tol_n[n-1]) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + + ### cosinus, non-diagonal deformation gradient + res = [15, 12, 11] + lens = [8, 8, 8] + d, dim, x_n, x_c, F, Chi_n, Chi_c, freqs = init_X_F_Chi(lens, res) + F[:,:,:,0,0] = 4*np.pi/lens[0]*np.cos(2*np.pi/lens[0]*x_c[:,:,:,0]) + F[:,:,:,1,1] = 2*np.pi/lens[1]*np.cos(2*np.pi/lens[1]*x_c[:,:,:,1]) + F[:,:,:,2,2] = 2*np.pi/lens[2]*np.cos(2*np.pi/lens[2]*x_c[:,:,:,2]) + F[:,:,:,1,0] = 2*np.pi/lens[0]*np.cos(2*np.pi/lens[0]*x_c[:,:,:,0]) + F[:,:,:,2,0] = 2*np.pi/lens[0]*np.cos(2*np.pi/lens[0]*x_c[:,:,:,0]) + for i in range(dim): + Chi_c[:,:,:,i]= np.sin(2*np.pi*x_c[:,:,:,i]/lens[i]) \ + + np.sin(2*np.pi*x_c[:,:,:,0]/lens[0]) + Chi_n[:,:,:,i]= np.sin(2*np.pi*x_n[:,:,:,i]/lens[i]) \ + + np.sin(2*np.pi*x_n[:,:,:,0]/lens[0]) + # zeroth order correction + placement_n = µ.gradient_integration.integrate_tensor_2(F, x_n, freqs, + staggered_grid=True, order=0) + placement_c = µ.gradient_integration.integrate_tensor_2(F, x_c, freqs, + staggered_grid=False, order=0) + self.assertLess(np.linalg.norm(Chi_n - placement_n), self.norm_tol) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + # higher order correction + for n in order: + tol_n = [2.563, 0.1544] #adjusted tolerances for node points + F_c = central_diff_derivative(Chi_c, d, order=n) + placement_n = µ.gradient_integration.integrate_tensor_2(F_c, x_n, + freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_tensor_2(F_c, x_c, + freqs, staggered_grid=False,order=n) + self.assertLess(np.linalg.norm(Chi_n - placement_n), tol_n[n-1]) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + + ### polynomial, diagonal deformation gradient + # Choose the prefactors of the polynomial such that at least Chi_X and F + # have respectively the same values at the boundaries (here X_i=0 and + # X_i=4). + res = [13, 14, 11] + lens = [4, 4, 4] + d, dim, x_n, x_c, F, Chi_n, Chi_c, freqs = init_X_F_Chi(lens, res) + for i in range(dim): + F[:,:,:,i,i] = 32*x_c[:,:,:,i] -24*x_c[:,:,:,i]**2+4*x_c[:,:,:,i]**3 + Chi_n = -128/15 + 16*x_n**2 -8*x_n**3 +x_n**4 + Chi_c = -128/15 + 16*x_c**2 -8*x_c**3 +x_c**4 + #subtract the mean of Chi_c, because the numeric integration is done to + #give a zero mean fluctuating deformation field. + mean_c = Chi_c.sum(axis=tuple(range(dim)))/ \ + np.array(Chi_c.shape[:-1]).prod() + Chi_n -= mean_c.reshape((1,)*dim + (dim,)) + Chi_c -= mean_c.reshape((1,)*dim + (dim,)) + # zeroth order correction + placement_n = µ.gradient_integration.integrate_tensor_2(F, x_n, freqs, + staggered_grid=True, order=0) + placement_c = µ.gradient_integration.integrate_tensor_2(F, x_c, freqs, + staggered_grid=False, order=0) + self.assertLess(np.linalg.norm(Chi_n - placement_n), 0.19477) + self.assertLess(np.linalg.norm(Chi_c - placement_c), 0.67355) + # higher order correction + for n in order: + tol_n = [18.266, 2.9073] #adjusted tolerances for node points + F_c = central_diff_derivative(Chi_c, d, order=n) + placement_n = µ.gradient_integration.integrate_tensor_2(F_c, x_n, + freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_tensor_2(F_c, x_c, + freqs, staggered_grid=False,order=n) + self.assertLess(np.linalg.norm(Chi_n - placement_n), tol_n[n-1]) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + + ### Realistic test: + # shear of a two dimensional material with two different Young moduli. + order_all = [0]+order #orders for which the test is run + #initialize material structure + res = [ 9, 21] #resolution + lens = [ 9, 21] #lengths + d, dim, x_n, x_c, _, _, _, freqs = init_X_F_Chi(lens, res) + formulation = µ.Formulation.finite_strain + Young = [10, 20] #Youngs modulus for each phase (soft, hard) + Poisson = [0.3, 0.3] #Poissons ratio for each phase + + #geometry (two slabs stacked in y-direction with, + #hight h (soft material) and hight res[1]-h (hard material)) + h = res[1]//2 + phase = np.zeros(tuple(res), dtype=int) + phase[:, h:] = 1 + phase = phase.flatten() + cell = µ.Cell(res, lens, formulation) + mat = µ.material.MaterialLinearElastic4_2d.make(cell, "material") + for i, pixel in enumerate(cell): + mat.add_pixel(pixel, Young[phase[i]], Poisson[phase[i]]) + cell.initialise() + DelF = np.array([[0 , 0.01], + [0 , 0 ]]) + + # µSpectre solution + solver = µ.solvers.SolverCG(cell, tol=1e-6, maxiter=100, verbose=0) + result = µ.solvers.newton_cg(cell, DelF, solver, newton_tol=1e-6, + equil_tol=1e-6, verbose=0) + F = µ.gradient_integration.reshape_gradient(result.grad, res) + fin_pos = {} #µSpectre computed center and node positions for all orders + for n in order_all: + placement_n = µ.gradient_integration.integrate_tensor_2(F, x_n, + freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_tensor_2(F, x_c, + freqs, staggered_grid=False, order=n) + fin_pos[str(n)+'_n'] = placement_n + fin_pos[str(n)+'_c'] = placement_c + + # analytic solution, "placement_ana" (node and center) + l_soft = d[1] * h #height soft material + l_hard = d[1] * (res[1]-h) #height hard material + Shear_modulus = np.array(Young) / (2 * (1+np.array(Poisson))) + mean_shear_strain = 2*DelF[0,1] + shear_strain_soft = (lens[1]*mean_shear_strain) / (l_soft + + l_hard * Shear_modulus[0]/Shear_modulus[1]) + shear_strain_hard = (lens[1]*mean_shear_strain) / (l_soft + * Shear_modulus[1]/Shear_modulus[0] + l_hard) + placement_ana_n = np.zeros(x_n.shape) + placement_ana_c = np.zeros(x_c.shape) + + #x-coordinate + #soft material + placement_ana_n[:,:h+1,0] = shear_strain_soft/2 * x_n[:, :h+1, 1] + placement_ana_c[:,:h ,0] = shear_strain_soft/2 * x_c[:, :h , 1] + #hard material + placement_ana_n[:,h+1:,0] =shear_strain_hard/2 * (x_n[:,h+1:,1]-l_soft)\ + + shear_strain_soft/2 * l_soft + placement_ana_c[:,h: ,0] =shear_strain_hard/2 * (x_c[:,h: ,1]-l_soft)\ + + shear_strain_soft/2 * l_soft + #y-coordinate + placement_ana_n[:, :, 1] = 0 + placement_ana_c[:, :, 1] = 0 + + #shift the analytic solution such that the average nonaffine deformation + #is zero (integral of the nonaffine deformation gradient + N*const != 0) + F_homo = (1./(np.prod(res)) * F.sum(axis=tuple(np.arange(dim))))\ + .reshape((1,)*dim+(dim,)*2) + #integration constant = integral of the nonaffine deformation gradient/N + int_const = - ((placement_ana_c[:,:,0] - F_homo[:,:,0,1] * x_c[:,:,1]) + .sum(axis=1))[0] / res[1] + ana_sol_n = placement_ana_n + x_n + \ + np.array([int_const, 0]).reshape((1,)*dim+(dim,)) + ana_sol_c = placement_ana_c + x_c + \ + np.array([int_const, 0]).reshape((1,)*dim+(dim,)) + + # check the numeric vs the analytic solution + tol_n = [2.2112e-3, 1.3488e-3, 1.8124e-3] + tol_c = [3.1095e-3, 3.2132e-2, 1.8989e-2] + for n in order_all: + norm_n = np.linalg.norm(fin_pos[str(n)+'_n'] - ana_sol_n) + norm_c = np.linalg.norm(fin_pos[str(n)+'_c'] - ana_sol_c) + self.assertLess(norm_n, tol_n[n]) + self.assertLess(norm_c, tol_c[n]) + + + def test_integrate_vector(self): + """Test the integration of a first-rank tensor gradient field.""" + order = [1,2] + + ### cosinus deformation gradient vector field + res = [13, 14, 13] + lens = [ 7, 4, 5] + d, dim, x_n, x_c, df, Chi_n, Chi_c, freqs = init_X_F_Chi(lens, res, 1) + for i in range(dim): + df[:,:,:,i] = 0.8*np.pi/lens[i]*np.cos(4*np.pi*x_c[:,:,:,i]/lens[i]) + Chi_n = 0.2 * np.sin(4*np.pi*x_n/lens).sum(axis=-1) + Chi_c = 0.2 * np.sin(4*np.pi*x_c/lens).sum(axis=-1) + # zeroth order correction + placement_n = µ.gradient_integration.integrate_vector( + df, x_n, freqs, staggered_grid=True, order=0) + placement_c = µ.gradient_integration.integrate_vector( + df, x_c, freqs, staggered_grid=False, order=0) + self.assertLess(np.linalg.norm(Chi_n - placement_n), self.norm_tol) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + # higher order correction + for n in order: + tol_n = [1.404, 0.2882] #adjusted tolerances for node points + df_c = central_diff_derivative(Chi_c, d, order=n, rank=0) + placement_n = µ.gradient_integration.integrate_vector( + df_c, x_n, freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_vector( + df_c, x_c, freqs, staggered_grid=False, order=n) + self.assertLess(np.linalg.norm(Chi_n - placement_n), tol_n[n-1]) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + + ### polynomial deformation gradient vector field + # Choose the prefactors of the polynomial such that at least Chi_X and F + # have respectively the same values at the boundaries (here X_i=0 and + # X_i=4). + res = [12, 11, 13] + lens = [4, 4, 4] + d, dim, x_n, x_c, df, Chi_n, Chi_c, freqs = init_X_F_Chi(lens, res, 1) + for i in range(dim): + df[:,:,:,i] = 32*x_c[:,:,:,i]-24*x_c[:,:,:,i]**2+4*x_c[:,:,:,i]**3 + Chi_n = (-128/15 + 16*x_n**2 -8*x_n**3 +x_n**4).sum(axis=-1) + Chi_c = (-128/15 + 16*x_c**2 -8*x_c**3 +x_c**4).sum(axis=-1) + #subtract the mean of Chi_c, because the numeric integration is done to + #give a zero mean fluctuating deformation field. + mean_c = Chi_c.sum() / np.array(Chi_c.shape).prod() + Chi_n -= mean_c + Chi_c -= mean_c + # zeroth order correction + placement_n = µ.gradient_integration.integrate_vector( + df, x_n, freqs, staggered_grid=True, order=0) + placement_c = µ.gradient_integration.integrate_vector( + df, x_c, freqs, staggered_grid=False, order=0) + self.assertLess(np.linalg.norm(Chi_n - placement_n), 0.20539) + self.assertLess(np.linalg.norm(Chi_c - placement_c), 0.67380) + # higher order correction + for n in order: + tol_n = [18.815, 3.14153] #adjusted tolerances for node points + df_c = central_diff_derivative(Chi_c, d, order=n, rank=0) + placement_n = µ.gradient_integration.integrate_vector( + df_c, x_n, freqs, staggered_grid=True, order=n) + placement_c = µ.gradient_integration.integrate_vector( + df_c, x_c, freqs, staggered_grid=False, order=n) + self.assertLess(np.linalg.norm(Chi_n - placement_n), tol_n[n-1]) + self.assertLess(np.linalg.norm(Chi_c - placement_c), self.norm_tol) + + + def test_compute_placement(self): + """Test the computation of placements and the original positions.""" + ### shear of a homogeneous material ### + res = [ 3, 11] #resolution + lens = [10, 10] #lengths + dim = len(res) #dimension + x_n=µ.gradient_integration.compute_grid(np.array(lens),np.array(res))[0] + + ### finite strain + formulation = µ.Formulation.finite_strain + cell = µ.Cell(res, lens, formulation) + mat = µ.material.MaterialLinearElastic1_2d.make(cell, "material", + Young=10, Poisson=0.3) + for pixel in cell: + mat.add_pixel(pixel) + cell.initialise() + DelF = np.array([[0 , 0.05], + [0 , 0 ]]) + # analytic + placement_ana = np.copy(x_n) + placement_ana[:,:,0] += DelF[0,1]*x_n[:,:,1] + # µSpectre solution + solver = µ.solvers.SolverCG(cell, tol=1e-6, maxiter=100, verbose=0) + result = µ.solvers.newton_cg(cell, DelF, solver, newton_tol=1e-6, + equil_tol=1e-6, verbose=0) + for r in [result, result.grad]: + #check input of result=OptimiseResult and result=np.ndarray + placement, x = µ.gradient_integration.compute_placement( + r, lens, res, order=0, formulation=µ.Formulation.finite_strain) + self.assertLess(np.linalg.norm(placement_ana - placement), 1e-12) + self.assertTrue((x_n == x).all()) diff --git a/tests/python_muSpectre_vtk_export_test.py b/tests/python_muSpectre_vtk_export_test.py new file mode 100644 index 0000000..b4e8206 --- /dev/null +++ b/tests/python_muSpectre_vtk_export_test.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +""" +@file python_muSpectre_vtk_export_test.py + +@author Richard Leute + +@date 10 Jan 2019 + +@brief test the functionality of vtk_export.py + +@section LICENSE + +Copyright © 2019 Till Junge, Richard Leute + +µSpectre is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as +published by the Free Software Foundation, either version 3, or (at +your option) any later version. + +µSpectre is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with µSpectre; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Additional permission under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or combining it +with proprietary FFT implementations or numerical libraries, containing parts +covered by the terms of those libraries' licenses, the licensors of this +Program grant you additional permission to convey the resulting work. +""" + +import unittest +import numpy as np +import tempfile +import os +from python_test_imports import µ + +class MuSpectre_vtk_export_Check(unittest.TestCase): + def setUp(self): + self.lengths = np.array([1.1, 2.2, 3]) + self.resolution = np.array([3, 5, 7]) + def test_vtk_export(self): + """ + Check the possibility to write scalar-, vector- and second rank tensor- + fields on the cell and node grid. The throw of exceptions is not checked + """ + grad = np.array([[0, 0.01, 0], + [0, 0, 0], + [0, 0, 0]]) + for dim in [2,3]: + #test if files are written for 2D and 3D + lens = self.lengths[:dim] + res = self.resolution[:dim] + F = grad[:dim, :dim].reshape((1,)*dim + (dim,)*2) + x_n, x_c = µ.gradient_integration.compute_grid(lens, res) + freqs = µ.gradient_integration.compute_wave_vectors(lens, res) + placement_n = µ.gradient_integration.integrate_tensor_2(F, x_n, + freqs, staggered_grid=True, order=0) + p_d = {'scalar' : np.random.random(x_n.shape[:-1]), + 'vector' : np.random.random(x_n.shape[:-1] + (dim,)), + '2-tensor': np.random.random(x_n.shape[:-1] + (dim,)*2)} + c_d = {'scalar' : np.random.random(x_c.shape[:-1]), + 'vector' : np.random.random(x_c.shape[:-1] + (dim,)), + '2-tensor': np.random.random(x_c.shape[:-1] + (dim,)*2)} + #The temporary directory is atomatically cleand up after one is + #exiting the block. + with tempfile.TemporaryDirectory(dir=os.getcwd()) as dir_name: + os.chdir(dir_name) + file_name = 'vtk_export_'+str(dim)+'D_test' + µ.vtk_export.vtk_export(file_name, x_n, placement_n, + point_data = p_d, cell_data = c_d) + assert os.path.exists(file_name+'.vtr') == 1,\ + "vtk_export() was not able to write the {}D output file "\ + "'{}.vtr'.".format(dim, file_name) + os.chdir('../') diff --git a/tests/python_test_imports.py b/tests/python_test_imports.py index 57f4351..be9192b 100644 --- a/tests/python_test_imports.py +++ b/tests/python_test_imports.py @@ -1,52 +1,53 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ file python_test_imports.py @author Till Junge @date 18 Jan 2018 @brief prepares sys.path to load muSpectre @section LICENSE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import sys import os # Default path of the library sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python")) # Path of the library when compiling with Xcode sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python/Debug")) try: import muSpectre as µ + import muSpectre except ImportError as err: print(err) sys.exit(-1) diff --git a/tests/test_cell_base.cc b/tests/test_cell_base.cc index 2ec9bf2..abde920 100644 --- a/tests/test_cell_base.cc +++ b/tests/test_cell_base.cc @@ -1,322 +1,325 @@ /** * @file test_cell_base.cc * * @author Till Junge * * @date 14 Dec 2017 * * @brief Tests for the basic cell class * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include "tests.hh" #include "common/common.hh" #include "common/iterators.hh" #include "common/field_map.hh" #include "tests/test_goodies.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(cell_base); - template struct Sizes {}; - template <> struct Sizes { + 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 { + template <> + struct Sizes { constexpr static Dim_t sdim{threeD}; constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8, 6.7}; } }; template struct CellBaseFixture : CellBase { constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static Formulation formulation{form}; CellBaseFixture() : CellBase{std::move( cell_input(Sizes::get_resolution(), Sizes::get_lengths(), form))} {} }; using fixlist = boost::mpl::list< CellBaseFixture, CellBaseFixture, CellBaseFixture, CellBaseFixture>; BOOST_AUTO_TEST_CASE(manual_construction) { constexpr Dim_t dim{twoD}; Ccoord_t resolutions{3, 3}; Rcoord_t lengths{2.3, 2.7}; Formulation form{Formulation::finite_strain}; auto fft_ptr{std::make_unique>(resolutions, dim * dim)}; auto proj_ptr{std::make_unique>( std::move(fft_ptr), lengths)}; CellBase sys{std::move(proj_ptr)}; auto sys2{make_cell(resolutions, lengths, form)}; auto sys2b{std::move(sys2)}; BOOST_CHECK_EQUAL(sys2b.size(), sys.size()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { BOOST_CHECK_THROW(fix::check_material_coverage(), std::runtime_error); BOOST_CHECK_THROW(fix::initialise(), std::runtime_error); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(add_material_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Material_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); BOOST_CHECK_NO_THROW(fix::add_material(std::move(Material_hard))); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(simple_evaluation_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; constexpr Formulation form{fix::formulation}; using Mat_t = MaterialLinearElastic1; const Real Young{210e9}, Poisson{.33}; const Real lambda{Young * Poisson / ((1 + Poisson) * (1 - 2 * Poisson))}; const Real mu{Young / (2 * (1 + Poisson))}; auto Material_hard = std::make_unique("hard", Young, Poisson); for (auto && pixel : *this) { Material_hard->add_pixel(pixel); } fix::add_material(std::move(Material_hard)); auto & F = fix::get_strain(); auto F_map = F.get_map(); // finite strain formulation expects the deformation gradient F, // while small strain expects infinitesimal strain ε for (auto grad : F_map) { switch (form) { case Formulation::finite_strain: { grad = grad.Identity(); break; } case Formulation::small_strain: { grad = grad.Zero(); break; } default: BOOST_CHECK(false); break; } } auto res_tup{fix::evaluate_stress_tangent(F)}; auto stress{std::get<0>(res_tup).get_map()}; auto tangent{std::get<1>(res_tup).get_map()}; auto tup = testGoodies::objective_hooke_explicit(lambda, mu, Matrices::I2()); auto P_ref = std::get<0>(tup); for (auto mat : stress) { Real norm = (mat - P_ref).norm(); BOOST_CHECK_EQUAL(norm, 0.); } auto tan_ref = std::get<1>(tup); for (const auto tan : tangent) { Real norm = (tan - tan_ref).norm(); BOOST_CHECK_EQUAL(norm, 0.); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(evaluation_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Mat_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); auto Material_soft = std::make_unique("soft", 70e9, .3); for (auto && cnt_pixel : akantu::enumerate(*this)) { auto counter = std::get<0>(cnt_pixel); auto && pixel = std::get<1>(cnt_pixel); if (counter < 5) { Material_hard->add_pixel(pixel); } else { Material_soft->add_pixel(pixel); } } fix::add_material(std::move(Material_hard)); fix::add_material(std::move(Material_soft)); auto & F = fix::get_strain(); fix::evaluate_stress_tangent(F); fix::evaluate_stress_tangent(F); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(evaluation_test_new_interface, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Mat_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); auto Material_soft = std::make_unique("soft", 70e9, .3); for (auto && cnt_pixel : akantu::enumerate(*this)) { auto counter = std::get<0>(cnt_pixel); auto && pixel = std::get<1>(cnt_pixel); if (counter < 5) { Material_hard->add_pixel(pixel); } else { Material_soft->add_pixel(pixel); } } fix::add_material(std::move(Material_hard)); fix::add_material(std::move(Material_soft)); auto F_vec = fix::get_strain_vector(); F_vec.setZero(); fix::evaluate_stress_tangent(); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_managed_fields, Fix, fixlist, Fix) { Cell & dyn_handle{*this}; CellBase & base_handle{*this}; const std::string name1{"aaa"}; constexpr size_t nb_comp{5}; auto new_dyn_array{dyn_handle.get_managed_real_array(name1, nb_comp)}; BOOST_CHECK_EQUAL(new_dyn_array.rows(), nb_comp); BOOST_CHECK_EQUAL(new_dyn_array.cols(), dyn_handle.size()); BOOST_CHECK_THROW(dyn_handle.get_managed_real_array(name1, nb_comp + 1), std::runtime_error); auto & new_field{base_handle.get_managed_real_field(name1, nb_comp)}; BOOST_CHECK_EQUAL(new_field.get_nb_components(), nb_comp); BOOST_CHECK_EQUAL(new_field.size(), dyn_handle.size()); BOOST_CHECK_THROW(base_handle.get_managed_real_field(name1, nb_comp + 1), std::runtime_error); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_globalised_fields, Fix, fixlist, Fix) { constexpr Dim_t Dim{Fix::sdim}; using Mat_t = MaterialLinearElastic1; using LColl_t = typename Mat_t::MFieldCollection_t; auto & material_soft{Mat_t::make(*this, "soft", 70e9, .3)}; auto & material_hard{Mat_t::make(*this, "hard", 210e9, .3)}; for (auto && tup : akantu::enumerate(*this)) { const auto & i{std::get<0>(tup)}; const auto & pixel{std::get<1>(tup)}; if (i % 2) { material_soft.add_pixel(pixel); } else { material_hard.add_pixel(pixel); } } material_soft.initialise(); material_hard.initialise(); auto & col_soft{material_soft.get_collection()}; auto & col_hard{material_hard.get_collection()}; // compatible fields: const std::string compatible_name{"compatible"}; auto & compatible_soft{ make_field>(compatible_name, col_soft, Dim)}; auto & compatible_hard{ make_field>(compatible_name, col_hard, Dim)}; auto pixler = [](auto & field) { auto map{field.get_map()}; for (auto && tup : map.enumerate()) { const auto & pixel{std::get<0>(tup)}; auto & val{std::get<1>(tup)}; for (Dim_t i{0}; i < Dim; ++i) { val(i) = pixel[i]; } } }; pixler(compatible_soft); pixler(compatible_hard); auto & global_compatible_field{ this->get_globalised_internal_real_field(compatible_name)}; auto glo_map{global_compatible_field.get_map()}; for (auto && tup : glo_map.enumerate()) { const auto & pixel{std::get<0>(tup)}; const auto & val(std::get<1>(tup)); using Map_t = Eigen::Map>; Real err{ (val - Map_t(pixel.data()).template cast()).matrix().norm()}; BOOST_CHECK_LT(err, tol); } // incompatible fields: const std::string incompatible_name{"incompatible"}; make_field>(incompatible_name, col_soft, Dim); make_field>(incompatible_name, col_hard, Dim + 1); BOOST_CHECK_THROW( this->get_globalised_internal_real_field(incompatible_name), std::runtime_error); // wrong name/ inexistant field const std::string wrong_name{"wrong_name"}; BOOST_CHECK_THROW(this->get_globalised_internal_real_field(wrong_name), std::runtime_error); // wrong scalar type: const std::string wrong_scalar_name{"wrong_scalar"}; make_field>(wrong_scalar_name, col_soft, Dim); make_field>(wrong_scalar_name, col_hard, Dim); BOOST_CHECK_THROW( this->get_globalised_internal_real_field(wrong_scalar_name), std::runtime_error); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_fftw_engine.cc b/tests/test_fftw_engine.cc index 052263c..20a6d7c 100644 --- a/tests/test_fftw_engine.cc +++ b/tests/test_fftw_engine.cc @@ -1,143 +1,144 @@ /** * @file test_fftw_engine.cc * * @author Till Junge * * @date 05 Dec 2017 * * @brief tests for the fftw fft engine implementation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "fft/fftw_engine.hh" #include "common/ccoord_operations.hh" #include "common/field_collection.hh" #include "common/field_map.hh" #include "common/iterators.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(fftw_engine); /* ---------------------------------------------------------------------- */ - template struct FFTW_fixture { + 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(), DimM * DimM) {} FFTWEngine engine; }; struct FFTW_fixture_python_segfault { constexpr static Dim_t dim{twoD}; constexpr static Dim_t sdim{twoD}; constexpr static Dim_t mdim{twoD}; constexpr static Ccoord_t res() { return {6, 4}; } constexpr static Ccoord_t loc() { return {0, 0}; } FFTW_fixture_python_segfault() : engine{res(), mdim * mdim} {} FFTWEngine engine; }; using fixlist = boost::mpl::list< FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture_python_segfault>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Constructor_test, Fix, fixlist, Fix) { BOOST_CHECK_NO_THROW(Fix::engine.initialise(FFT_PlanFlags::estimate)); BOOST_CHECK_EQUAL(Fix::engine.size(), CcoordOps::get_size(Fix::res())); } /* ---------------------------------------------------------------------- */ BOOST_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(); } // namespace muSpectre diff --git a/tests/test_field_collections.hh b/tests/test_field_collections.hh index 8486496..b238956 100644 --- a/tests/test_field_collections.hh +++ b/tests/test_field_collections.hh @@ -1,159 +1,161 @@ /** * @file test_field_collections.hh * * @author Till Junge * * @date 23 Nov 2017 * * @brief declares fixtures for field_collection tests, so that they can be * split * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef TESTS_TEST_FIELD_COLLECTIONS_HH_ #define TESTS_TEST_FIELD_COLLECTIONS_HH_ #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 { + template + struct FC_multi_fixture { using FC_t = std::conditional_t, LocalFieldCollection>; using T4_t = TensorField; using T2_t = TensorField; using Sc_t = ScalarField; using M2_t = MatrixField; using Dyn_t = TypedField; FC_multi_fixture() : fc(), t4_field{make_field("Tensorfield Real o4", fc)}, // Real tensor field t2_field{make_field("Tensorfield Real o2", fc)}, // Real tensor field sc_field{ make_field("integer Scalar", fc)}, // integer scalar field m2_field{make_field("Matrixfield Complex sdim x mdim", fc)}, // complex matrix field dyn_field{make_field("Dynamically sized Field", fc, 12)} {} inline static constexpr Dim_t sdim() { return DimS; } inline static constexpr Dim_t mdim() { return DimM; } inline static constexpr bool global() { return Global; } FC_t fc; T4_t & t4_field; T2_t & t2_field; Sc_t & sc_field; M2_t & m2_field; Dyn_t & dyn_field; }; using mult_collections = boost::mpl::list< FC_multi_fixture<2, 2, true>, FC_multi_fixture<2, 3, true>, FC_multi_fixture<3, 3, true>, FC_multi_fixture<2, 2, false>, FC_multi_fixture<2, 3, false>, FC_multi_fixture<3, 3, false>>; //! Test fixture for iterators over multiple fields template struct FC_iterator_fixture : public FC_multi_fixture { using Parent = FC_multi_fixture; FC_iterator_fixture() : Parent() { this->fill(); } - template std::enable_if_t fill() { + template + std::enable_if_t fill() { static_assert(Global == isGlobal, "You're breaking my SFINAE plan"); Ccoord_t size; Ccoord_t loc{}; for (auto && s : size) { s = cube_size(); } this->fc.initialise(size, loc); } template std::enable_if_t fill(int dummy = 0) { static_assert(notGlobal != Global, "You're breaking my SFINAE plan"); testGoodies::RandRange rng; this->fc.add_pixel({0, 0}); for (int i = 0 * dummy; i < sele_size(); ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } this->fc.add_pixel(pixel); } this->fc.initialise(); } constexpr static Dim_t cube_size() { return 3; } constexpr static Dim_t sele_size() { return 7; } }; using iter_collections = boost::mpl::list< FC_iterator_fixture<2, 2, true>, FC_iterator_fixture<2, 3, true>, FC_iterator_fixture<3, 3, true>, FC_iterator_fixture<2, 2, false>, FC_iterator_fixture<2, 3, false>, FC_iterator_fixture<3, 3, false>>; using glob_iter_colls = boost::mpl::list, FC_iterator_fixture<2, 3, true>, FC_iterator_fixture<3, 3, true>>; } // namespace muSpectre #endif // TESTS_TEST_FIELD_COLLECTIONS_HH_ diff --git a/tests/test_field_collections_1.cc b/tests/test_field_collections_1.cc index be5f512..cb3260c 100644 --- a/tests/test_field_collections_1.cc +++ b/tests/test_field_collections_1.cc @@ -1,215 +1,222 @@ /** * @file test_field_collections_1.cc * * @author Till Junge * * @date 20 Sep 2017 * * @brief Test the FieldCollection classes which provide fast optimized * iterators over run-time typed fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with GNU Emacs; see the file COPYING. If not, write to the + * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(field_collection_tests); BOOST_AUTO_TEST_CASE(simple) { constexpr Dim_t sdim = 2; using FC_t = GlobalFieldCollection; FC_t fc; BOOST_CHECK_EQUAL(FC_t::spatial_dim(), sdim); BOOST_CHECK_EQUAL(fc.get_spatial_dim(), sdim); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(Simple_construction_test, F, test_collections, F) { BOOST_CHECK_EQUAL(F::FC_t::spatial_dim(), F::sdim()); BOOST_CHECK_EQUAL(F::fc.get_spatial_dim(), F::sdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(get_field2_test, F, test_collections, F) { const auto order{2}; using FC_t = typename F::FC_t; using TF_t = TensorField; auto && myfield = make_field("TensorField real 2", F::fc); using TensorMap = TensorFieldMap; using MatrixMap = MatrixFieldMap; using ArrayMap = ArrayFieldMap; TensorMap TFM(myfield); MatrixMap MFM(myfield); ArrayMap AFM(myfield); BOOST_CHECK_EQUAL(TFM.info_string(), "Tensor(d, " + std::to_string(order) + "_o, " + std::to_string(F::mdim()) + "_d)"); BOOST_CHECK_EQUAL(MFM.info_string(), "Matrix(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); BOOST_CHECK_EQUAL(AFM.info_string(), "Array(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(multi_field_test, F, mult_collections, F) { using FC_t = typename F::FC_t; // possible maptypes for Real tensor fields using T_type = Real; using T_TFM1_t = TensorFieldMap; using T_TFM2_t = TensorFieldMap; //! dangerous using T4_Map_t = T4MatrixFieldMap; // impossible maptypes for Real tensor fields using T_SFM_t = ScalarFieldMap; using T_MFM_t = MatrixFieldMap; using T_AFM_t = ArrayFieldMap; using T_MFMw1_t = MatrixFieldMap; using T_MFMw2_t = MatrixFieldMap; using T_MFMw3_t = MatrixFieldMap; const std::string T_name{"Tensorfield Real o4"}; const std::string T_name_w{"TensorField Real o4 wrongname"}; BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(T_TFM1_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T_TFM2_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T4_Map_t(F::fc.at(T_name))); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(T_name_w)), std::out_of_range); BOOST_CHECK_THROW(T_MFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_AFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw1_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw3_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name_w)), std::out_of_range); // possible maptypes for integer scalar fields using S_type = Int; using S_SFM_t = ScalarFieldMap; using S_TFM1_t = TensorFieldMap; using S_TFM2_t = TensorFieldMap; using S_MFM_t = MatrixFieldMap; using S_AFM_t = ArrayFieldMap; using S4_Map_t = T4MatrixFieldMap; // impossible maptypes for integer scalar fields using S_MFMw1_t = MatrixFieldMap; using S_MFMw2_t = MatrixFieldMap; using S_MFMw3_t = MatrixFieldMap; const std::string S_name{"integer Scalar"}; const std::string S_name_w{"integer Scalar wrongname"}; BOOST_CHECK_NO_THROW(S_SFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM1_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM2_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_MFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_AFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S4_Map_t(F::fc.at(S_name))); BOOST_CHECK_THROW(S_MFMw1_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw3_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_SFM_t(F::fc.at(S_name_w)), std::out_of_range); // possible maptypes for complex matrix fields using M_type = Complex; using M_MFM_t = MatrixFieldMap; using M_AFM_t = ArrayFieldMap; // impossible maptypes for complex matrix fields using M_SFM_t = ScalarFieldMap; using M_MFMw1_t = MatrixFieldMap; using M_MFMw2_t = MatrixFieldMap; using M_MFMw3_t = MatrixFieldMap; const std::string M_name{"Matrixfield Complex sdim x mdim"}; const std::string M_name_w{"Matrixfield Complex sdim x mdim wrongname"}; BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(M_MFM_t(F::fc.at(M_name))); BOOST_CHECK_NO_THROW(M_AFM_t(F::fc.at(M_name))); BOOST_CHECK_THROW(M_MFMw1_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw3_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name_w)), std::out_of_range); } /* ---------------------------------------------------------------------- */ //! Check whether fields can be initialized using mult_collections_t = boost::mpl::list, FC_multi_fixture<2, 3, true>, FC_multi_fixture<3, 3, true>>; using mult_collections_f = boost::mpl::list, FC_multi_fixture<2, 3, false>, FC_multi_fixture<3, 3, false>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_glob, F, mult_collections_t, F) { Ccoord_t size; Ccoord_t loc{}; for (auto && s : size) { s = 3; } BOOST_CHECK_NO_THROW(F::fc.initialise(size, loc)); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca, F, mult_collections_f, F) { testGoodies::RandRange rng; for (int i = 0; i < 7; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca_with_push_back, F, mult_collections_f, F) { constexpr auto mdim{F::mdim()}; constexpr int nb_pix{7}; testGoodies::RandRange rng{}; using ftype = internal::TypedSizedFieldBase; using stype = Eigen::Array; auto & field = static_cast(F::fc["Tensorfield Real o4"]); field.push_back(stype()); for (int i = 0; i < nb_pix; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_THROW(F::fc.initialise(), FieldCollectionError); for (int i = 0; i < nb_pix - 1; ++i) { field.push_back(stype()); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_field_collections_2.cc b/tests/test_field_collections_2.cc index b2d6d18..a5645c8 100644 --- a/tests/test_field_collections_2.cc +++ b/tests/test_field_collections_2.cc @@ -1,300 +1,308 @@ /** * @file test_field_collections_2.cc * * @author Till Junge * * @date 23 Nov 2017 * * @brief Continuation of tests from test_field_collection.cc, split for faster * compilation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with GNU Emacs; see the file COPYING. If not, write to the + * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" #include "common/field_map_dynamic.hh" 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"]}; TypedFieldMap dyn_map{F::fc["Tensorfield Real o4"]}; F::fc["Tensorfield Real o4"].set_zero(); for (auto && tens : T4map) { BOOST_CHECK_EQUAL(Real(Eigen::Tensor(tens.abs().sum().eval())()), 0); } for (auto && tens : T4map) { tens.setRandom(); } for (auto && tup : akantu::zip(T4map, dyn_map)) { auto & tens = std::get<0>(tup); auto & dyn = std::get<1>(tup); constexpr Dim_t nb_comp{ipow(F::mdim(), order)}; Eigen::Map> tens_arr(tens.data()); Real error{(dyn - tens_arr).matrix().norm()}; BOOST_CHECK_EQUAL(error, 0); } using Tensor2Map = TensorFieldMap; using MSqMap = MatrixFieldMap; using ASqMap = ArrayFieldMap; using A2Map = ArrayFieldMap; using WrongMap = ArrayFieldMap; Tensor2Map T2map{F::fc["Tensorfield Real o2"]}; MSqMap Mmap{F::fc["Tensorfield Real o2"]}; ASqMap Amap{F::fc["Tensorfield Real o2"]}; A2Map DynMap{F::fc["Dynamically sized Field"]}; auto & fc_ref{F::fc}; BOOST_CHECK_THROW(WrongMap{fc_ref["Dynamically sized Field"]}, FieldInterpretationError); auto t2_it = T2map.begin(); auto t2_it_end = T2map.end(); auto m_it = Mmap.begin(); auto a_it = Amap.begin(); for (; t2_it != t2_it_end; ++t2_it, ++m_it, ++a_it) { t2_it->setRandom(); auto && m = *m_it; bool comp = (m == a_it->matrix()); BOOST_CHECK(comp); } size_t counter{0}; for (auto val : DynMap) { ++counter; val += val.Ones() * counter; } counter = 0; for (auto val : DynMap) { ++counter; val -= val.Ones() * counter; auto error{val.matrix().norm()}; BOOST_CHECK_LT(error, tol); } using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } counter = 0; for (const auto & val : s_map) { BOOST_CHECK_EQUAL(counter++, val); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(ccoord_indexing_test, F, glob_iter_colls, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } for (size_t i = 0; i < CcoordOps::get_size(F::fc.get_sizes()); ++i) { BOOST_CHECK_EQUAL( CcoordOps::get_index(F::fc.get_sizes(), F::fc.get_locations(), CcoordOps::get_ccoord(F::fc.get_sizes(), F::fc.get_locations(), i)), i); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(iterator_methods_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using it_t = typename Tensor4Map::iterator; std::ptrdiff_t diff{ 3}; // arbitrary, as long as it is smaller than the container size // check constructors auto itstart = T4map.begin(); // standard way of obtaining iterator auto itend = T4map.end(); // ditto it_t it1{T4map}; it_t it2{T4map, false}; it_t it3{T4map, size_t(diff)}; BOOST_CHECK(itstart == itstart); BOOST_CHECK(itstart != itend); BOOST_CHECK_EQUAL(itstart, it1); BOOST_CHECK_EQUAL(itend, it2); // check ostream operator std::stringstream response; response << it3; BOOST_CHECK_EQUAL( response.str(), std::string("iterator on field 'Tensorfield Real o4', entry ") + std::to_string(diff)); // check move and assigment constructor (and operator+) it_t it_repl{T4map}; it_t itmove = std::move(T4map.begin()); it_t it4 = it1 + diff; it_t it7 = it4 - diff; - // BOOST_CHECK_EQUAL(itcopy, it1); + BOOST_CHECK_EQUAL(itmove, it1); BOOST_CHECK_EQUAL(it4, it3); BOOST_CHECK_EQUAL(it7, it1); // check increments/decrements BOOST_CHECK_EQUAL(it1++, it_repl); // post-increment BOOST_CHECK_EQUAL(it1, it_repl + 1); BOOST_CHECK_EQUAL(--it1, it_repl); // pre -decrement BOOST_CHECK_EQUAL(++it1, it_repl + 1); // pre -increment BOOST_CHECK_EQUAL(it1--, it_repl + 1); // post-decrement BOOST_CHECK_EQUAL(it1, it_repl); // dereference and member-of-pointer check Eigen::Tensor Tens = *it1; Eigen::Tensor Tens2 = *itstart; Eigen::Tensor check = (Tens == Tens2).all(); BOOST_CHECK_EQUAL(static_cast(check()), true); BOOST_CHECK_NO_THROW(itstart->setZero()); // check access subscripting auto T3a = *it3; auto T3b = itstart[diff]; BOOST_CHECK( static_cast(Eigen::Tensor((T3a == T3b).all())())); // div. comparisons BOOST_CHECK_LT(itstart, itend); BOOST_CHECK(!(itend < itstart)); BOOST_CHECK(!(itstart < itstart)); BOOST_CHECK_LE(itstart, itend); BOOST_CHECK_LE(itstart, itstart); BOOST_CHECK(!(itend <= itstart)); BOOST_CHECK_GT(itend, itstart); BOOST_CHECK(!(itend > itend)); BOOST_CHECK(!(itstart > itend)); BOOST_CHECK_GE(itend, itstart); BOOST_CHECK_GE(itend, itend); BOOST_CHECK(!(itstart >= itend)); // check assignment increment/decrement BOOST_CHECK_EQUAL(it1 += diff, it3); BOOST_CHECK_EQUAL(it1 -= diff, itstart); // check cell coordinates using Ccoord = Ccoord_t; Ccoord a{itstart.get_ccoord()}; Ccoord b{0}; // Weirdly, boost::has_left_shift::value is false for - // Ccoords, even though the operator is implemented :( + // Ccoords, even though the operator is implemented :(, hence we can't write // BOOST_CHECK_EQUAL(a, b); + // Workaround: bool check2 = (a == b); BOOST_CHECK(check2); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_tensor_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using T_t = typename Tensor4Map::T_t; Eigen::TensorMap Tens2(T4map[0].data(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim()); for (auto it = T4map.cbegin(); it != T4map.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && tens = *it; auto && ptr = tens.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Tensor were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // TensorMap. This means that const-correct field maps // are then also possible for tensors BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_matrix_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using MatrixMap = MatrixFieldMap; MatrixMap Mmap{F::fc["Matrixfield Complex sdim x mdim"]}; for (auto it = Mmap.cbegin(); it != Mmap.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && mat = *it; auto && ptr = mat.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Matrix were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // MatrixMap. This means that const-correct field maps // are then also possible for matrices BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_scalar_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap Smap{F::fc["integer Scalar"]}; for (auto it = Smap.cbegin(); it != Smap.cend(); ++it) { auto && scal = *it; static_assert( std::is_const>::value, "referred type should be const"); static_assert(std::is_lvalue_reference::value, "Should have returned an lvalue ref"); } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_field_collections_3.cc b/tests/test_field_collections_3.cc index 3355359..0fd7e5d 100644 --- a/tests/test_field_collections_3.cc +++ b/tests/test_field_collections_3.cc @@ -1,154 +1,163 @@ /** * @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 + * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. */ -#include + #include "test_field_collections.hh" #include "tests/test_goodies.hh" #include "common/tensor_algebra.hh" +#include + 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_FIXTURE_TEST_CASE_TEMPLATE(typed_field_getter, Fix, mult_collections, Fix) { constexpr auto mdim{Fix::mdim()}; auto & fc{Fix::fc}; auto & field = fc.template get_typed_field("Tensorfield Real o4"); BOOST_CHECK_EQUAL(field.get_nb_components(), ipow(mdim, fourthOrder)); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_geometry.cc b/tests/test_geometry.cc index 3cfe4e8..1beb9cd 100644 --- a/tests/test_geometry.cc +++ b/tests/test_geometry.cc @@ -1,174 +1,182 @@ /** * file test_geometry.cc * * @author Till Junge * * @date 19 Apr 2018 * * @brief Tests for tensor rotations * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with GNU Emacs; see the file COPYING. If not, write to the + * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. */ #include "common/geometry.hh" #include "tests.hh" #include "test_goodies.hh" #include "common/T4_map_proxy.hh" #include #include #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(geometry); /* ---------------------------------------------------------------------- */ - template struct RotationFixture { + template + struct RotationFixture { static constexpr Dim_t Dim{Dim_}; using Vec_t = Eigen::Matrix; using Mat_t = Eigen::Matrix; using Ten_t = T4Mat; using Angles_t = Eigen::Matrix; using Rot_t = Rotator; static constexpr RotationOrder EulerOrder{Rot}; static constexpr Dim_t get_Dim() { return Dim_; } RotationFixture() : rotator{euler} {} testGoodies::RandRange rr{}; Angles_t euler{2 * pi * Angles_t::Random()}; Vec_t v{Vec_t::Random()}; Mat_t m{Mat_t::Random()}; Ten_t t{Ten_t::Random()}; Rot_t rotator; }; /* ---------------------------------------------------------------------- */ using fix_list = boost::mpl::list, RotationFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_test, Fix, fix_list, Fix) { using Vec_t = typename Fix::Vec_t; using Mat_t = typename Fix::Mat_t; using Ten_t = typename Fix::Ten_t; constexpr const Dim_t Dim{Fix::get_Dim()}; Vec_t & v{Fix::v}; Mat_t & m{Fix::m}; Ten_t & t{Fix::t}; const Mat_t & R{Fix::rotator.get_rot_mat()}; Vec_t v_ref{R * v}; Mat_t m_ref{R * m * R.transpose()}; Ten_t t_ref{Ten_t::Zero()}; for (int i = 0; i < Dim; ++i) { for (int a = 0; a < Dim; ++a) { for (int l = 0; l < Dim; ++l) { for (int b = 0; b < Dim; ++b) { for (int m = 0; m < Dim; ++m) { for (int n = 0; n < Dim; ++n) { for (int o = 0; o < Dim; ++o) { for (int p = 0; p < Dim; ++p) { get(t_ref, a, b, o, p) += R(a, i) * R(b, l) * get(t, i, l, m, n) * R(o, m) * R(p, n); } } } } } } } } Vec_t v_rotator(Fix::rotator.rotate(v)); Mat_t m_rotator(Fix::rotator.rotate(m)); Ten_t t_rotator(Fix::rotator.rotate(t)); auto v_error{(v_rotator - v_ref).norm() / v_ref.norm()}; BOOST_CHECK_LT(v_error, tol); auto m_error{(m_rotator - m_ref).norm() / m_ref.norm()}; BOOST_CHECK_LT(m_error, tol); auto t_error{(t_rotator - t_ref).norm() / t_ref.norm()}; BOOST_CHECK_LT(t_error, tol); if (t_error >= tol) { std::cout << "t4_reference:" << std::endl << t_ref << std::endl; std::cout << "t4_rotator:" << std::endl << t_rotator << std::endl; } Vec_t v_back{Fix::rotator.rotate_back(v_rotator)}; Mat_t m_back{Fix::rotator.rotate_back(m_rotator)}; Ten_t t_back{Fix::rotator.rotate_back(t_rotator)}; v_error = (v_back - v).norm() / v.norm(); BOOST_CHECK_LT(v_error, tol); m_error = (m_back - m).norm() / m.norm(); BOOST_CHECK_LT(m_error, tol); t_error = (t_back - t).norm() / t.norm(); BOOST_CHECK_LT(t_error, tol); } /* ---------------------------------------------------------------------- */ using threeD_list = boost::mpl::list>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_matrix_test, Fix, threeD_list, Fix) { using Mat_t = typename Fix::Mat_t; auto c{Eigen::cos(Fix::euler.array())}; Real c_1{c[0]}, c_2{c[1]}, c_3{c[2]}; auto s{Eigen::sin(Fix::euler.array())}; Real s_1{s[0]}, s_2{s[1]}, s_3{s[2]}; Mat_t rot_ref; switch (Fix::EulerOrder) { case RotationOrder::ZXYTaitBryan: { rot_ref << c_1 * c_3 - s_1 * s_2 * s_3, -c_2 * s_1, c_1 * s_3 + c_3 * s_1 * s_2, c_3 * s_1 + c_1 * s_2 * s_3, c_1 * c_2, s_1 * s_3 - c_1 * c_3 * s_2, -c_2 * s_3, s_2, c_2 * c_3; break; } default: { BOOST_CHECK(false); break; } } auto err{(rot_ref - Fix::rotator.get_rot_mat()).norm()}; BOOST_CHECK_LT(err, tol); if (err >= tol) { std::cout << "Reference:" << std::endl << rot_ref << std::endl; std::cout << "Rotator:" << std::endl << Fix::rotator.get_rot_mat() << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_goodies.hh b/tests/test_goodies.hh index f30bb0e..9637e40 100644 --- a/tests/test_goodies.hh +++ b/tests/test_goodies.hh @@ -1,224 +1,228 @@ /** * @file test_goodies.hh * * @author Till Junge * * @date 27 Sep 2017 * * @brief helpers for testing * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef TESTS_TEST_GOODIES_HH_ #define TESTS_TEST_GOODIES_HH_ #include "common/tensor_algebra.hh" #include #include #include namespace muSpectre { namespace testGoodies { - template struct dimFixture { constexpr static Dim_t dim{Dim}; }; + template + struct dimFixture { + constexpr static Dim_t dim{Dim}; + }; using dimlist = boost::mpl::list, dimFixture, dimFixture>; /* ---------------------------------------------------------------------- */ - template class RandRange { + template + class RandRange { public: RandRange() : rd(), gen(rd()) {} template std::enable_if_t::value, dummyT> randval(T && lower, T && upper) { static_assert(std::is_same::value, "SFINAE"); auto distro = std::uniform_real_distribution(lower, upper); return distro(this->gen); } template std::enable_if_t::value, dummyT> randval(T && lower, T && upper) { static_assert(std::is_same::value, "SFINAE"); auto distro = std::uniform_int_distribution(lower, upper); return distro(this->gen); } private: std::random_device rd; std::default_random_engine gen; }; /** * explicit computation of linearisation of PK1 stress for an * objective Hooke's law. This implementation is not meant to be * efficient, but te reflect exactly the formulation in Curnier * 2000, "Méthodes numériques en mécanique des solides" for * reference and testing */ template decltype(auto) objective_hooke_explicit(Real lambda, Real mu, const Matrices::Tens2_t & F) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; using T2 = Tens2_t; using T4 = Tens4_t; T2 P; T2 I = P.Identity(); T4 K; // See Curnier, 2000, "Méthodes numériques en mécanique des // solides", p 252, (6.95b) Real Fjrjr = (F.array() * F.array()).sum(); T2 Fjrjm = F.transpose() * F; P.setZero(); for (Dim_t i = 0; i < Dim; ++i) { for (Dim_t m = 0; m < Dim; ++m) { P(i, m) += lambda / 2 * (Fjrjr - Dim) * F(i, m); for (Dim_t r = 0; r < Dim; ++r) { P(i, m) += mu * F(i, r) * (Fjrjm(r, m) - I(r, m)); } } } // See Curnier, 2000, "Méthodes numériques en mécanique des solides", p // 252 Real Fkrkr = (F.array() * F.array()).sum(); T2 Fkmkn = F.transpose() * F; T2 Fisjs = F * F.transpose(); K.setZero(); for (Dim_t i = 0; i < Dim; ++i) { for (Dim_t j = 0; j < Dim; ++j) { for (Dim_t m = 0; m < Dim; ++m) { for (Dim_t n = 0; n < Dim; ++n) { get(K, i, m, j, n) = (lambda * ((Fkrkr - Dim) / 2 * I(i, j) * I(m, n) + F(i, m) * F(j, n)) + mu * (I(i, j) * Fkmkn(m, n) + Fisjs(i, j) * I(m, n) - I(i, j) * I(m, n) + F(i, n) * F(j, m))); } } } } return std::make_tuple(P, K); } /** * takes a 4th-rank tensor and returns a copy with the last two * dimensions switched. This is particularly useful to check for * identity between a stiffness tensors computed the regular way * and the Geers way. For testing, not efficient. */ template inline auto right_transpose(const Eigen::MatrixBase & t4) -> Eigen::Matrix { constexpr Dim_t Rows{Derived::RowsAtCompileTime}; constexpr Dim_t Cols{Derived::ColsAtCompileTime}; constexpr Dim_t DimSq{Rows}; using T = typename Derived::Scalar; static_assert(Rows == Cols, "only square problems"); constexpr Dim_t Dim{ct_sqrt(DimSq)}; static_assert((Dim == twoD) or (Dim == threeD), "only two- and three-dimensional problems"); static_assert(ipow(Dim, 2) == DimSq, "The array is not a valid fourth order tensor"); T4Mat retval{T4Mat::Zero()}; /** * Note: this looks like it's doing a left transpose, but in * reality, np is rowmajor in all directions, so from numpy to * eigen, we need to transpose left, center, and * right. Therefore, if we want to right-transpose, then we need * to transpose once left, once center, and *twice* right, which * is equal to just left and center transpose. Center-transpose * happens automatically when eigen parses the input (which is * naturally written in rowmajor but interpreted into colmajor), * so all that's left to do is (ironically) the subsequent * left-transpose */ for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { for (int k{0}; k < Dim; ++k) { for (int l{0}; l < Dim; ++l) { get(retval, i, j, k, l) = get(t4, j, i, k, l); } } } } return retval; } /** * recomputes a colmajor representation of a fourth-rank rowmajor * tensor. this is useful when comparing to reference results * computed in numpy */ template inline auto from_numpy(const Eigen::MatrixBase & t4_np) -> Eigen::Matrix { constexpr Dim_t Rows{Derived::RowsAtCompileTime}; constexpr Dim_t Cols{Derived::ColsAtCompileTime}; constexpr Dim_t DimSq{Rows}; using T = typename Derived::Scalar; static_assert(Rows == Cols, "only square problems"); constexpr Dim_t Dim{ct_sqrt(DimSq)}; static_assert((Dim == twoD) or (Dim == threeD), "only two- and three-dimensional problems"); static_assert(ipow(Dim, 2) == DimSq, "The array is not a valid fourth order tensor"); T4Mat retval{T4Mat::Zero()}; T4Mat intermediate{T4Mat::Zero()}; // transpose rows for (int row{0}; row < DimSq; ++row) { for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { intermediate(row, i + Dim * j) = t4_np(row, i * Dim + j); } } } // transpose columns for (int col{0}; col < DimSq; ++col) { for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { retval(i + Dim * j, col) = intermediate(i * Dim + j, col); } } } return retval; } } // namespace testGoodies } // namespace muSpectre #endif // TESTS_TEST_GOODIES_HH_ diff --git a/tests/test_material_evaluator.cc b/tests/test_material_evaluator.cc new file mode 100644 index 0000000..44630ea --- /dev/null +++ b/tests/test_material_evaluator.cc @@ -0,0 +1,288 @@ +/** + * @file test_material_evaluator.cc + * + * @author Till Junge + * + * @date 13 Jan 2019 + * + * @brief tests for the material evaluator mechanism + * + * Copyright © 2019 Till Junge + * + * µSpectre is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µSpectre is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µSpectre; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#include "tests.hh" +#include "common/T4_map_proxy.hh" +#include "materials/material_linear_elastic2.hh" +#include "materials/material_evaluator.hh" + +#include "Eigen/Dense" + +namespace muSpectre { + + BOOST_AUTO_TEST_SUITE(material_evaluator_tests); + + /* ---------------------------------------------------------------------- */ + BOOST_AUTO_TEST_CASE(without_per_pixel_data) { + using Mat_t = MaterialLinearElastic1; + + constexpr Real Young{210e9}; + constexpr Real Poisson{.33}; + + auto mat_eval = Mat_t::make_evaluator(Young, Poisson); + auto & mat = *std::get<0>(mat_eval); + auto & evaluator = std::get<1>(mat_eval); + + using T2_t = Eigen::Matrix; + using T4_t = T4Mat; + const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + + T2_t::Identity()}; + const T2_t eps{ + .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; + + /* + * at this point, the evaluator has been created, but the underlying + * material still has zero pixels. Evaluation is not yet possible, and + * trying to do so has to fail with an explicit error message + */ + BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), + std::runtime_error); + + mat.add_pixel({}); + + const T2_t sigma{evaluator.evaluate_stress(eps, Formulation::small_strain)}; + const T2_t P{evaluator.evaluate_stress(F, Formulation::finite_strain)}; + + auto J{F.determinant()}; + auto P_reconstruct{J * sigma * F.inverse().transpose()}; + + auto error_comp{[](const auto & a, const auto & b) { + return (a - b).norm() / (a + b).norm(); + }}; + auto error{error_comp(P, P_reconstruct)}; + + constexpr Real small_strain_tol{1e-3}; + if (not(error <= small_strain_tol)) { + std::cout << "F =" << std::endl << F << std::endl; + std::cout << "ε =" << std::endl << eps << std::endl; + std::cout << "P =" << std::endl << P << std::endl; + std::cout << "σ =" << std::endl << sigma << std::endl; + std::cout << "P_reconstructed =" << std::endl + << P_reconstruct << std::endl; + } + + BOOST_CHECK_LE(error, small_strain_tol); + + T2_t sigma2, P2; + T4_t C, K; + + std::tie(sigma2, C) = + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + std::tie(P2, K) = + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + + error = error_comp(sigma2, sigma); + BOOST_CHECK_LE(error, tol); + error = error_comp(P2, P); + BOOST_CHECK_LE(error, tol); + + error = error_comp(C, K); + if (not(error <= small_strain_tol)) { + std::cout << "F =" << std::endl << F << std::endl; + std::cout << "ε =" << std::endl << eps << std::endl; + std::cout << "P =" << std::endl << P << std::endl; + std::cout << "σ =" << std::endl << sigma << std::endl; + std::cout << "K =" << std::endl << K << std::endl; + std::cout << "C =" << std::endl << C << std::endl; + } + BOOST_CHECK_LE(error, small_strain_tol); + + + mat.add_pixel({1}); + /* + * Now, the material has two pixels, and evaluating it would be ambiguous. + * It should fail with an explicit error message + */ + BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), + std::runtime_error); + } + + /* ---------------------------------------------------------------------- */ + BOOST_AUTO_TEST_CASE(with_per_pixel_data) { + using Mat_t = MaterialLinearElastic2; + + constexpr Real Young{210e9}; + constexpr Real Poisson{.33}; + + auto mat_eval{Mat_t::make_evaluator(Young, Poisson)}; + auto & mat{*std::get<0>(mat_eval)}; + auto & evaluator{std::get<1>(mat_eval)}; + + + using T2_t = Eigen::Matrix; + using T4_t = T4Mat; + const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + + T2_t::Identity()}; + const T2_t eps{ + .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; + + BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), + std::runtime_error); + + T2_t eigen_strain{[](auto x) { + return 1e-4 * (x + x.transpose()); + }(T2_t::Random() - T2_t::Ones() * .5)}; + + mat.add_pixel({}, eigen_strain); + + const T2_t sigma{evaluator.evaluate_stress(eps, Formulation::small_strain)}; + const T2_t P{evaluator.evaluate_stress(F, Formulation::finite_strain)}; + + auto J{F.determinant()}; + auto P_reconstruct{J * sigma * F.inverse().transpose()}; + + auto error_comp{[](const auto & a, const auto & b) { + return (a - b).norm() / (a + b).norm(); + }}; + auto error{error_comp(P, P_reconstruct)}; + + constexpr Real small_strain_tol{1e-3}; + if (not(error <= small_strain_tol)) { + std::cout << "F =" << std::endl << F << std::endl; + std::cout << "ε =" << std::endl << eps << std::endl; + std::cout << "P =" << std::endl << P << std::endl; + std::cout << "σ =" << std::endl << sigma << std::endl; + std::cout << "P_reconstructed =" << std::endl + << P_reconstruct << std::endl; + } + + BOOST_CHECK_LE(error, small_strain_tol); + + T2_t sigma2, P2; + T4_t C, K; + + std::tie(sigma2, C) = + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + std::tie(P2, K) = + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + + error = error_comp(sigma2, sigma); + BOOST_CHECK_LE(error, tol); + error = error_comp(P2, P); + BOOST_CHECK_LE(error, tol); + + error = error_comp(C, K); + if (not(error <= small_strain_tol)) { + std::cout << "F =" << std::endl << F << std::endl; + std::cout << "ε =" << std::endl << eps << std::endl; + std::cout << "P =" << std::endl << P << std::endl; + std::cout << "σ =" << std::endl << sigma << std::endl; + std::cout << "K =" << std::endl << K << std::endl; + std::cout << "C =" << std::endl << C << std::endl; + } + BOOST_CHECK_LE(error, small_strain_tol); + } + + /* ---------------------------------------------------------------------- */ + BOOST_AUTO_TEST_CASE(tangent_estimation) { + using Mat_t = MaterialLinearElastic1; + + constexpr Real Young{210e9}; + constexpr Real Poisson{.33}; + + auto mat_eval = Mat_t::make_evaluator(Young, Poisson); + auto & mat = *std::get<0>(mat_eval); + auto & evaluator = std::get<1>(mat_eval); + + using T2_t = Eigen::Matrix; + using T4_t = T4Mat; + const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + + T2_t::Identity()}; + const T2_t eps{ + .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; + + BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), + std::runtime_error); + + mat.add_pixel({}); + + T2_t sigma, P; + T4_t C, K; + + std::tie(sigma, C) = + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + std::tie(P, K) = + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + + constexpr Real linear_step{1.}; + constexpr Real nonlin_step{1.e-6}; + T4_t C_estim{evaluator.estimate_tangent(eps, Formulation::small_strain, + linear_step)}; + T4_t K_estim{evaluator.estimate_tangent(F, Formulation::finite_strain, + nonlin_step)}; + + auto error_comp{[](const auto & a, const auto & b) { + return (a - b).norm() / (a + b).norm(); + }}; + + constexpr Real finite_diff_tol{1e-9}; + Real error {error_comp(K, K_estim)}; + if (not(error <= finite_diff_tol)) { + std::cout << "K =" << std::endl << K << std::endl; + std::cout << "K_estim =" << std::endl << K_estim << std::endl; + } + BOOST_CHECK_LE(error, finite_diff_tol); + + error = error_comp(C, C_estim); + if (not(error <= tol)) { + std::cout << "centred difference:" << std::endl; + std::cout << "C =" << std::endl << C << std::endl; + std::cout << "C_estim =" << std::endl << C_estim << std::endl; + } + BOOST_CHECK_LE(error, tol); + + C_estim = evaluator.estimate_tangent(eps, Formulation::small_strain, + linear_step, FiniteDiff::forward); + error = error_comp(C, C_estim); + if (not(error <= tol)) { + std::cout << "forward difference:" << std::endl; + std::cout << "C =" << std::endl << C << std::endl; + std::cout << "C_estim =" << std::endl << C_estim << std::endl; + } + BOOST_CHECK_LE(error, tol); + + C_estim = evaluator.estimate_tangent(eps, Formulation::small_strain, + linear_step, FiniteDiff::backward); + error = error_comp(C, C_estim); + if (not(error <= tol)) { + std::cout << "backward difference:" << std::endl; + std::cout << "C =" << std::endl << C << std::endl; + std::cout << "C_estim =" << std::endl << C_estim << std::endl; + } + BOOST_CHECK_LE(error, tol); +} + + BOOST_AUTO_TEST_SUITE_END(); + +} // namespace muSpectre diff --git a/tests/test_material_hyper_elasto_plastic1.cc b/tests/test_material_hyper_elasto_plastic1.cc index 76cf04b..7c7b281 100644 --- a/tests/test_material_hyper_elasto_plastic1.cc +++ b/tests/test_material_hyper_elasto_plastic1.cc @@ -1,424 +1,425 @@ /** * @file test_material_hyper_elasto_plastic1.cc * * @author Till Junge * * @date 25 Feb 2018 * * @brief Tests for the large-strain Simo-type plastic law implemented * using MaterialMuSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "boost/mpl/list.hpp" #include "materials/stress_transformations_Kirchhoff.hh" #include "materials/material_hyper_elasto_plastic1.hh" #include "materials/materials_toolbox.hh" #include "tests.hh" #include "test_goodies.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_hyper_elasto_plastic_1); - template struct MaterialFixture { + template + struct MaterialFixture { using Mat = Mat_t; constexpr static Real K{.833}; // bulk modulus constexpr static Real mu{.386}; // shear modulus constexpr static Real H{.004}; // hardening modulus constexpr static Real tau_y0{.003}; // initial yield stress constexpr static Real young{MatTB::convert_elastic_modulus< ElasticModulus::Young, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; constexpr static Real poisson{MatTB::convert_elastic_modulus< ElasticModulus::Poisson, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; MaterialFixture() : mat("Name", young, poisson, tau_y0, H) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; using mats = boost::mpl::list< MaterialFixture>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mats, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_stress, Fix, mats, Fix) { // This test uses precomputed reference values (computed using // elasto-plasticity.py) for the 3d case only // need higher tol because of printout precision of reference solutions constexpr Real hi_tol{1e-8}; constexpr Dim_t mdim{Fix::mdim}, sdim{Fix::sdim}; constexpr bool has_precomputed_values{(mdim == sdim) && (mdim == threeD)}; constexpr bool verbose{false}; using Strain_t = Eigen::Matrix; using traits = MaterialMuSpectre_traits>; using LColl_t = typename traits::LFieldColl_t; using StrainStField_t = StateField>; using FlowStField_t = StateField>; // using StrainStRef_t = typename traits::LStrainMap_t::reference; // using ScalarStRef_t = typename traits::LScalarMap_t::reference; // create statefields LColl_t coll{}; coll.add_pixel({0}); coll.initialise(); auto & F_{make_statefield("previous gradient", coll)}; auto & be_{ make_statefield("previous elastic strain", coll)}; auto & eps_{make_statefield("plastic flow", coll)}; auto F_prev{F_.get_map()}; F_prev[0].current() = Strain_t::Identity(); auto be_prev{be_.get_map()}; be_prev[0].current() = Strain_t::Identity(); auto eps_prev{eps_.get_map()}; eps_prev[0].current() = 0; // elastic deformation Strain_t F{Strain_t::Identity()}; F(0, 1) = 1e-5; F_.cycle(); be_.cycle(); eps_.cycle(); Strain_t stress{ Fix::mat.evaluate_stress(F, F_prev[0], be_prev[0], eps_prev[0])}; if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.92999522e-11, 3.86000000e-06, 0.00000000e+00, 3.86000000e-06, -1.93000510e-11, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.95741950e-17; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00000000e+00, 1.00000000e-05, 0.00000000e+00, 1.00000000e-05, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0}; error = ep_ref - eps_prev[0].current(); BOOST_CHECK_LT(error, hi_tol); } if (verbose) { std::cout << "τ =" << std::endl << stress << std::endl; std::cout << "F =" << std::endl << F << std::endl; std::cout << "Fₜ =" << std::endl << F_prev[0].current() << std::endl; std::cout << "bₑ =" << std::endl << be_prev[0].current() << std::endl; std::cout << "εₚ =" << std::endl << eps_prev[0].current() << std::endl; } F_.cycle(); be_.cycle(); eps_.cycle(); // plastic deformation F(0, 1) = .2; stress = Fix::mat.evaluate_stress(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.98151335e-04, 1.98151335e-03, 0.00000000e+00, 1.98151335e-03, -1.98151335e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.60615155e-16; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00052666, 0.00513348, 0., 0.00513348, 0.99949996, 0., 0., 0., 1.; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0.11229988}; error = (ep_ref - eps_prev[0].current()) / ep_ref; BOOST_CHECK_LT(error, hi_tol); } if (verbose) { std::cout << "Post Cycle" << std::endl; std::cout << "τ =" << std::endl << stress << std::endl << "F =" << std::endl << F << std::endl << "Fₜ =" << std::endl << F_prev[0].current() << std::endl << "bₑ =" << std::endl << be_prev[0].current() << std::endl << "εₚ =" << std::endl << eps_prev[0].current() << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_stiffness, Fix, mats, Fix) { // This test uses precomputed reference values (computed using // elasto-plasticity.py) for the 3d case only // need higher tol because of printout precision of reference solutions constexpr Real hi_tol{2e-7}; constexpr Dim_t mdim{Fix::mdim}, sdim{Fix::sdim}; constexpr bool has_precomputed_values{(mdim == sdim) && (mdim == threeD)}; constexpr bool verbose{has_precomputed_values && false}; using Strain_t = Eigen::Matrix; using Stiffness_t = T4Mat; using traits = MaterialMuSpectre_traits>; using LColl_t = typename traits::LFieldColl_t; using StrainStField_t = StateField>; using FlowStField_t = StateField>; // using StrainStRef_t = typename traits::LStrainMap_t::reference; // using ScalarStRef_t = typename traits::LScalarMap_t::reference; // create statefields LColl_t coll{}; coll.add_pixel({0}); coll.initialise(); auto & F_{make_statefield("previous gradient", coll)}; auto & be_{ make_statefield("previous elastic strain", coll)}; auto & eps_{make_statefield("plastic flow", coll)}; auto F_prev{F_.get_map()}; F_prev[0].current() = Strain_t::Identity(); auto be_prev{be_.get_map()}; be_prev[0].current() = Strain_t::Identity(); auto eps_prev{eps_.get_map()}; eps_prev[0].current() = 0; // elastic deformation Strain_t F{Strain_t::Identity()}; F(0, 1) = 1e-5; F_.cycle(); be_.cycle(); eps_.cycle(); Strain_t stress{}; Stiffness_t stiffness{}; std::tie(stress, stiffness) = Fix::mat.evaluate_stress_tangent(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.92999522e-11, 3.86000000e-06, 0.00000000e+00, 3.86000000e-06, -1.93000510e-11, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.95741950e-17; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00000000e+00, 1.00000000e-05, 0.00000000e+00, 1.00000000e-05, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0}; error = ep_ref - eps_prev[0].current(); BOOST_CHECK_LT(error, hi_tol); Stiffness_t temp; temp << 1.34766667e+00, 3.86000000e-06, 0.00000000e+00, -3.86000000e-06, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, -3.61540123e-17, 3.86000000e-01, 0.00000000e+00, 3.86000000e-01, 7.12911684e-17, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 3.86000000e-01, 1.93000000e-06, 0.00000000e+00, -3.61540123e-17, 3.86000000e-01, 0.00000000e+00, 3.86000000e-01, 7.12911684e-17, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, -3.86000000e-06, 0.00000000e+00, 3.86000000e-06, 1.34766667e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 1.93000000e-06, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 3.86000000e-01, 1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 1.93000000e-06, 3.86000000e-01, 0.00000000e+00, 5.75666667e-01, 2.61999996e-17, 0.00000000e+00, 2.61999996e-17, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.34766667e+00; Stiffness_t K4b_ref{testGoodies::from_numpy(temp)}; error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4b_ref << std::endl; std::cout << "stiffness computed:\n" << stiffness << std::endl; } } if (verbose) { std::cout << "C₄ =" << std::endl << stiffness << std::endl; } F_.cycle(); be_.cycle(); eps_.cycle(); // plastic deformation F(0, 1) = .2; std::tie(stress, stiffness) = Fix::mat.evaluate_stress_tangent(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.98151335e-04, 1.98151335e-03, 0.00000000e+00, 1.98151335e-03, -1.98151335e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.60615155e-16; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00052666, 0.00513348, 0., 0.00513348, 0.99949996, 0., 0., 0., 1.; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0.11229988}; error = (ep_ref - eps_prev[0].current()) / ep_ref; BOOST_CHECK_LT(error, hi_tol); Stiffness_t temp{}; temp << 8.46343327e-01, 1.11250597e-03, 0.00000000e+00, -2.85052074e-03, 8.26305692e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 8.26305692e-01, -1.11250597e-03, 0.00000000e+00, 2.85052074e-03, 8.46343327e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 1.38777878e-17, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.46298039e-01; Stiffness_t K4b_ref{testGoodies::from_numpy(temp)}; error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4b_ref << std::endl; std::cout << "stiffness computed:\n" << stiffness << std::endl; } // check also whether pull_back is correct Stiffness_t intermediate{stiffness}; Stiffness_t zero_mediate{Stiffness_t::Zero()}; for (int i{0}; i < mdim; ++i) { for (int j{0}; j < mdim; ++j) { for (int m{0}; m < mdim; ++m) { const auto & k{i}; const auto & l{j}; // k,m inverted for right transpose get(zero_mediate, i, j, k, m) -= stress(l, m); get(intermediate, i, j, k, m) -= stress(l, m); } } } temp << 8.46145176e-01, -8.69007382e-04, 0.00000000e+00, -2.85052074e-03, 8.26305692e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, -2.85052074e-03, 1.41564428e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.41564428e-03, -1.11250597e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 8.26305692e-01, -1.11250597e-03, 0.00000000e+00, 8.69007382e-04, 8.46541479e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 9.90756677e-03, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, -9.90756677e-04, 1.01057181e-02, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 1.38777878e-17, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.46298039e-01; Stiffness_t K4c_ref{testGoodies::from_numpy(temp)}; error = (K4b_ref + zero_mediate - K4c_ref).norm() / zero_mediate.norm(); BOOST_CHECK_LT(error, hi_tol); // rel error on small difference between // inexacly read doubles if (not(error < hi_tol)) { std::cout << "decrement reference:\n" << K4c_ref - K4b_ref << std::endl; std::cout << "zero_mediate computed:\n" << zero_mediate << std::endl; } error = (K4c_ref - intermediate).norm() / K4c_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4c_ref << std::endl; std::cout << "stiffness computed:\n" << intermediate << std::endl; std::cout << "zero-mediate computed:\n" << zero_mediate << std::endl; std::cout << "difference:\n" << K4c_ref - intermediate << std::endl; } } if (verbose) { std::cout << "Post Cycle" << std::endl; std::cout << "C₄ =" << std::endl << stiffness << std::endl; } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(stress_strain_test, Fix, mats, Fix) {} BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic1.cc b/tests/test_material_linear_elastic1.cc index 1d66afd..ed36e30 100644 --- a/tests/test_material_linear_elastic1.cc +++ b/tests/test_material_linear_elastic1.cc @@ -1,233 +1,235 @@ /** * @file test_material_linear_elastic1.cc * * @author Till Junge * * @date 28 Nov 2017 * * @brief Tests for the large-strain, objective Hooke's law, implemented in * the convenient strategy (i.e., using MaterialMuSpectre), also used * to test parts of MaterialLinearElastic2 * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include "materials/material_linear_elastic1.hh" #include "materials/material_linear_elastic2.hh" #include "tests.hh" #include "tests/test_goodies.hh" #include "common/field_collection.hh" #include "common/iterators.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_1); - template struct MaterialFixture { + template + struct MaterialFixture { using Mat = Mat_t; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; MaterialFixture() : mat("Name", young, poisson) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; - template struct has_internals { + template + struct has_internals { constexpr static bool value{false}; }; template struct has_internals> { constexpr static bool value{true}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>, MaterialFixture>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_add_pixel, Fix, mat_list, Fix) { auto & mat{Fix::mat}; constexpr Dim_t sdim{Fix::sdim}; testGoodies::RandRange rng; const Dim_t nb_pixel{7}, box_size{17}; using Ccoord = Ccoord_t; for (Dim_t i = 0; i < nb_pixel; ++i) { Ccoord c; for (Dim_t j = 0; j < sdim; ++j) { c[j] = rng.randval(0, box_size); } if (!has_internals::value) { BOOST_CHECK_NO_THROW(mat.add_pixel(c)); } } BOOST_CHECK_NO_THROW(mat.initialise()); } template struct MaterialFixtureFilled : public MaterialFixture { using Mat = Mat_t; constexpr static Dim_t box_size{3}; MaterialFixtureFilled() : MaterialFixture() { using Ccoord = Ccoord_t; Ccoord cube{CcoordOps::get_cube(box_size)}; CcoordOps::Pixels pixels(cube); for (auto pixel : pixels) { this->mat.add_pixel(pixel); } this->mat.initialise(); } }; using mat_fill = boost::mpl::list< MaterialFixtureFilled>, MaterialFixtureFilled>, MaterialFixtureFilled>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_law, Fix, mat_fill, Fix) { constexpr auto cube{CcoordOps::get_cube(Fix::box_size)}; constexpr auto loc{CcoordOps::get_cube(0)}; auto & mat{Fix::mat}; using FC_t = GlobalFieldCollection; FC_t globalfields; auto & F{make_field( "Transformation Gradient", globalfields)}; auto & P1 = make_field( "Nominal Stress1", globalfields); // to be computed alone auto & P2 = make_field( "Nominal Stress2", globalfields); // to be computed with tangent auto & K = make_field( "Tangent Moduli", globalfields); // to be computed with tangent auto & Pr = make_field( "Nominal Stress reference", globalfields); auto & Kr = make_field( "Tangent Moduli reference", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); static_assert( std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); using traits = MaterialMuSpectre_traits; { // block to contain not-constant gradient map typename traits::StressMap_t grad_map( globalfields["Transformation Gradient"]); for (auto F_ : grad_map) { F_.setRandom(); } grad_map[0] = grad_map[0].Identity(); // identifiable gradients for debug grad_map[1] = 1.2 * grad_map[1].Identity(); // ditto } // compute stresses using material mat.compute_stresses(globalfields["Transformation Gradient"], globalfields["Nominal Stress1"], Formulation::finite_strain); // compute stresses and tangent moduli using material BOOST_CHECK_THROW( mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Nominal Stress2"], Formulation::finite_strain), std::runtime_error); mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Tangent Moduli"], Formulation::finite_strain); typename traits::StrainMap_t Fmap(globalfields["Transformation Gradient"]); typename traits::StressMap_t Pmap_ref( globalfields["Nominal Stress reference"]); typename traits::TangentMap_t Kmap_ref( globalfields["Tangent Moduli reference"]); for (auto tup : akantu::zip(Fmap, Pmap_ref, Kmap_ref)) { auto F_ = std::get<0>(tup); auto P_ = std::get<1>(tup); auto K_ = std::get<2>(tup); std::tie(P_, K_) = testGoodies::objective_hooke_explicit( Fix::lambda, Fix::mu, F_); } typename traits::StressMap_t Pmap_1(globalfields["Nominal Stress1"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_1)) { auto P_r = std::get<0>(tup); auto P_1 = std::get<1>(tup); Real error = (P_r - P_1).norm(); BOOST_CHECK_LT(error, tol); } typename traits::StressMap_t Pmap_2(globalfields["Nominal Stress2"]); typename traits::TangentMap_t Kmap(globalfields["Tangent Moduli"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_2, Kmap_ref, Kmap)) { auto P_r = std::get<0>(tup); auto P = std::get<1>(tup); Real error = (P_r - P).norm(); BOOST_CHECK_LT(error, tol); auto K_r = std::get<2>(tup); auto K = std::get<3>(tup); error = (K_r - K).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic2.cc b/tests/test_material_linear_elastic2.cc index 424b23c..56222ab 100644 --- a/tests/test_material_linear_elastic2.cc +++ b/tests/test_material_linear_elastic2.cc @@ -1,279 +1,280 @@ /** * @file test_material_linear_elastic2.cc * * @author Till Junge * * @date 04 Feb 2018 * * @brief Tests for the objective Hooke's law with eigenstrains, * (tests that do not require add_pixel are integrated into * `test_material_linear_elastic1.cc` * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include "materials/material_linear_elastic2.hh" #include "tests.hh" #include "tests/test_goodies.hh" #include "common/field_collection.hh" #include "common/iterators.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_2); - template struct MaterialFixture { + template + struct MaterialFixture { using Mat = Mat_t; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; MaterialFixture() : mat("Name", young, poisson) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_add_pixel, Fix, mat_list, Fix) { auto & mat{Fix::mat}; constexpr Dim_t sdim{Fix::sdim}; testGoodies::RandRange rng; const Dim_t nb_pixel{7}, box_size{17}; using Ccoord = Ccoord_t; for (Dim_t i = 0; i < nb_pixel; ++i) { Ccoord c; for (Dim_t j = 0; j < sdim; ++j) { c[j] = rng.randval(0, box_size); } Eigen::Matrix Zero = Eigen::Matrix::Zero(); BOOST_CHECK_NO_THROW(mat.add_pixel(c, Zero)); } BOOST_CHECK_NO_THROW(mat.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_eigenstrain_equivalence, Fix, mat_list, Fix) { auto & mat{Fix::mat}; const Dim_t nb_pixel{2}; constexpr auto cube{CcoordOps::get_cube(nb_pixel)}; constexpr auto loc{CcoordOps::get_cube(0)}; using Mat_t = Eigen::Matrix; using FC_t = GlobalFieldCollection; FC_t globalfields; auto & F_f{make_field( "Transformation Gradient", globalfields)}; auto & P1_f = make_field( "Nominal Stress1", globalfields); // to be computed alone auto & K_f = make_field( "Tangent Moduli", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); Mat_t zero{Mat_t::Zero()}; Mat_t F{Mat_t::Random() / 100 + Mat_t::Identity()}; Mat_t strain{-.5 * (F + F.transpose()) - Mat_t::Identity()}; using Ccoord = Ccoord_t; Ccoord pix0{0}; Ccoord pix1{1}; mat.add_pixel(pix0, zero); mat.add_pixel(pix1, strain); mat.initialise(); F_f.get_map()[pix0] = -strain; F_f.get_map()[pix1] = zero; mat.compute_stresses_tangent(F_f, P1_f, K_f, Formulation::small_strain); Real error{(P1_f.get_map()[pix0] - P1_f.get_map()[pix1]).norm()}; Real tol{1e-12}; if (error >= tol) { std::cout << "error = " << error << " >= " << tol << " = tol" << std::endl; std::cout << "P(0) =" << std::endl << P1_f.get_map()[pix0] << std::endl; std::cout << "P(1) =" << std::endl << P1_f.get_map()[pix1] << std::endl; } BOOST_CHECK_LT(error, tol); } template struct MaterialFixtureFilled : public MaterialFixture { using Par = MaterialFixture; using Mat = Mat_t; constexpr static Dim_t box_size{3}; MaterialFixtureFilled() : MaterialFixture() { using Ccoord = Ccoord_t; Ccoord cube{CcoordOps::get_cube(box_size)}; CcoordOps::Pixels pixels(cube); for (auto pixel : pixels) { Eigen::Matrix Zero = Eigen::Matrix::Zero(); this->mat.add_pixel(pixel, Zero); } this->mat.initialise(); } }; using mat_fill = boost::mpl::list< MaterialFixtureFilled>, MaterialFixtureFilled>, MaterialFixtureFilled>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_law, Fix, mat_fill, Fix) { constexpr auto cube{CcoordOps::get_cube(Fix::box_size)}; constexpr auto loc{CcoordOps::get_cube(0)}; auto & mat{Fix::mat}; using FC_t = GlobalFieldCollection; FC_t globalfields; auto & F{make_field( "Transformation Gradient", globalfields)}; auto & P1 = make_field( "Nominal Stress1", globalfields); // to be computed alone auto & P2 = make_field( "Nominal Stress2", globalfields); // to be computed with tangent auto & K = make_field( "Tangent Moduli", globalfields); // to be computed with tangent auto & Pr = make_field( "Nominal Stress reference", globalfields); auto & Kr = make_field( "Tangent Moduli reference", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); static_assert( std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); using traits = MaterialMuSpectre_traits; { // block to contain not-constant gradient map typename traits::StressMap_t grad_map( globalfields["Transformation Gradient"]); for (auto F_ : grad_map) { F_.setRandom(); } grad_map[0] = grad_map[0].Identity(); // identifiable gradients for debug grad_map[1] = 1.2 * grad_map[1].Identity(); // ditto } // compute stresses using material mat.compute_stresses(globalfields["Transformation Gradient"], globalfields["Nominal Stress1"], Formulation::finite_strain); // compute stresses and tangent moduli using material BOOST_CHECK_THROW( mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Nominal Stress2"], Formulation::finite_strain), std::runtime_error); mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Tangent Moduli"], Formulation::finite_strain); typename traits::StrainMap_t Fmap(globalfields["Transformation Gradient"]); typename traits::StressMap_t Pmap_ref( globalfields["Nominal Stress reference"]); typename traits::TangentMap_t Kmap_ref( globalfields["Tangent Moduli reference"]); for (auto tup : akantu::zip(Fmap, Pmap_ref, Kmap_ref)) { auto F_ = std::get<0>(tup); auto P_ = std::get<1>(tup); auto K_ = std::get<2>(tup); std::tie(P_, K_) = testGoodies::objective_hooke_explicit( Fix::lambda, Fix::mu, F_); } typename traits::StressMap_t Pmap_1(globalfields["Nominal Stress1"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_1)) { auto P_r = std::get<0>(tup); auto P_1 = std::get<1>(tup); Real error = (P_r - P_1).norm(); BOOST_CHECK_LT(error, tol); } typename traits::StressMap_t Pmap_2(globalfields["Nominal Stress2"]); typename traits::TangentMap_t Kmap(globalfields["Tangent Moduli"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_2, Kmap_ref, Kmap)) { auto P_r = std::get<0>(tup); auto P = std::get<1>(tup); Real error = (P_r - P).norm(); if (error >= tol) { std::cout << "error = " << error << " >= " << tol << " = tol" << std::endl; std::cout << "P(0) =" << std::endl << P_r << std::endl; std::cout << "P(1) =" << std::endl << P << std::endl; } BOOST_CHECK_LT(error, tol); auto K_r = std::get<2>(tup); auto K = std::get<3>(tup); error = (K_r - K).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic3.cc b/tests/test_material_linear_elastic3.cc index 66be5c2..a25b0c8 100644 --- a/tests/test_material_linear_elastic3.cc +++ b/tests/test_material_linear_elastic3.cc @@ -1,91 +1,92 @@ /** * @file test_material_linear_elastic3.cc * * @author Richard Leute * * @date 21 Feb 2018 * * @brief description * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "materials/material_linear_elastic3.hh" #include "materials/materials_toolbox.hh" #include "common/T4_map_proxy.hh" #include "cmath" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_3); - template struct MaterialFixture { + template + struct MaterialFixture { using Material_t = Mat_t; Material_t mat; MaterialFixture() : mat("name") { mat.add_pixel({0}, Young, Poisson); } Real Young{10}; Real Poisson{0.3}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix){}; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_response, Fix, mat_list, Fix) { constexpr Dim_t Dim{Fix::Material_t::Parent::Parent::mdim()}; Eigen::Matrix E; E.setZero(); E(0, 0) = 0.001; E(1, 0) = E(0, 1) = 0.005; using Hooke = MatTB::Hooke, T4Mat>; Real lambda = Hooke::compute_lambda(Fix::Young, Fix::Poisson); Real mu = Hooke::compute_mu(Fix::Young, Fix::Poisson); auto C = Hooke::compute_C(lambda, mu); T4MatMap Cmap{C.data()}; Eigen::Matrix stress = Fix::mat.evaluate_stress(E, Cmap); Real sigma00 = lambda * E(0, 0) + 2 * mu * E(0, 0); Real sigma01 = 2 * mu * E(0, 1); Real sigma11 = lambda * E(0, 0); BOOST_CHECK_LT(std::abs(stress(0, 0) - sigma00), tol); BOOST_CHECK_LT(std::abs(stress(0, 1) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 0) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 1) - sigma11), tol); if (Dim == threeD) { for (int i = 0; i < Dim - 1; ++i) { BOOST_CHECK_LT(std::abs(stress(2, i)), tol); BOOST_CHECK_LT(std::abs(stress(i, 2)), tol); } BOOST_CHECK_LT(std::abs(stress(2, 2) - sigma11), tol); } }; BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic4.cc b/tests/test_material_linear_elastic4.cc index aa155db..5677597 100644 --- a/tests/test_material_linear_elastic4.cc +++ b/tests/test_material_linear_elastic4.cc @@ -1,96 +1,97 @@ /** * @file test_material_linear_elastic4.cc * * @author Richard Leute * * @date 27 Mar 2018 * * @brief description * * Copyright © 2018 Richard Leute * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "materials/material_linear_elastic4.hh" #include "materials/materials_toolbox.hh" #include "common/T4_map_proxy.hh" #include "cmath" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_4); - template struct MaterialFixture { + template + struct MaterialFixture { using Material_t = Mat_t; Material_t mat; MaterialFixture() : mat("name") { mat.add_pixel({0}, Youngs_modulus, Poisson_ratio); } Real Youngs_modulus{10}; Real Poisson_ratio{0.3}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix){}; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_response, Fix, mat_list, Fix) { constexpr Dim_t Dim{Fix::Material_t::Parent::Parent::mdim()}; Eigen::Matrix E; E.setZero(); E(0, 0) = 0.001; E(1, 0) = E(0, 1) = 0.005; using Hooke = MatTB::Hooke, T4Mat>; Real lambda = Hooke::compute_lambda(Fix::Youngs_modulus, Fix::Poisson_ratio); Real mu = Hooke::compute_mu(Fix::Youngs_modulus, Fix::Poisson_ratio); Eigen::Matrix stress = Fix::mat.evaluate_stress(E, lambda, mu); Real sigma00 = lambda * E(0, 0) + 2 * mu * E(0, 0); Real sigma01 = 2 * mu * E(0, 1); Real sigma11 = lambda * E(0, 0); BOOST_CHECK_LT(std::abs(stress(0, 0) - sigma00), tol); BOOST_CHECK_LT(std::abs(stress(0, 1) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 0) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 1) - sigma11), tol); if (Dim == threeD) { for (int i = 0; i < Dim - 1; ++i) { BOOST_CHECK_LT(std::abs(stress(2, i)), tol); BOOST_CHECK_LT(std::abs(stress(i, 2)), tol); } BOOST_CHECK_LT(std::abs(stress(2, 2) - sigma11), tol); } }; BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic_generic.cc b/tests/test_material_linear_elastic_generic.cc index 17024f4..a4f80b6 100644 --- a/tests/test_material_linear_elastic_generic.cc +++ b/tests/test_material_linear_elastic_generic.cc @@ -1,91 +1,92 @@ /** * @file test_material_linear_elastic_generic.cc * * @author Till Junge * * @date 21 Sep 2018 * * @brief test for the generic linear elastic law * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" -#include "materials/material_linear_elastic_generic.cc" +#include "materials/material_linear_elastic_generic1.hh" #include "materials/materials_toolbox.hh" #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_generic); - template struct MatFixture { - using Mat_t = MaterialLinearElasticGeneric; + template + struct MatFixture { + using Mat_t = MaterialLinearElasticGeneric1; using T2_t = Eigen::Matrix; using T4_t = T4Mat; using V_t = Eigen::Matrix; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real get_lambda() { return lambda; } constexpr static Real get_mu() { return mu; } constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; using Hooke = MatTB::Hooke; MatFixture() : C_voigt{get_C_voigt()}, mat("material", this->C_voigt) {} static V_t get_C_voigt() { V_t C{}; C.setZero(); C.template topLeftCorner().setConstant(get_lambda()); C.template topLeftCorner() += 2 * get_mu() * T2_t::Identity(); constexpr Dim_t Rest{vsize(Dim) - Dim}; using Rest_t = Eigen::Matrix; C.template bottomRightCorner() += get_mu() * Rest_t::Identity(); return C; } V_t C_voigt; Mat_t mat; }; using mats = boost::mpl::list, MatFixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(C_test, Fix, mats, Fix) { const auto ref_C{ Fix::Hooke::compute_C_T4(Fix::get_lambda(), Fix::get_mu())}; Real error{(ref_C - Fix::mat.get_C()).norm()}; if (not(error < -tol)) { std::cout << "ref:" << std::endl << ref_C << std::endl; std::cout << "new:" << std::endl << Fix::mat.get_C() << std::endl; } //// TODO: (testmemory)BOOST_CHECK_LT(error, tol); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_materials_toolbox.cc b/tests/test_materials_toolbox.cc index 78ad495..97885a8 100644 --- a/tests/test_materials_toolbox.cc +++ b/tests/test_materials_toolbox.cc @@ -1,370 +1,371 @@ /** * @file test_materials_toolbox.cc * * @author Till Junge * * @date 05 Nov 2017 * * @brief Tests for the materials toolbox * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "materials/materials_toolbox.hh" #include "materials/stress_transformations_default_case.hh" #include "materials/stress_transformations_PK1_impl.hh" #include "materials/stress_transformations_PK2_impl.hh" #include "materials/stress_transformations.hh" #include "common/T4_map_proxy.hh" #include "common/tensor_algebra.hh" #include "tests/test_goodies.hh" #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(materials_toolbox) BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_strain_conversion, Fix, testGoodies::dimlist, Fix) { constexpr Dim_t dim{Fix::dim}; using T2 = Eigen::Matrix; T2 F{(T2::Random() - .5 * T2::Ones()) / 20 + T2::Identity()}; // checking Green-Lagrange T2 Eref = .5 * (F.transpose() * F - T2::Identity()); T2 E_tb = MatTB::convert_strain( Eigen::Map>(F.data())); Real error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Left Cauchy-Green Eref = F * F.transpose(); E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Right Cauchy-Green Eref = F.transpose() * F; E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Hencky (logarithmic) strain Eref = F.transpose() * F; Eigen::SelfAdjointEigenSolver EigSolv(Eref); Eref.setZero(); for (size_t i{0}; i < dim; ++i) { auto && vec = EigSolv.eigenvectors().col(i); auto && val = EigSolv.eigenvalues()(i); Eref += .5 * std::log(val) * vec * vec.transpose(); } E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); auto F_tb = MatTB::convert_strain( F); error = (F - F_tb).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(dumb_tensor_mult_test, Fix, testGoodies::dimlist, Fix) { constexpr Dim_t dim{Fix::dim}; using T4 = T4Mat; T4 A, B, R1, R2; A.setRandom(); B.setRandom(); R1 = A * B; R2.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t a = 0; a < dim; ++a) { for (Dim_t b = 0; b < dim; ++b) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(R2, i, j, k, l) += get(A, i, j, a, b) * get(B, a, b, k, l); } } } } } } auto error{(R1 - R2).norm()}; BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_PK1_stress, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Eigen::Matrix; using T4 = T4Mat; testGoodies::RandRange rng; T2 F = T2::Identity() * 2; // F.setRandom(); T2 E_tb = MatTB::convert_strain( Eigen::Map>(F.data())); Real lambda = 3; // rng.randval(1, 2); Real mu = 4; // rng.randval(1,2); T4 J = Matrices::Itrac(); T2 I = Matrices::I2(); T4 I4 = Matrices::Isymm(); T4 C = lambda * J + 2 * mu * I4; T2 S = Matrices::tensmult(C, E_tb); T2 Sref = lambda * E_tb.trace() * I + 2 * mu * E_tb; auto error{(Sref - S).norm()}; BOOST_CHECK_LT(error, tol); T4 K = Matrices::outer_under(I, S) + Matrices::outer_under(F, I) * C * Matrices::outer_under(F.transpose(), I); // See Curnier, 2000, "Méthodes numériques en mécanique des solides", p 252 T4 Kref; Real Fkrkr = (F.array() * F.array()).sum(); T2 Fkmkn = F.transpose() * F; T2 Fisjs = F * F.transpose(); Kref.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t m = 0; m < dim; ++m) { for (Dim_t n = 0; n < dim; ++n) { get(Kref, i, m, j, n) = (lambda * ((Fkrkr - dim) / 2 * I(i, j) * I(m, n) + F(i, m) * F(j, n)) + mu * (I(i, j) * Fkmkn(m, n) + Fisjs(i, j) * I(m, n) - I(i, j) * I(m, n) + F(i, n) * F(j, m))); } } } } error = (Kref - K).norm(); BOOST_CHECK_LT(error, tol); T2 P = MatTB::PK1_stress( F, S); T2 Pref = F * S; error = (P - Pref).norm(); BOOST_CHECK_LT(error, tol); auto && stress_tgt = MatTB::PK1_stress( F, S, C); T2 P_t = std::move(std::get<0>(stress_tgt)); T4 K_t = std::move(std::get<1>(stress_tgt)); error = (P_t - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_t - Kref).norm(); BOOST_CHECK_LT(error, tol); auto && stress_tgt_trivial = MatTB::PK1_stress(F, P, K); T2 P_u = std::move(std::get<0>(stress_tgt_trivial)); T4 K_u = std::move(std::get<1>(stress_tgt_trivial)); error = (P_u - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_u - Kref).norm(); BOOST_CHECK_LT(error, tol); T2 P_g; T4 K_g; std::tie(P_g, K_g) = testGoodies::objective_hooke_explicit(lambda, mu, F); error = (P_g - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_g - Kref).norm(); BOOST_CHECK_LT(error, tol); } BOOST_AUTO_TEST_CASE(elastic_modulus_conversions) { // define original input constexpr Real E{123.456}; constexpr Real nu{.3}; using MatTB::convert_elastic_modulus; // derived values constexpr Real K{ convert_elastic_modulus(E, nu)}; constexpr Real lambda{ convert_elastic_modulus(E, nu)}; constexpr Real mu{ convert_elastic_modulus(E, nu)}; // recover original inputs Real comp = convert_elastic_modulus(K, mu); Real err = E - comp; BOOST_CHECK_LT(err, tol); comp = convert_elastic_modulus(K, mu); err = nu - comp; BOOST_CHECK_LT(err, tol); comp = convert_elastic_modulus(lambda, mu); err = E - comp; BOOST_CHECK_LT(err, tol); // check inversion resistance Real compA = convert_elastic_modulus(K, mu); Real compB = convert_elastic_modulus(mu, K); BOOST_CHECK_EQUAL(compA, compB); // check trivial self-returning comp = convert_elastic_modulus(K, mu); BOOST_CHECK_EQUAL(K, comp); comp = convert_elastic_modulus(K, mu); BOOST_CHECK_EQUAL(mu, comp); // check alternative calculation of computed values comp = convert_elastic_modulus( K, mu); // alternative for "Shear" BOOST_CHECK_LE(std::abs((comp - lambda) / lambda), tol); } - template struct FiniteDifferencesHolder { + template + struct FiniteDifferencesHolder { constexpr static FiniteDiff value{FinDiff}; }; using FinDiffList = boost::mpl::list, FiniteDifferencesHolder, FiniteDifferencesHolder>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(numerical_tangent_test, Fix, FinDiffList, Fix) { constexpr Dim_t Dim{twoD}; using T4_t = T4Mat; using T2_t = Eigen::Matrix; bool verbose{false}; T4_t Q{}; Q << 1., 2., 0., 0., 0., 1.66666667, 0., 0., 0., 0., 2.33333333, 0., 0., 0., 0., 3.; if (verbose) { std::cout << Q << std::endl << std::endl; } T2_t B{}; B << 2., 3.33333333, 2.66666667, 4.; if (verbose) { std::cout << B << std::endl << std::endl; } auto fun = [&](const T2_t & x) -> T2_t { using cmap_t = Eigen::Map>; using map_t = Eigen::Map>; cmap_t x_vec{x.data()}; T2_t ret_val{}; map_t(ret_val.data()) = Q * x_vec + cmap_t(B.data()); return ret_val; }; T2_t temp_res = fun(T2_t::Ones()); if (verbose) { std::cout << temp_res << std::endl << std::endl; } T4_t numerical_tangent{MatTB::compute_numerical_tangent( fun, T2_t::Ones(), 1e-2)}; if (verbose) { std::cout << numerical_tangent << std::endl << std::endl; } Real error{(numerical_tangent - Q).norm() / Q.norm()}; BOOST_CHECK_LT(error, tol); if (not(error < tol)) { switch (Fix::value) { case FiniteDiff::backward: { std::cout << "backward difference: " << std::endl; break; } case FiniteDiff::forward: { std::cout << "forward difference: " << std::endl; break; } case FiniteDiff::centred: { std::cout << "centered difference: " << std::endl; break; } } std::cout << "error = " << error << std::endl; std::cout << "numerical tangent:\n" << numerical_tangent << std::endl; std::cout << "reference:\n" << Q << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_projection.hh b/tests/test_projection.hh index 9e42631..9888732 100644 --- a/tests/test_projection.hh +++ b/tests/test_projection.hh @@ -1,99 +1,105 @@ /** * @file test_projection.hh * * @author Till Junge * * @date 16 Jan 2018 * * @brief common declarations for testing both the small and finite strain * projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "fft/fftw_engine.hh" #include #include #ifndef TESTS_TEST_PROJECTION_HH_ #define TESTS_TEST_PROJECTION_HH_ namespace muSpectre { /* ---------------------------------------------------------------------- */ - template struct Sizes {}; - template <> struct Sizes { + 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 { + 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 { + 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 { + 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 Parent = Proj; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; ProjectionFixture() : projector(std::make_unique(SizeGiver::get_resolution(), mdim * mdim), SizeGiver::get_lengths()) {} Parent projector; }; } // namespace muSpectre #endif // TESTS_TEST_PROJECTION_HH_ diff --git a/tests/test_solver_newton_cg.cc b/tests/test_solver_newton_cg.cc index ab94ad3..16db226 100644 --- a/tests/test_solver_newton_cg.cc +++ b/tests/test_solver_newton_cg.cc @@ -1,478 +1,481 @@ /** * @file test_solver_newton_cg.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief Tests for the standard Newton-Raphson + Conjugate Gradient solver * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" #include "solver/solver_eigen.hh" #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" #include "solver/deprecated_solver_cg_eigen.hh" #include "fft/fftw_engine.hh" #include "fft/projection_finite_strain_fast.hh" #include "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, 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); DeprecatedSolverCG cg{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res1{ deprecated_de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res2{ deprecated_newton_cg(sys, grads, cg2, newton_tol, verbose)[0].grad}; BOOST_CHECK_LE(abs(res1 - res2).mean(), cg_tol); } BOOST_AUTO_TEST_CASE(small_strain_patch_test) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); sys.initialise(); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}, equil_tol{1e-10}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto result = deprecated_newton_cg( sys, delEps0, cg, newton_tol, // de_geus(sys, delEps0, cg, newton_tol, equil_tol, verbose); if (verbose) { std::cout << "result:" << std::endl << result.grad << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0 = Grad_t::Zero(); delEps0(0, 1) = delEps0(1, 0) = eps0; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; result = deprecated_newton_cg(sys, delEps0, cg2, newton_tol, equil_tol, verbose); Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } - template struct SolverFixture { using type = SolverType; }; + template + struct SolverFixture { + using type = SolverType; + }; using SolverList = boost::mpl::list< SolverFixture, SolverFixture, SolverFixture, SolverFixture, SolverFixture, SolverFixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(small_strain_patch_dynamic_solver, Fix, SolverList, Fix) { // BOOST_AUTO_TEST_CASE(small_strain_patch_test_dynamic_solver) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); sys.initialise(); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}, equil_tol{1e-10}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; using Solver_t = typename Fix::type; Solver_t cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto result = newton_cg(sys, delEps0, cg, newton_tol, equil_tol, verbose); if (verbose) { std::cout << "result:" << std::endl << result.grad << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0 = Grad_t::Zero(); delEps0(0, 1) = delEps0(1, 0) = eps0; Solver_t cg2{sys, cg_tol, maxiter, static_cast(verbose)}; result = de_geus(sys, delEps0, cg2, newton_tol, equil_tol, verbose); Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } BOOST_AUTO_TEST_CASE(small_strain_patch_test_new_interface_manual) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto F = sys.get_strain_vector(); F.setZero(); sys.evaluate_stress_tangent(); Eigen::VectorXd DelF(sys.get_nb_dof()); using RMap_t = RawFieldMap>>; for (auto tmp : RMap_t(DelF)) { tmp = delEps0; } Eigen::VectorXd rhs = -sys.evaluate_projected_directional_stiffness(DelF); F += DelF; DelF.setZero(); cg.initialise(); Eigen::Map(DelF.data(), DelF.size()) = cg.solve(rhs, DelF); F += DelF; if (verbose) { std::cout << "result:" << std::endl << F << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0.setZero(); delEps0(0, 1) = delEps0(1, 0) = eps0; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; F.setZero(); sys.evaluate_stress_tangent(); for (auto tmp : RMap_t(DelF)) { tmp = delEps0; } rhs = -sys.evaluate_projected_directional_stiffness(DelF); F += DelF; DelF.setZero(); cg2.initialise(); DelF = cg2.solve(rhs, DelF); F += DelF; Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre