diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index 16c9bdd30..7e9d5ccc4 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -1,305 +1,271 @@ #=============================================================================== # @file CMakeLists.txt # # @author Nicolas Richart <nicolas.richart@epfl.ch> # # @date creation: Fri Dec 12 2014 # @date last modification: Mon Jan 18 2016 # # @brief CMake file for the python wrapping of akantu # # @section LICENSE # # Copyright (©) 2015 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 <http://www.gnu.org/licenses/>. # #=============================================================================== #=============================================================================== # Configuration #=============================================================================== package_get_all_definitions(AKANTU_DEFS) list(REMOVE_ITEM AKANTU_DEFS AKANTU_CORE_CXX11) #message(${AKANTU_DEFS}) set(AKA_DEFS "") foreach (def ${AKANTU_DEFS}) list(APPEND AKA_DEFS "-D${def}") endforeach() set(AKANTU_SWIG_FLAGS -w309,325,401,317,509,503,383,384 ${AKA_DEFS}) set(AKANTU_SWIG_OUTDIR ${CMAKE_CURRENT_SOURCE_DIR}) set(AKANTU_SWIG_MODULES swig/akantu.i) #=============================================================================== # Swig wrapper #=============================================================================== - set(SWIG_REQURIED_VERISON 3.0) find_package(SWIG ${SWIG_REQURIED_VERISON}) find_package(PythonInterp ${AKANTU_PREFERRED_PYTHON_VERSION} REQUIRED) mark_as_advanced(SWIG_EXECUTABLE) if(NOT PYTHON_VERSION_MAJOR LESS 3) list(APPEND AKANTU_SWIG_FLAGS -py3) endif() package_get_all_include_directories( AKANTU_LIBRARY_INCLUDE_DIRS ) set(_swig_include_dirs ${CMAKE_CURRENT_SOURCE_DIR}/swig ${AKANTU_LIBRARY_INCLUDE_DIRS} ${PROJECT_BINARY_DIR}/src ${AKANTU_EXTERNAL_INCLUDE_DIR} ) include(CMakeParseArguments) function(swig_generate_dependencies _module _depedencies _depedencies_out) set(_dependencies_script "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/_swig_generate_dependencies.cmake") file(WRITE ${_dependencies_script} " set(_include_directories ${_include_directories}) list(APPEND _include_directories \"./\") set(_dep) set(_files_to_process \${_module}) while(_files_to_process) list(GET _files_to_process 0 _file) list(REMOVE_AT _files_to_process 0) file(STRINGS \${_file} _file_content REGEX \"^%include *\\\"(.*)\\\"\") set(_includes) foreach(_line \${_file_content}) string(REGEX REPLACE \"^%include *\\\"(.*)\\\"\" \"\\\\1\" _inc \${_line}) if(_inc) list(APPEND _includes \${_inc}) endif() endforeach() foreach(_include \${_includes}) unset(_found) foreach(_inc_dir \${_include_directories}) if(EXISTS \${_inc_dir}/\${_include}) set(_found \${_inc_dir}/\${_include}) break() endif() endforeach() if(_found) list(APPEND _files_to_process \${_found}) list(APPEND _dep \${_found}) endif() endforeach() endwhile() get_filename_component(_module_we \"\${_module}\" NAME_WE) set(_dependencies_file \${CMAKE_CURRENT_BINARY_DIR}\${CMAKE_FILES_DIRECTORY}/_swig_\${_module_we}_depends.cmake) file(WRITE \"\${_dependencies_file}\" \"set(_swig_\${_module_we}_depends\") foreach(_d \${_dep}) file(APPEND \"\${_dependencies_file}\" \" \${_d}\") endforeach() file(APPEND \"\${_dependencies_file}\" \" )\") ") get_filename_component(_module_absolute "${_module}" ABSOLUTE) get_filename_component(_module_we "${_module}" NAME_WE) set(_dependencies_file ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/_swig_${_module_we}_depends.cmake) if(EXISTS ${_dependencies_file}) include(${_dependencies_file}) else() execute_process(COMMAND ${CMAKE_COMMAND} -D_module=${_module_absolute} -P ${_dependencies_script} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) include(${_dependencies_file}) endif() set(${_depedencies_out} ${_swig_${_module_we}_depends} PARENT_SCOPE) add_custom_command(OUTPUT ${_dependencies_file} COMMAND ${CMAKE_COMMAND} -D_module=${_module_absolute} -P ${_dependencies_script} COMMENT "Scanning dependencies for swig module ${_module_we}" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} MAIN_DEPENDENCY ${_module_absolute} DEPENDS ${_swig_${_module_we}_depends} ) set(${_depedencies} ${_dependencies_file} PARENT_SCOPE) endfunction() function(swig_generate_wrappers project _wrappers_cpp _wrappers_py) cmake_parse_arguments(_swig_opt "" "OUTPUT_DIR;DEPENDENCIES" "EXTRA_FLAGS;INCLUDE_DIRECTORIES" ${ARGN}) if(_swig_opt_OUTPUT_DIR) set(_output_dir ${_swig_opt_OUTPUT_DIR}) else() set(_output_dir ${CMAKE_CURRENT_BINARY_DIR}) endif() set(_swig_wrappers) get_directory_property(_include_directories INCLUDE_DIRECTORIES) list(APPEND _include_directories ${_swig_opt_INCLUDE_DIRECTORIES}) if(_include_directories) string(REPLACE ";" ";-I" _swig_include_directories "${_include_directories}") endif() foreach(_module ${_swig_opt_UNPARSED_ARGUMENTS}) swig_generate_dependencies(${_module} _module_dependencies _depends_out) if(_swig_opt_DEPENDENCIES) set(${_swig_opt_DEPENDENCIES} ${_depends_out} PARENT_SCOPE) endif() get_filename_component(_module_absolute "${_module}" ABSOLUTE) get_filename_component(_module_path "${_module_absolute}" PATH) get_filename_component(_module_name "${_module}" NAME) get_filename_component(_module_we "${_module}" NAME_WE) set(_wrapper "${_output_dir}/${_module_we}_wrapper.cpp") set(_extra_wrapper "${_output_dir}/${_module_we}.py") set(_extra_wrapper_bin "${CMAKE_CURRENT_BINARY_DIR}/${_module_we}.py") if(SWIG_FOUND) set_source_files_properties("${_wrapper}" PROPERTIES GENERATED 1) set_source_files_properties("${_extra_wrapper}" PROPERTIES GENERATED 1) set(_dependencies_file ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/_swig_${_module_we}_depends.cmake) set(_ouput "${_wrapper}" "${_extra_wrapper}") add_custom_command( OUTPUT ${_ouput} COMMAND "${SWIG_EXECUTABLE}" ARGS -python -c++ ${_swig_opt_EXTRA_FLAGS} -outdir ${_output_dir} -I${_swig_include_directories} -I${_module_path} -o "${_wrapper}" "${_module_absolute}" COMMAND ${CMAKE_COMMAND} -E copy_if_different ${_extra_wrapper} ${_extra_wrapper_bin} # MAIN_DEPENDENCY "${_module_absolute}" DEPENDS ${_module_dependencies} COMMENT "Generating swig wrapper ${_module} -> ${_wrapper}" ) list(APPEND _swig_wrappers ${_wrapper}) list(APPEND _swig_wrappers_py "${_extra_wrapper_bin}") else() if(NOT EXISTS ${_wrapper} OR NOT EXISTS "${_extra_wrapper}") message(FATAL_ERROR "The file ${_wrapper} and/or ${_extra_wrapper} does " "not exists and they cannot be generated. Install swig ${SWIG_REQURIED_VERISON} " " in order to generate them. Or get them from a different machine, " "in order to be able to compile the python interface") else() list(APPEND _swig_wrappers "${_wrapper}") list(APPEND _swig_wrappers_py "${_extra_wrapper_bin}") endif() endif() endforeach() add_custom_target(${project}_generate_swig_wrappers DEPENDS ${_swig_wrappers}) set(${_wrappers_cpp} ${_swig_wrappers} PARENT_SCOPE) set(${_wrappers_py} ${_swig_wrappers_py} PARENT_SCOPE) endfunction() swig_generate_wrappers(akantu AKANTU_SWIG_WRAPPERS_CPP AKANTU_WRAPPERS_PYTHON ${AKANTU_SWIG_MODULES} EXTRA_FLAGS ${AKANTU_SWIG_FLAGS} DEPENDENCIES _deps INCLUDE_DIRECTORIES ${_swig_include_dirs}) if(AKANTU_SWIG_WRAPPERS_CPP) - string(REPLACE ";" "', '" _ext_files "${AKANTU_SWIG_WRAPPERS_CPP}") - string(REPLACE ";" "', '" _inc_dirs "${_swig_include_dirs}") - if (AKANTU_EXTRA_CXX_FLAGS) - string(STRIP "${AKANTU_EXTRA_CXX_FLAGS}" _tmp_flags) - string(REGEX REPLACE " +" "', '" _flags "${_tmp_flags} -Wno-maybe-uninitialized") - else() - set(_flags "-Wno-maybe-uninitialized") - endif() - - if(CMAKE_VERBOSE_MAKEFILE) - set(_quiet) - else() + set(_ext_files "${AKANTU_SWIG_WRAPPERS_CPP}") + set(_inc_dirs "${_swig_include_dirs}") + set(_lib_dirs "${Akantu_BINARY_DIR}/src") + + string(TOUPPER CMAKE_BUILD_TYPE _config) + set(_akantu_lib_name "akantu${CMAKE_${_config}_POSTFIX}") + + get_property(_compile_flags TARGET akantu PROPERTY COMPILE_FLAGS) + set(_compile_flags "${_compile_flags} ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${_config}}") + separate_arguments(_compile_flags) + get_property(_cxx_standard TARGET akantu PROPERTY CXX_STANDARD) + set(_flags ${_compile_flags} -std=c++${_cxx_standard} + -Wno-maybe-uninitialized -Wno-unused-parameter) + + set(_quiet) + if(NOT CMAKE_VERBOSE_MAKEFILE) set(_quiet --quiet) endif() - file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/setup.py " -from distutils.core import setup -from distutils.core import setup, Extension -import os - - -os.environ['CC'] = '${CMAKE_CXX_COMPILER}' -os.environ['CXX'] = '${CMAKE_CXX_COMPILER}' - -setup(name='akantu', - license='LGPLv3', - version='${AKANTU_VERSION}', - py_modules=['akantu'], - ext_modules=[Extension('_akantu', ['${_ext_files}'], - include_dirs=['${_inc_dirs}'], - language='c++', - libraries=['akantu${CMAKE_DEBUG_POSTFIX}'], - library_dirs=['${PROJECT_BINARY_DIR}/src'], - extra_compile_args=['${_flags}', '-O0', '-g', '-std=c++14'])], - ) -") + configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/setup.py.in + ${CMAKE_CURRENT_BINARY_DIR}/setup.py @ONLY) add_custom_target(_akantu ALL COMMAND ${PYTHON_EXECUTABLE} ./setup.py ${_quiet} --no-user-cfg build_ext --inplace WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${AKANTU_SWIG_WRAPPERS_CPP} akantu COMMENT "Building akantu's python interface" ) set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES - ${CMAKE_CURRENT_BINARY_DIR}/_akantu${CMAKE_SHARED_MODULE_SUFFIX}) - - # add_library(_akantu MODULE ${AKANTU_SWIG_WRAPPERS_CPP}) - # target_link_libraries(_akantu akantu) - - # set_target_properties(_akantu PROPERTIES PREFIX "") - - # list(APPEND AKANTU_EXPORT_LIST _akantu) - - # install(TARGETS _akantu - # EXPORT ${AKANTU_TARGETS_EXPORT} - # LIBRARY DESTINATION lib COMPONENT python NAMELINK_SKIP # for real systems - # ARCHIVE DESTINATION lib COMPONENT python - # RUNTIME DESTINATION bin COMPONENT python # for windows ... - # ) - - # install(FILES ${AKANTU_WRAPPERS_PYTHON} - # DESTINATION lib COMPONENT python - # ) + ${CMAKE_CURRENT_BINARY_DIR}/_akantu${CMAKE_SHARED_MODULE_SUFFIX}) install(CODE "execute_process( COMMAND ${PYTHON_EXECUTABLE} ./setup.py ${_quiet} install --prefix=${AKANTU_PYTHON_INSTALL_PREFIX} - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - )" - COMPONENT python) + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})" + ) package_declare_extra_files_to_package(python_interface ${_deps} ${PROJECT_SOURCE_DIR}/python/${AKANTU_SWIG_MODULES}) endif() diff --git a/python/setup.py.in b/python/setup.py.in new file mode 100644 index 000000000..f373e97c0 --- /dev/null +++ b/python/setup.py.in @@ -0,0 +1,28 @@ +from distutils.core import setup +from distutils.core import setup, Extension +import os +import sys + +os.environ['CC'] = '@CMAKE_CXX_COMPILER@' +os.environ['CXX'] = '@CMAKE_CXX_COMPILER@' + +def cmake_to_list(cmake_list): + if cmake_list == '': + return [] + return cmake_list.split(';') + +setup( + name='akantu', + license='LGPLv3', + version='@AKANTU_VERSION@', + py_modules=['akantu'], + ext_modules=[Extension( + '_akantu', + cmake_to_list('@_ext_files@'), + include_dirs=cmake_to_list('@_inc_dirs@'), + language='c++', + libraries=cmake_to_list('@_akantu_lib_name@'), + library_dirs=cmake_to_list('@_lib_dirs@'), + extra_compile_args=cmake_to_list('@_flags@') + )] +) diff --git a/python/swig/aka_common.i b/python/swig/aka_common.i index 20401aac7..51fc2b460 100644 --- a/python/swig/aka_common.i +++ b/python/swig/aka_common.i @@ -1,125 +1,124 @@ /** * @file aka_common.i * * @author Guillaume Anciaux <guillaume.anciaux@epfl.ch> * @author Fabian Barras <fabian.barras@epfl.ch> * @author Nicolas Richart <nicolas.richart@epfl.ch> * * @date creation: Fri Dec 12 2014 * @date last modification: Wed Jan 13 2016 * * @brief wrapper to aka_common.hh * * @section LICENSE * * Copyright (©) 2015 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 <http://www.gnu.org/licenses/>. * */ %{ //#include "aka_config.hh" #include "aka_common.hh" #include "aka_csr.hh" #include "element.hh" %} namespace akantu { %ignore getStaticParser; %ignore getUserParser; %ignore ghost_types; %ignore initialize(int & argc, char ** & argv); %ignore initialize(const std::string & input_file, int & argc, char ** & argv); extern const Array<UInt> empty_filter; } %typemap(in) (int argc, char *argv[]) { int i = 0; if (!PyList_Check($input)) { PyErr_SetString(PyExc_ValueError, "Expecting a list"); return NULL; } $1 = PyList_Size($input); $2 = new char *[$1+1]; for (i = 0; i < $1; i++) { PyObject *s = PyList_GetItem($input,i); if (!PyString_Check(s)) { free($2); PyErr_SetString(PyExc_ValueError, "List items must be strings"); return NULL; } $2[i] = PyString_AsString(s); } $2[i] = 0; } %typemap(freearg) (int argc, char *argv[]) { %#if defined(__INTEL_COMPILER) //#pragma warning ( disable : 383 ) %#elif defined (__clang__) // test clang to be sure that when we test for gnu it is only gnu %#elif (defined(__GNUC__) || defined(__GNUG__)) %# if __cplusplus > 199711L %# pragma GCC diagnostic ignored "-Wmaybe-uninitialized" %# endif %#endif delete [] $2; %#if defined(__INTEL_COMPILER) //#pragma warning ( disable : 383 ) %#elif defined (__clang__) // test clang to be sure that when we test for gnu it is only gnu %#elif (defined(__GNUC__) || defined(__GNUG__)) %# if __cplusplus > 199711L %# pragma GCC diagnostic pop %# endif %#endif } %inline %{ namespace akantu { #if defined(AKANTU_USE_MPI) const int MPI=1; #else const int MPI=0; #endif - void _initializeWithArgv(const std::string & input_file, int argc, char *argv[]) { - initialize(input_file, argc, argv); + void _initializeWithoutArgv(const std::string & input_file) { + int nb_args = 0; + char ** null = nullptr; + initialize(input_file, nb_args, null); } } %} %pythoncode %{ import sys as _aka_sys def initialize(input_file="", argv=_aka_sys.argv): if _aka_sys.modules[__name__].MPI == 1: try: from mpi4py import MPI except ImportError: pass - _initializeWithArgv(input_file, argv) + _initializeWithoutArgv(input_file) %} %include "aka_config.hh" %include "aka_common.hh" %include "aka_element_classes_info.hh" %include "element.hh" - - - diff --git a/python/swig/communicator.i b/python/swig/communicator.i new file mode 100644 index 000000000..af49d1d2c --- /dev/null +++ b/python/swig/communicator.i @@ -0,0 +1,6 @@ +namespace akantu { +%ignore CommunicationBuffer::operator=; +%template(DataAccessorElement) DataAccessor<Element>; +} + +%include "data_accessor.hh" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 14bd39a32..c753e1594 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,211 +1,217 @@ #=============================================================================== # @file CMakeLists.txt # # @author Guillaume Anciaux <guillaume.anciaux@epfl.ch> # @author Nicolas Richart <nicolas.richart@epfl.ch> # # @date creation: Mon Jun 14 2010 # @date last modification: Wed Jan 20 2016 # # @brief CMake file for the library # # @section LICENSE # # Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. # #=============================================================================== #=============================================================================== # Package Management #=============================================================================== package_get_all_source_files( AKANTU_LIBRARY_SRCS AKANTU_LIBRARY_PUBLIC_HDRS AKANTU_LIBRARY_PRIVATE_HDRS ) package_get_all_include_directories( AKANTU_LIBRARY_INCLUDE_DIRS ) package_get_all_external_informations( PRIVATE_INCLUDE AKANTU_PRIVATE_EXTERNAL_INCLUDE_DIR INTERFACE_INCLUDE AKANTU_INTERFACE_EXTERNAL_INCLUDE_DIR LIBRARIES AKANTU_EXTERNAL_LIBRARIES ) package_get_all_compilation_flags(CXX _cxx_flags) set(AKANTU_EXTRA_CXX_FLAGS "${_cxx_flags}" CACHE STRING "Extra flags defined by loaded packages" FORCE) mark_as_advanced(AKANTU_EXTRA_CXX_FLAGS) foreach(src_ ${AKANTU_SPIRIT_SOURCES}) set_property(SOURCE ${src_} PROPERTY COMPILE_FLAGS "-g0 -Werror") endforeach() #=========================================================================== # header for blas/lapack (any other fortran libraries) #=========================================================================== package_is_activated(BLAS _blas_activated) package_is_activated(LAPACK _lapack_activated) if(_blas_activated OR _lapack_activated) if(CMAKE_Fortran_COMPILER) # ugly hack set(CMAKE_Fortran_COMPILER_LOADED TRUE) endif() include(FortranCInterface) FortranCInterface_HEADER( "${CMAKE_CURRENT_BINARY_DIR}/aka_fortran_mangling.hh" MACRO_NAMESPACE "AKA_FC_") mark_as_advanced(CDEFS) endif() list(APPEND AKANTU_LIBRARY_INCLUDE_DIRS "${CMAKE_CURRENT_BINARY_DIR}") set(AKANTU_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} ${AKANTU_LIBRARY_INCLUDE_DIRS} CACHE INTERNAL "Internal include directories to link with Akantu as a subproject") #=========================================================================== # configurations #=========================================================================== package_get_all_material_includes(AKANTU_MATERIAL_INCLUDES) package_get_all_material_lists(AKANTU_MATERIAL_LISTS) configure_file(model/solid_mechanics/material_list.hh.in "${CMAKE_CURRENT_BINARY_DIR}/material_list.hh" @ONLY) package_get_element_lists() configure_file(common/aka_element_classes_info.hh.in "${CMAKE_CURRENT_BINARY_DIR}/aka_element_classes_info.hh" @ONLY) configure_file(common/aka_config.hh.in "${CMAKE_CURRENT_BINARY_DIR}/aka_config.hh" @ONLY) #=============================================================================== # Debug infos #=============================================================================== set(AKANTU_GDB_DIR ${PROJECT_SOURCE_DIR}/cmake) if(UNIX) string(TOUPPER "${CMAKE_BUILD_TYPE}" _u_build_type) if(_u_build_type STREQUAL "DEBUG" OR _u_build_type STREQUAL "RELWITHDEBINFO") configure_file(${PROJECT_SOURCE_DIR}/cmake/libakantu-gdb.py.in "${PROJECT_BINARY_DIR}/libakantu-gdb.py" @ONLY) configure_file(${PROJECT_SOURCE_DIR}/cmake/akantu-debug.cc.in "${PROJECT_BINARY_DIR}/akantu-debug.cc" @ONLY) list(APPEND AKANTU_LIBRARY_SRCS ${PROJECT_BINARY_DIR}/akantu-debug.cc) endif() else() find_program(GDB_EXECUTABLE gdb) if(GDB_EXECUTABLE) execute_process(COMMAND ${GDB_EXECUTABLE} --batch -x "${PROJECT_SOURCE_DIR}/cmake/gdb_python_path" OUTPUT_VARIABLE AKANTU_PYTHON_GDB_DIR ERROR_QUIET RESULT_VARIABLE _res) if(_res EQUAL 0 AND UNIX) set(GDB_USER_CONFIG $ENV{HOME}/.gdb/auto-load) file(MAKE_DIRECTORY ${GDB_USER_CONFIG}) configure_file(${PROJECT_SOURCE_DIR}/cmake/libakantu-gdb.py.in "${GDB_USER_CONFIG}/${CMAKE_SHARED_LIBRARY_PREFIX}akantu${CMAKE_SHARED_LIBRARY_SUFFIX}.${AKANTU_VERSION}-gdb.py" @ONLY) endif() endif() endif() #=============================================================================== # Library generation #=============================================================================== add_library(akantu ${AKANTU_LIBRARY_SRCS}) target_include_directories(akantu - PRIVATE $<BUILD_INTERFACE:${AKANTU_INCLUDE_DIRS}> + PRIVATE $<BUILD_INTERFACE:${AKANTU_INCLUDE_DIRS}> INTERFACE $<INSTALL_INTERFACE:include/akantu> ) -target_include_directories(akantu SYSTEM BEFORE + +# small trick for build includes in public +set_property(TARGET akantu APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $<BUILD_INTERFACE:${AKANTU_INCLUDE_DIRS}>) + +target_include_directories(akantu SYSTEM PUBLIC $<BUILD_INTERFACE:${AKANTU_INTERFACE_EXTERNAL_INCLUDE_DIR}> - $<INSTALL_INTERFACE:${AKANTU_INTERFACE_EXTERNAL_INCLUDE_DIR}> + $<INSTALL_INTERFACE:${AKANTU_INTERFACE_EXTERNAL_INCLUDE_DIR}> ) -target_include_directories(akantu SYSTEM BEFORE +target_include_directories(akantu SYSTEM PRIVATE ${AKANTU_PRIVATE_EXTERNAL_INCLUDE_DIR} ) target_link_libraries(akantu ${AKANTU_EXTERNAL_LIBRARIES}) set_target_properties(akantu PROPERTIES ${AKANTU_LIBRARY_PROPERTIES} # this contains the version COMPILE_FLAGS "${_cxx_flags}" + ) if(NOT CMAKE_VERSION VERSION_LESS 3.1) package_get_all_features_public(_PUBLIC_features) package_get_all_features_private(_PRIVATE_features) foreach(_type PRIVATE PUBLIC) if(_${_type}_features) target_compile_features(akantu ${_type} ${_${_type}_features}) endif() endforeach() else() set_target_properties(akantu PROPERTIES CXX_STANDARD 14 ) endif() package_get_all_extra_dependencies(_extra_target_dependencies) if(_extra_target_dependencies) # This only adding todo: find a solution for when a dependency was add the is removed... add_dependencies(akantu ${_extra_target_dependencies}) endif() package_get_all_export_list(AKANTU_EXPORT_LIST) list(APPEND AKANTU_EXPORT_LIST akantu) # TODO separate public from private headers install(TARGETS akantu EXPORT ${AKANTU_TARGETS_EXPORT} LIBRARY DESTINATION lib COMPONENT lib ARCHIVE DESTINATION lib COMPONENT lib RUNTIME DESTINATION bin COMPONENT bin PUBLIC_HEADER DESTINATION include/akantu/ COMPONENT dev ) if("${AKANTU_TARGETS_EXPORT}" STREQUAL "AkantuTargets") install(EXPORT AkantuTargets DESTINATION share/cmake/${PROJECT_NAME} COMPONENT dev) #Export for build tree export(EXPORT AkantuTargets FILE "${CMAKE_BINARY_DIR}/AkantuTargets.cmake") export(PACKAGE Akantu) endif() # print out the list of materials generate_material_list() register_target_to_tidy(akantu) diff --git a/src/common/aka_common.cc b/src/common/aka_common.cc index 90bea4a96..d10b593ad 100644 --- a/src/common/aka_common.cc +++ b/src/common/aka_common.cc @@ -1,155 +1,154 @@ /** * @file aka_common.cc * * @author Aurelia Isabel Cuba Ramos <aurelia.cubaramos@epfl.ch> * @author Nicolas Richart <nicolas.richart@epfl.ch> * * @date creation: Mon Jun 14 2010 * @date last modification: Tue Jan 19 2016 * * @brief Initialization of global variables * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #include "aka_common.hh" #include "aka_static_memory.hh" #include "communicator.hh" #include "aka_random_generator.hh" #include "parser.hh" #include "cppargparse.hh" #include "communication_tag.hh" /* -------------------------------------------------------------------------- */ #include <ctime> /* -------------------------------------------------------------------------- */ namespace akantu { /* -------------------------------------------------------------------------- */ void initialize(int & argc, char **& argv) { AKANTU_DEBUG_IN(); initialize("", argc, argv); AKANTU_DEBUG_OUT(); } /* -------------------------------------------------------------------------- */ void initialize(const std::string & input_file, int & argc, char **& argv) { AKANTU_DEBUG_IN(); StaticMemory::getStaticMemory(); Communicator & comm = Communicator::getStaticCommunicator(argc, argv); Tag::setMaxTag(comm.getMaxTag()); debug::debugger.setParallelContext(comm.whoAmI(), comm.getNbProc()); debug::setDebugLevel(dblError); static_argparser.setParallelContext(comm.whoAmI(), comm.getNbProc()); static_argparser.setExternalExitFunction(debug::exit); static_argparser.addArgument("--aka_input_file", "Akantu's input file", 1, cppargparse::_string, std::string()); static_argparser.addArgument( "--aka_debug_level", std::string("Akantu's overall debug level") + std::string(" (0: error, 1: exceptions, 4: warnings, 5: info, ..., " "100: dump") + std::string(" more info on levels can be foind in aka_error.hh)"), 1, cppargparse::_integer, int(dblWarning)); static_argparser.addArgument( "--aka_print_backtrace", "Should Akantu print a backtrace in case of error", 0, cppargparse::_boolean, false, true); static_argparser.parse(argc, argv, cppargparse::_remove_parsed); std::string infile = static_argparser["aka_input_file"]; if (infile == "") infile = input_file; - debug::debugger.printBacktrace(static_argparser["aka_print_backtrace"]); if ("" != infile) { readInputFile(infile); } long int seed; try { seed = static_parser.getParameter("seed", _ppsc_current_scope); } catch (debug::Exception &) { seed = time(nullptr); } seed *= (comm.whoAmI() + 1); RandomGenerator<UInt>::seed(seed); int dbl_level = static_argparser["aka_debug_level"]; debug::setDebugLevel(DebugLevel(dbl_level)); AKANTU_DEBUG_INFO("Random seed set to " << seed); std::atexit(finalize); AKANTU_DEBUG_OUT(); } /* -------------------------------------------------------------------------- */ void finalize() { AKANTU_DEBUG_IN(); // if (StaticCommunicator::isInstantiated()) { // StaticCommunicator & comm = StaticCommunicator::getStaticCommunicator(); // delete &comm; // } if (StaticMemory::isInstantiated()) { delete &(StaticMemory::getStaticMemory()); } AKANTU_DEBUG_OUT(); } /* -------------------------------------------------------------------------- */ void readInputFile(const std::string & input_file) { static_parser.parse(input_file); } /* -------------------------------------------------------------------------- */ cppargparse::ArgumentParser & getStaticArgumentParser() { return static_argparser; } /* -------------------------------------------------------------------------- */ Parser & getStaticParser() { return static_parser; } /* -------------------------------------------------------------------------- */ const ParserSection & getUserParser() { return *(static_parser.getSubSections(ParserType::_user).first); } std::unique_ptr<Communicator> Communicator::static_communicator; } // akantu diff --git a/src/model/heat_transfer/heat_transfer_model.hh b/src/model/heat_transfer/heat_transfer_model.hh index bc1b06b62..723f6bf2b 100644 --- a/src/model/heat_transfer/heat_transfer_model.hh +++ b/src/model/heat_transfer/heat_transfer_model.hh @@ -1,340 +1,337 @@ /** * @file heat_transfer_model.hh * * @author Guillaume Anciaux <guillaume.anciaux@epfl.ch> * @author Lucas Frerot <lucas.frerot@epfl.ch> * @author Srinivasa Babu Ramisetti <srinivasa.ramisetti@epfl.ch> * @author Nicolas Richart <nicolas.richart@epfl.ch> * @author Rui Wang <rui.wang@epfl.ch> * * @date creation: Sun May 01 2011 * @date last modification: Tue Dec 08 2015 * * @brief Model of Heat Transfer * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #include "data_accessor.hh" #include "fe_engine.hh" #include "model.hh" /* -------------------------------------------------------------------------- */ #include <array> /* -------------------------------------------------------------------------- */ #ifndef __AKANTU_HEAT_TRANSFER_MODEL_HH__ #define __AKANTU_HEAT_TRANSFER_MODEL_HH__ namespace akantu { template <ElementKind kind, class IntegrationOrderFunctor> class IntegratorGauss; template <ElementKind kind> class ShapeLagrange; } namespace akantu { class HeatTransferModel : public Model, public DataAccessor<Element>, public DataAccessor<UInt> { /* ------------------------------------------------------------------------ */ /* Constructors/Destructors */ /* ------------------------------------------------------------------------ */ public: using FEEngineType = FEEngineTemplate<IntegratorGauss, ShapeLagrange>; HeatTransferModel(Mesh & mesh, UInt spatial_dimension = _all_dimensions, const ID & id = "heat_transfer_model", const MemoryID & memory_id = 0); virtual ~HeatTransferModel(); /* ------------------------------------------------------------------------ */ /* Methods */ /* ------------------------------------------------------------------------ */ protected: /// generic function to initialize everything ready for explicit dynamics void initFullImpl(const ModelOptions & options) override; /// read one material file to instantiate all the materials void readMaterials(); /// allocate all vectors void initSolver(TimeStepSolverType, NonLinearSolverType) override; /// initialize the model void initModel() override; void predictor() override; /// compute the heat flux void assembleResidual() override; /// get the type of matrix needed MatrixType getMatrixType(const ID &) override; /// callback to assemble a Matrix void assembleMatrix(const ID &) override; /// callback to assemble a lumped Matrix void assembleLumpedMatrix(const ID &) override; std::tuple<ID, TimeStepSolverType> getDefaultSolverID(const AnalysisMethod & method) override; ModelSolverOptions getDefaultSolverOptions(const TimeStepSolverType & type) const; /* ------------------------------------------------------------------------ */ /* Methods for explicit */ /* ------------------------------------------------------------------------ */ public: /// compute and get the stable time step Real getStableTimeStep(); /// compute the internal heat flux void assembleInternalHeatRate(); /// calculate the lumped capacity vector for heat transfer problem void assembleCapacityLumped(); /* ------------------------------------------------------------------------ */ /* Methods for static */ /* ------------------------------------------------------------------------ */ public: /// assemble the conductivity matrix void assembleConductivityMatrix(); /// assemble the conductivity matrix void assembleCapacity(); - /// assemble the conductivity matrix - void assembleCapacity(GhostType ghost_type); - /// compute the capacity on quadrature points void computeRho(Array<Real> & rho, ElementType type, GhostType ghost_type); private: /// calculate the lumped capacity vector for heat transfer problem (w /// ghost type) void assembleCapacityLumped(const GhostType & ghost_type); /// assemble the conductivity matrix (w/ ghost type) template <UInt dim> void assembleConductivityMatrix(const GhostType & ghost_type); /// compute the conductivity tensor for each quadrature point in an array void computeConductivityOnQuadPoints(const GhostType & ghost_type); /// compute vector k \grad T for each quadrature point void computeKgradT(const GhostType & ghost_type); /// compute the thermal energy Real computeThermalEnergyByNode(); /* ------------------------------------------------------------------------ */ /* Data Accessor inherited members */ /* ------------------------------------------------------------------------ */ public: inline UInt getNbData(const Array<Element> & elements, const SynchronizationTag & tag) const override; inline void packData(CommunicationBuffer & buffer, const Array<Element> & elements, const SynchronizationTag & tag) const override; inline void unpackData(CommunicationBuffer & buffer, const Array<Element> & elements, const SynchronizationTag & tag) override; inline UInt getNbData(const Array<UInt> & indexes, const SynchronizationTag & tag) const override; inline void packData(CommunicationBuffer & buffer, const Array<UInt> & indexes, const SynchronizationTag & tag) const override; inline void unpackData(CommunicationBuffer & buffer, const Array<UInt> & indexes, const SynchronizationTag & tag) override; /* ------------------------------------------------------------------------ */ /* Dumpable interface */ /* ------------------------------------------------------------------------ */ public: dumper::Field * createNodalFieldReal(const std::string & field_name, const std::string & group_name, bool padding_flag) override; dumper::Field * createNodalFieldBool(const std::string & field_name, const std::string & group_name, bool padding_flag) override; dumper::Field * createElementalField(const std::string & field_name, const std::string & group_name, bool padding_flag, const UInt & spatial_dimension, const ElementKind & kind) override; virtual void dump(const std::string & dumper_name); virtual void dump(const std::string & dumper_name, UInt step); virtual void dump(const std::string & dumper_name, Real time, UInt step); void dump() override; virtual void dump(UInt step); virtual void dump(Real time, UInt step); /* ------------------------------------------------------------------------ */ /* Accessors */ /* ------------------------------------------------------------------------ */ public: AKANTU_GET_MACRO(Density, density, Real); AKANTU_GET_MACRO(Capacity, capacity, Real); /// get the dimension of the system space AKANTU_GET_MACRO(SpatialDimension, spatial_dimension, UInt); /// get the current value of the time step AKANTU_GET_MACRO(TimeStep, time_step, Real); /// get the assembled heat flux AKANTU_GET_MACRO(InternalHeatRate, *internal_heat_rate, Array<Real> &); /// get the lumped capacity AKANTU_GET_MACRO(CapacityLumped, *capacity_lumped, Array<Real> &); /// get the boundary vector AKANTU_GET_MACRO(BlockedDOFs, *blocked_dofs, Array<bool> &); /// get the external heat rate vector AKANTU_GET_MACRO(ExternalHeatRate, *external_heat_rate, Array<Real> &); /// get the temperature gradient AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(TemperatureGradient, temperature_gradient, Real); /// get the conductivity on q points AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(ConductivityOnQpoints, conductivity_on_qpoints, Real); /// get the conductivity on q points AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(TemperatureOnQpoints, temperature_on_qpoints, Real); /// internal variables AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(KgradT, k_gradt_on_qpoints, Real); /// get the temperature AKANTU_GET_MACRO(Temperature, *temperature, Array<Real> &); /// get the temperature derivative AKANTU_GET_MACRO(TemperatureRate, *temperature_rate, Array<Real> &); /// get the energy denominated by thermal Real getEnergy(const std::string & energy_id, const ElementType & type, UInt index); /// get the energy denominated by thermal Real getEnergy(const std::string & energy_id); /// get the thermal energy for a given element Real getThermalEnergy(const ElementType & type, UInt index); /// get the thermal energy for a given element Real getThermalEnergy(); protected: /* ------------------------------------------------------------------------ */ FEEngine & getFEEngineBoundary(const ID & name = "") override; /* ----------------------------------------------------------------------- */ template <class iterator> void getThermalEnergy(iterator Eth, Array<Real>::const_iterator<Real> T_it, Array<Real>::const_iterator<Real> T_end) const; template <typename T> void allocNodalField(Array<T> *& array, const ID & name); /* ------------------------------------------------------------------------ */ /* Class Members */ /* ------------------------------------------------------------------------ */ private: /// number of iterations UInt n_iter; /// time step Real time_step; /// temperatures array Array<Real> * temperature{nullptr}; /// temperatures derivatives array Array<Real> * temperature_rate{nullptr}; /// increment array (@f$\delta \dot T@f$ or @f$\delta T@f$) Array<Real> * increment{nullptr}; /// the density Real density; /// the speed of the changing temperature ElementTypeMapArray<Real> temperature_gradient; /// temperature field on quadrature points ElementTypeMapArray<Real> temperature_on_qpoints; /// conductivity tensor on quadrature points ElementTypeMapArray<Real> conductivity_on_qpoints; /// vector k \grad T on quad points ElementTypeMapArray<Real> k_gradt_on_qpoints; /// external flux vector Array<Real> * external_heat_rate{nullptr}; /// residuals array Array<Real> * internal_heat_rate{nullptr}; // lumped vector Array<Real> * capacity_lumped{nullptr}; /// boundary vector Array<bool> * blocked_dofs{nullptr}; // realtime Real time; /// capacity Real capacity; // conductivity matrix Matrix<Real> conductivity; // linear variation of the conductivity (for temperature dependent // conductivity) Real conductivity_variation; // reference temperature for the interpretation of temperature variation Real T_ref; // the biggest parameter of conductivity matrix Real conductivitymax; UInt temperature_release{0}; UInt conductivity_matrix_release{0}; std::unordered_map<GhostType, bool> initial_conductivity{{_not_ghost, true}, {_ghost, true}}; std::unordered_map<GhostType, UInt> conductivity_release{{_not_ghost, 0}, {_ghost, 0}}; }; } // akantu /* -------------------------------------------------------------------------- */ /* inline functions */ /* -------------------------------------------------------------------------- */ #include "heat_transfer_model_inline_impl.cc" #endif /* __AKANTU_HEAT_TRANSFER_MODEL_HH__ */ diff --git a/src/model/solid_mechanics/solid_mechanics_model_cohesive/solid_mechanics_model_cohesive.hh b/src/model/solid_mechanics/solid_mechanics_model_cohesive/solid_mechanics_model_cohesive.hh index 024ffa970..a4f9a9d81 100644 --- a/src/model/solid_mechanics/solid_mechanics_model_cohesive/solid_mechanics_model_cohesive.hh +++ b/src/model/solid_mechanics/solid_mechanics_model_cohesive/solid_mechanics_model_cohesive.hh @@ -1,323 +1,319 @@ /** * @file solid_mechanics_model_cohesive.hh * * @author Nicolas Richart <nicolas.richart@epfl.ch> * @author Marco Vocialta <marco.vocialta@epfl.ch> * * @date creation: Tue May 08 2012 * @date last modification: Mon Dec 14 2015 * * @brief Solid mechanics model for cohesive elements * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #include "cohesive_element_inserter.hh" #include "material_selector_cohesive.hh" #include "random_internal_field.hh" // included to have the specialization of #include "solid_mechanics_model.hh" #include "solid_mechanics_model_event_handler.hh" // ParameterTyped::operator Real() /* -------------------------------------------------------------------------- */ #ifndef __AKANTU_SOLID_MECHANICS_MODEL_COHESIVE_HH__ #define __AKANTU_SOLID_MECHANICS_MODEL_COHESIVE_HH__ /* -------------------------------------------------------------------------- */ namespace akantu { class FacetSynchronizer; class FacetStressSynchronizer; class ElementSynchronizer; } // namespace akantu namespace akantu { /* -------------------------------------------------------------------------- */ struct FacetsCohesiveIntegrationOrderFunctor { template <ElementType type, ElementType cohesive_type = CohesiveFacetProperty<type>::cohesive_type> struct _helper { static constexpr int get() { return ElementClassProperty<cohesive_type>::polynomial_degree; } }; template <ElementType type> struct _helper<type, _not_defined> { static constexpr int get() { return ElementClassProperty<type>::polynomial_degree; } }; template <ElementType type> static inline constexpr int getOrder() { return _helper<type>::get(); } }; /* -------------------------------------------------------------------------- */ /* Solid Mechanics Model for Cohesive elements */ /* -------------------------------------------------------------------------- */ class SolidMechanicsModelCohesive : public SolidMechanicsModel, public SolidMechanicsModelEventHandler { /* ------------------------------------------------------------------------ */ /* Constructors/Destructors */ /* ------------------------------------------------------------------------ */ public: class NewCohesiveNodesEvent : public NewNodesEvent { public: AKANTU_GET_MACRO_NOT_CONST(OldNodesList, old_nodes, Array<UInt> &); AKANTU_GET_MACRO(OldNodesList, old_nodes, const Array<UInt> &); protected: Array<UInt> old_nodes; }; using MyFEEngineCohesiveType = FEEngineTemplate<IntegratorGauss, ShapeLagrange, _ek_cohesive>; using MyFEEngineFacetType = FEEngineTemplate<IntegratorGauss, ShapeLagrange, _ek_regular, FacetsCohesiveIntegrationOrderFunctor>; SolidMechanicsModelCohesive(Mesh & mesh, UInt spatial_dimension = _all_dimensions, const ID & id = "solid_mechanics_model_cohesive", const MemoryID & memory_id = 0); ~SolidMechanicsModelCohesive() override; /* ------------------------------------------------------------------------ */ /* Methods */ /* ------------------------------------------------------------------------ */ protected: /// initialize the cohesive model void initFullImpl(const ModelOptions & options) override; public: /// set the value of the time step void setTimeStep(Real time_step, const ID & solver_id = "") override; /// assemble the residual for the explicit scheme void assembleInternalForces() override; /// function to perform a stress check on each facet and insert /// cohesive elements if needed (returns the number of new cohesive /// elements) UInt checkCohesiveStress(); /// interpolate stress on facets void interpolateStress(); - - /// limit the cohesive element insertion to a given area - void limitInsertion(BC::Axis axis, Real first_limit, Real second_limit); - /// update automatic insertion after a change in the element inserter void updateAutomaticInsertion(); /// insert intrinsic cohesive elements void insertIntrinsicElements(); // template <SolveConvergenceMethod cmethod, SolveConvergenceCriteria // criteria> bool solveStepCohesive(Real tolerance, Real & error, UInt // max_iteration = 100, // bool load_reduction = false, // Real tol_increase_factor = 1.0, // bool do_not_factorize = false); protected: /// initialize stress interpolation void initStressInterpolation(); /// initialize the model void initModel() override; /// initialize cohesive material void initMaterials() override; /// init facet filters for cohesive materials void initFacetFilter(); // synchronize facets physical data before insertion along physical surfaces void synchronizeInsertionData(); /// function to print the contain of the class void printself(std::ostream & stream, int indent = 0) const override; private: /// initialize cohesive material with extrinsic insertion void initExtrinsicMaterials(); /// initialize cohesive material with intrinsic insertion void initIntrinsicMaterials(); /// insert cohesive elements along a given physical surface of the mesh void insertElementsFromMeshData(const std::string & physical_name); /// initialize completely the model for extrinsic elements void initAutomaticInsertion(); /// compute facets' normals void computeNormals(); /// resize facet stress void resizeFacetStress(); /// init facets_check array void initFacetsCheck(); /* ------------------------------------------------------------------------ */ /* Mesh Event Handler inherited members */ /* ------------------------------------------------------------------------ */ protected: void onNodesAdded(const Array<UInt> & nodes_list, const NewNodesEvent & event) override; void onElementsAdded(const Array<Element> & nodes_list, const NewElementsEvent & event) override; /* ------------------------------------------------------------------------ */ /* SolidMechanicsModelEventHandler inherited members */ /* ------------------------------------------------------------------------ */ public: void onEndSolveStep(const AnalysisMethod & method) override; /* ------------------------------------------------------------------------ */ /* Dumpable interface */ /* ------------------------------------------------------------------------ */ public: void onDump() override; void addDumpGroupFieldToDumper(const std::string & dumper_name, const std::string & field_id, const std::string & group_name, const ElementKind & element_kind, bool padding_flag) override; public: /// register the tags associated with the parallel synchronizer for /// cohesive elements // void initParallel(MeshPartition * partition, // DataAccessor * data_accessor = NULL, // bool extrinsic = false); protected: void synchronizeGhostFacetsConnectivity(); void updateCohesiveSynchronizers(); void updateFacetStressSynchronizer(); /* ------------------------------------------------------------------------ */ /* Data Accessor inherited members */ /* ------------------------------------------------------------------------ */ public: UInt getNbData(const Array<Element> & elements, const SynchronizationTag & tag) const override; void packData(CommunicationBuffer & buffer, const Array<Element> & elements, const SynchronizationTag & tag) const override; void unpackData(CommunicationBuffer & buffer, const Array<Element> & elements, const SynchronizationTag & tag) override; protected: UInt getNbQuadsForFacetCheck(const Array<Element> & elements) const; template <typename T> void packFacetStressDataHelper(const ElementTypeMapArray<T> & data_to_pack, CommunicationBuffer & buffer, const Array<Element> & elements) const; template <typename T> void unpackFacetStressDataHelper(ElementTypeMapArray<T> & data_to_unpack, CommunicationBuffer & buffer, const Array<Element> & elements) const; template <typename T, bool pack_helper> void packUnpackFacetStressDataHelper(ElementTypeMapArray<T> & data_to_pack, CommunicationBuffer & buffer, const Array<Element> & element) const; /* ------------------------------------------------------------------------ */ /* Accessors */ /* ------------------------------------------------------------------------ */ public: /// get facet mesh AKANTU_GET_MACRO(MeshFacets, mesh.getMeshFacets(), const Mesh &); /// get stress on facets vector AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(StressOnFacets, facet_stress, Real); /// get facet material AKANTU_GET_MACRO_BY_ELEMENT_TYPE(FacetMaterial, facet_material, UInt); /// get facet material AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(FacetMaterial, facet_material, UInt); /// get facet material AKANTU_GET_MACRO(FacetMaterial, facet_material, const ElementTypeMapArray<UInt> &); /// @todo THIS HAS TO BE CHANGED AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(Tangents, tangents, Real); /// get element inserter AKANTU_GET_MACRO_NOT_CONST(ElementInserter, *inserter, CohesiveElementInserter &); /// get is_extrinsic boolean AKANTU_GET_MACRO(IsExtrinsic, is_extrinsic, bool); /// get cohesive elements synchronizer AKANTU_GET_MACRO(CohesiveSynchronizer, *cohesive_synchronizer, const ElementSynchronizer &); /* ------------------------------------------------------------------------ */ /* Class Members */ /* ------------------------------------------------------------------------ */ private: /// @todo store tangents when normals are computed: ElementTypeMapArray<Real> tangents; /// stress on facets on the two sides by quadrature point ElementTypeMapArray<Real> facet_stress; /// material to use if a cohesive element is created on a facet ElementTypeMapArray<UInt> facet_material; bool is_extrinsic; /// cohesive element inserter std::unique_ptr<CohesiveElementInserter> inserter; /// facet stress synchronizer std::unique_ptr<ElementSynchronizer> facet_stress_synchronizer; /// cohesive elements synchronizer std::unique_ptr<ElementSynchronizer> cohesive_synchronizer; /// global connectivity ElementTypeMapArray<UInt> * global_connectivity; }; } // namespace akantu #include "solid_mechanics_model_cohesive_inline_impl.cc" #endif /* __AKANTU_SOLID_MECHANICS_MODEL_COHESIVE_HH__ */ diff --git a/src/model/structural_mechanics/structural_mechanics_model.hh b/src/model/structural_mechanics/structural_mechanics_model.hh index 8ec1f8739..fcb036768 100644 --- a/src/model/structural_mechanics/structural_mechanics_model.hh +++ b/src/model/structural_mechanics/structural_mechanics_model.hh @@ -1,334 +1,327 @@ /** * @file structural_mechanics_model.hh * * @author Fabian Barras <fabian.barras@epfl.ch> * @author Sébastien Hartmann <sebastien.hartmann@epfl.ch> * @author Nicolas Richart <nicolas.richart@epfl.ch> * @author Damien Spielmann <damien.spielmann@epfl.ch> * * @date creation: Fri Jul 15 2011 * @date last modification: Thu Jan 21 2016 * * @brief Particular implementation of the structural elements in the * StructuralMechanicsModel * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #include "aka_named_argument.hh" #include "boundary_condition.hh" #include "model.hh" /* -------------------------------------------------------------------------- */ #ifndef __AKANTU_STRUCTURAL_MECHANICS_MODEL_HH__ #define __AKANTU_STRUCTURAL_MECHANICS_MODEL_HH__ /* -------------------------------------------------------------------------- */ namespace akantu { class Material; class MaterialSelector; class DumperIOHelper; class NonLocalManager; template <ElementKind kind, class IntegrationOrderFunctor> class IntegratorGauss; template <ElementKind kind> class ShapeStructural; } // namespace akantu namespace akantu { struct StructuralMaterial { Real E{0}; Real A{1}; Real I{0}; Real Iz{0}; Real Iy{0}; Real GJ{0}; Real rho{0}; Real t{0}; Real nu{0}; }; class StructuralMechanicsModel : public Model { /* ------------------------------------------------------------------------ */ /* Constructors/Destructors */ /* ------------------------------------------------------------------------ */ public: using MyFEEngineType = FEEngineTemplate<IntegratorGauss, ShapeStructural, _ek_structural>; StructuralMechanicsModel(Mesh & mesh, UInt spatial_dimension = _all_dimensions, const ID & id = "structural_mechanics_model", const MemoryID & memory_id = 0); virtual ~StructuralMechanicsModel(); /// Init full model void initFullImpl(const ModelOptions & options) override; /// Init boundary FEEngine void initFEEngineBoundary() override; /* ------------------------------------------------------------------------ */ /* Virtual methods from SolverCallback */ /* ------------------------------------------------------------------------ */ /// get the type of matrix needed MatrixType getMatrixType(const ID &) override; /// callback to assemble a Matrix void assembleMatrix(const ID &) override; /// callback to assemble a lumped Matrix void assembleLumpedMatrix(const ID &) override; /// callback to assemble the residual (rhs) void assembleResidual() override; /* ------------------------------------------------------------------------ */ /* Virtual methods from MeshEventHandler */ /* ------------------------------------------------------------------------ */ /// function to implement to react on akantu::NewNodesEvent void onNodesAdded(const Array<UInt> & nodes_list, const NewNodesEvent & event) override; /// function to implement to react on akantu::RemovedNodesEvent void onNodesRemoved(const Array<UInt> & nodes_list, const Array<UInt> & new_numbering, const RemovedNodesEvent & event) override; /// function to implement to react on akantu::NewElementsEvent void onElementsAdded(const Array<Element> & elements_list, const NewElementsEvent & event) override; /// function to implement to react on akantu::RemovedElementsEvent void onElementsRemoved(const Array<Element> & elements_list, const ElementTypeMapArray<UInt> & new_numbering, const RemovedElementsEvent & event) override; /// function to implement to react on akantu::ChangedElementsEvent void onElementsChanged(const Array<Element> & old_elements_list, const Array<Element> & new_elements_list, const ElementTypeMapArray<UInt> & new_numbering, const ChangedElementsEvent & event) override; /* ------------------------------------------------------------------------ */ /* Virtual methods from Model */ /* ------------------------------------------------------------------------ */ protected: /// get some default values for derived classes std::tuple<ID, TimeStepSolverType> getDefaultSolverID(const AnalysisMethod & method) override; ModelSolverOptions getDefaultSolverOptions(const TimeStepSolverType & type) const override; /* ------------------------------------------------------------------------ */ /* Methods */ /* ------------------------------------------------------------------------ */ void initSolver(TimeStepSolverType, NonLinearSolverType) override; /// initialize the model void initModel() override; /// compute the stresses per elements void computeStresses(); /// assemble the stiffness matrix void assembleStiffnessMatrix(); /// assemble the mass matrix for consistent mass resolutions void assembleMass(); /// update the residual vector void updateResidual(); void computeRotationMatrix(const ElementType & type); protected: /// compute Rotation Matrices template <const ElementType type> void computeRotationMatrix(__attribute__((unused)) Array<Real> & rotations) {} /* ------------------------------------------------------------------------ */ /* Mass (structural_mechanics_model_mass.cc) */ /* ------------------------------------------------------------------------ */ /// assemble the mass matrix for either _ghost or _not_ghost elements void assembleMass(GhostType ghost_type); /// computes rho void computeRho(Array<Real> & rho, ElementType type, GhostType ghost_type); /// finish the computation of residual to solve in increment void updateResidualInternal(); /* ------------------------------------------------------------------------ */ private: template <ElementType type> void assembleStiffnessMatrix(); template <ElementType type> void assembleMass(); template <ElementType type> void computeStressOnQuad(); template <ElementType type> void computeTangentModuli(Array<Real> & tangent_moduli); /* ------------------------------------------------------------------------ */ /* Dumpable interface */ /* ------------------------------------------------------------------------ */ public: virtual dumper::Field * createNodalFieldReal(const std::string & field_name, const std::string & group_name, bool padding_flag); virtual dumper::Field * createNodalFieldBool(const std::string & field_name, const std::string & group_name, bool padding_flag); virtual dumper::Field * createElementalField(const std::string & field_name, const std::string & group_name, bool padding_flag, const ElementKind & kind, const std::string & fe_engine_id = ""); /* ------------------------------------------------------------------------ */ /* Accessors */ /* ------------------------------------------------------------------------ */ public: /// set the value of the time step // void setTimeStep(Real time_step, const ID & solver_id = "") override; /// return the dimension of the system space AKANTU_GET_MACRO(SpatialDimension, spatial_dimension, UInt); /// get the StructuralMechanicsModel::displacement vector AKANTU_GET_MACRO(Displacement, *displacement_rotation, Array<Real> &); /// get the StructuralMechanicsModel::velocity vector AKANTU_GET_MACRO(Velocity, *velocity, Array<Real> &); /// get the StructuralMechanicsModel::acceleration vector, updated /// by /// StructuralMechanicsModel::updateAcceleration AKANTU_GET_MACRO(Acceleration, *acceleration, Array<Real> &); /// get the StructuralMechanicsModel::external_force vector AKANTU_GET_MACRO(ExternalForce, *external_force_momentum, Array<Real> &); /// get the StructuralMechanicsModel::internal_force vector (boundary forces) AKANTU_GET_MACRO(InternalForce, *internal_force_momentum, Array<Real> &); /// get the StructuralMechanicsModel::boundary vector AKANTU_GET_MACRO(BlockedDOFs, *blocked_dofs, Array<bool> &); AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(RotationMatrix, rotation_matrix, Real); AKANTU_GET_MACRO_BY_ELEMENT_TYPE_CONST(Stress, stress, Real); AKANTU_GET_MACRO_BY_ELEMENT_TYPE(ElementMaterial, element_material, UInt); AKANTU_GET_MACRO_BY_ELEMENT_TYPE(Set_ID, set_ID, UInt); void addMaterial(StructuralMaterial & material) { materials.push_back(material); } - /** - * @brief set the StructuralMechanicsModel::increment_flag to on, the - * activate the - * update of the StructuralMechanicsModel::increment vector - */ - void setIncrementFlagOn(); - const StructuralMaterial & getMaterial(const Element & element) const { return materials[element_material(element)]; } /* ------------------------------------------------------------------------ */ /* Boundaries (structural_mechanics_model_boundary.cc) */ /* ------------------------------------------------------------------------ */ public: /// Compute Linear load function set in global axis template <ElementType type> void computeForcesByGlobalTractionArray(const Array<Real> & tractions); /// Compute Linear load function set in local axis template <ElementType type> void computeForcesByLocalTractionArray(const Array<Real> & tractions); /// compute force vector from a function(x,y,momentum) that describe stresses // template <ElementType type> // void computeForcesFromFunction(BoundaryFunction in_function, // BoundaryFunctionType function_type); /* ------------------------------------------------------------------------ */ /* Class Members */ /* ------------------------------------------------------------------------ */ private: /// time step Real time_step; /// conversion coefficient form force/mass to acceleration Real f_m2a; /// displacements array Array<Real> * displacement_rotation{nullptr}; /// velocities array Array<Real> * velocity{nullptr}; /// accelerations array Array<Real> * acceleration{nullptr}; /// forces array Array<Real> * internal_force_momentum{nullptr}; /// forces array Array<Real> * external_force_momentum{nullptr}; /// lumped mass array Array<Real> * mass{nullptr}; /// boundaries array Array<bool> * blocked_dofs{nullptr}; /// stress array ElementTypeMapArray<Real> stress; ElementTypeMapArray<UInt> element_material; // Define sets of beams ElementTypeMapArray<UInt> set_ID; /// number of degre of freedom UInt nb_degree_of_freedom; // Rotation matrix ElementTypeMapArray<Real> rotation_matrix; // /// analysis method check the list in akantu::AnalysisMethod // AnalysisMethod method; /// flag defining if the increment must be computed or not bool increment_flag; /* ------------------------------------------------------------------------ */ std::vector<StructuralMaterial> materials; }; } // namespace akantu #endif /* __AKANTU_STRUCTURAL_MECHANICS_MODEL_HH__ */ diff --git a/src/synchronizer/communicator.cc b/src/synchronizer/communicator.cc index 445d78b79..83102da56 100644 --- a/src/synchronizer/communicator.cc +++ b/src/synchronizer/communicator.cc @@ -1,174 +1,180 @@ /** * @file static_communicator.cc * * @author Nicolas Richart <nicolas.richart@epfl.ch> * * @date creation: Fri Jun 18 2010 * @date last modification: Tue Jan 19 2016 * * @brief implementation of the common part of the static communicator * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #include "communicator.hh" +#if defined(AKANTU_USE_MPI) +#include "mpi_communicator_data.hh" +#endif /* -------------------------------------------------------------------------- */ namespace akantu { +#if defined(AKANTU_USE_MPI) +int MPICommunicatorData::is_externaly_initialized = 0; +#endif + UInt InternalCommunicationRequest::counter = 0; /* -------------------------------------------------------------------------- */ InternalCommunicationRequest::InternalCommunicationRequest(UInt source, UInt dest) : source(source), destination(dest) { this->id = counter++; } /* -------------------------------------------------------------------------- */ InternalCommunicationRequest::~InternalCommunicationRequest() = default; /* -------------------------------------------------------------------------- */ void InternalCommunicationRequest::printself(std::ostream & stream, int indent) const { std::string space; for (Int i = 0; i < indent; i++, space += AKANTU_INDENT) ; stream << space << "CommunicationRequest [" << std::endl; stream << space << " + id : " << id << std::endl; stream << space << " + source : " << source << std::endl; stream << space << " + destination : " << destination << std::endl; stream << space << "]" << std::endl; } /* -------------------------------------------------------------------------- */ Communicator::~Communicator() { auto * event = new FinalizeCommunicatorEvent(*this); this->sendEvent(*event); - this->barrier(); delete event; } /* -------------------------------------------------------------------------- */ Communicator & Communicator::getStaticCommunicator() { AKANTU_DEBUG_IN(); if (!static_communicator) { int nb_args = 0; char ** null = nullptr; static_communicator = std::make_unique<Communicator>(nb_args, null, private_member{}); } AKANTU_DEBUG_OUT(); return *static_communicator; } /* -------------------------------------------------------------------------- */ Communicator & Communicator::getStaticCommunicator(int & argc, char **& argv) { if (!static_communicator) static_communicator = std::make_unique<Communicator>(argc, argv, private_member{}); return getStaticCommunicator(); } } // namespace akantu #ifdef AKANTU_USE_MPI # include "communicator_mpi_inline_impl.cc" #else # include "communicator_dummy_inline_impl.cc" #endif namespace akantu { /* -------------------------------------------------------------------------- */ /* Template instantiation */ /* -------------------------------------------------------------------------- */ #define AKANTU_COMM_INSTANTIATE(T) \ template void Communicator::probe<T>(Int sender, Int tag, \ CommunicationStatus & status) const; \ template bool Communicator::asyncProbe<T>( \ Int sender, Int tag, CommunicationStatus & status) const; \ template void Communicator::sendImpl<T>( \ const T * buffer, Int size, Int receiver, Int tag, \ const CommunicationMode & mode) const; \ template void Communicator::receiveImpl<T>(T * buffer, Int size, Int sender, \ Int tag) const; \ template CommunicationRequest Communicator::asyncSendImpl<T>( \ const T * buffer, Int size, Int receiver, Int tag, \ const CommunicationMode & mode) const; \ template CommunicationRequest Communicator::asyncReceiveImpl<T>( \ T * buffer, Int size, Int sender, Int tag) const; \ template void Communicator::allGatherImpl<T>(T * values, int nb_values) \ const; \ template void Communicator::allGatherVImpl<T>(T * values, int * nb_values) \ const; \ template void Communicator::gatherImpl<T>(T * values, int nb_values, \ int root) const; \ template void Communicator::gatherImpl<T>( \ T * values, int nb_values, T * gathered, int nb_gathered) const; \ template void Communicator::gatherVImpl<T>(T * values, int * nb_values, \ int root) const; \ template void Communicator::broadcastImpl<T>(T * values, int nb_values, \ int root) const; \ template void Communicator::allReduceImpl<T>( \ T * values, int nb_values, const SynchronizerOperation & op) const #define MIN_MAX_REAL SCMinMaxLoc<Real, int> AKANTU_COMM_INSTANTIATE(bool); AKANTU_COMM_INSTANTIATE(Real); AKANTU_COMM_INSTANTIATE(UInt); AKANTU_COMM_INSTANTIATE(Int); AKANTU_COMM_INSTANTIATE(char); AKANTU_COMM_INSTANTIATE(NodeType); AKANTU_COMM_INSTANTIATE(MIN_MAX_REAL); #if AKANTU_INTEGER_SIZE > 4 AKANTU_COMM_INSTANTIATE(int); #endif // template void Communicator::send<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * buffer, Int size, Int receiver, Int tag); // template void Communicator::receive<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * buffer, Int size, Int sender, Int tag); // template CommunicationRequest // Communicator::asyncSend<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * buffer, Int size, Int receiver, Int tag); // template CommunicationRequest // Communicator::asyncReceive<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * buffer, Int size, Int sender, Int tag); // template void Communicator::probe<SCMinMaxLoc<Real, int>>( // Int sender, Int tag, CommunicationStatus & status); // template void Communicator::allGather<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int nb_values); // template void Communicator::allGatherV<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int * nb_values); // template void Communicator::gather<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int nb_values, int root); // template void Communicator::gatherV<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int * nb_values, int root); // template void Communicator::broadcast<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int nb_values, int root); // template void Communicator::allReduce<SCMinMaxLoc<Real, int>>( // SCMinMaxLoc<Real, int> * values, int nb_values, // const SynchronizerOperation & op); } // akantu diff --git a/src/synchronizer/mpi_communicator_data.hh b/src/synchronizer/mpi_communicator_data.hh index 2b0222e90..526316228 100644 --- a/src/synchronizer/mpi_communicator_data.hh +++ b/src/synchronizer/mpi_communicator_data.hh @@ -1,136 +1,134 @@ /** * @file mpi_type_wrapper.hh * * @author Nicolas Richart <nicolas.richart@epfl.ch> * * @date creation: Mon Jun 14 2010 * @date last modification: Wed Oct 07 2015 * * @brief Wrapper on MPI types to have a better separation between libraries * * @section LICENSE * * Copyright (©) 2010-2012, 2014, 2015 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 <http://www.gnu.org/licenses/>. * */ /* -------------------------------------------------------------------------- */ #if defined(__INTEL_COMPILER) //#pragma warning ( disable : 383 ) #elif defined(__clang__) // test clang to be sure that when we test for gnu it // is only gnu #elif (defined(__GNUC__) || defined(__GNUG__)) #if __cplusplus > 199711L #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" #endif #endif #include <mpi.h> #if defined(__INTEL_COMPILER) //#pragma warning ( disable : 383 ) #elif defined(__clang__) // test clang to be sure that when we test for gnu it // is only gnu #elif (defined(__GNUC__) || defined(__GNUG__)) #if __cplusplus > 199711L #pragma GCC diagnostic pop #endif #endif /* -------------------------------------------------------------------------- */ #include "communicator.hh" /* -------------------------------------------------------------------------- */ #include <unordered_map> /* -------------------------------------------------------------------------- */ #ifndef __AKANTU_MPI_TYPE_WRAPPER_HH__ #define __AKANTU_MPI_TYPE_WRAPPER_HH__ namespace akantu { class MPICommunicatorData : public CommunicatorInternalData { public: MPICommunicatorData() { - int is_initialized = false; - MPI_Initialized(&is_initialized); - if (!is_initialized) { + MPI_Initialized(&is_externaly_initialized); + if (!is_externaly_initialized) { MPI_Init(nullptr, nullptr); // valid according to the spec } MPI_Comm_create_errhandler(MPICommunicatorData::errorHandler, &error_handler); + MPI_Comm_set_errhandler(MPI_COMM_WORLD, error_handler); setMPICommunicator(MPI_COMM_WORLD); - is_externaly_initialized = is_initialized; } ~MPICommunicatorData() override { if (not is_externaly_initialized) { MPI_Finalize(); } } inline void setMPICommunicator(MPI_Comm comm) { MPI_Comm_set_errhandler(communicator, save_error_handler); communicator = comm; MPI_Comm_get_errhandler(comm, &save_error_handler); MPI_Comm_set_errhandler(comm, error_handler); } inline int rank() const { int prank; MPI_Comm_rank(communicator, &prank); return prank; } inline int size() const { int psize; MPI_Comm_size(communicator, &psize); return psize; } inline MPI_Comm getMPICommunicator() const { return communicator; } inline int getMaxTag() const { int flag; int * value; MPI_Comm_get_attr(communicator, MPI_TAG_UB, &value, &flag); AKANTU_DEBUG_ASSERT(flag, "No attribute MPI_TAG_UB."); return *value; } private: MPI_Comm communicator{MPI_COMM_WORLD}; MPI_Errhandler save_error_handler{MPI_ERRORS_ARE_FATAL}; - bool is_externaly_initialized{false}; - + static int is_externaly_initialized; /* ------------------------------------------------------------------------ */ MPI_Errhandler error_handler; static void errorHandler(MPI_Comm * /*comm*/, int * error_code, ...) { char error_string[MPI_MAX_ERROR_STRING]; int str_len; MPI_Error_string(*error_code, error_string, &str_len); AKANTU_CUSTOM_EXCEPTION_INFO(debug::CommunicationException(), "MPI failed with the error code " << *error_code << ": \"" << error_string << "\""); } }; } // namespace akantu #endif /* __AKANTU_MPI_TYPE_WRAPPER_HH__ */ diff --git a/test/test_python_interface/test_boundary_condition_functors.py b/test/test_python_interface/test_boundary_condition_functors.py index 2cd77a3f5..1deed3e25 100644 --- a/test/test_python_interface/test_boundary_condition_functors.py +++ b/test/test_python_interface/test_boundary_condition_functors.py @@ -1,106 +1,105 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # =============================================================================== # @file test_boundary_condition_functors.py # # @author Lucas Frérot <lucas.frerot@epfl.ch> # # @date creation: Thu Feb 11 2016 # # @brief Testing the apply*BC functions in python interface # # @section LICENSE # # Copyright (©) 2016 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 <http://www.gnu.org/licenses/>. # # =============================================================================== - +from __future__ import print_function import sys import os import numpy as np import akantu as aka ###################################################################### # Boundary conditions founctors ###################################################################### class FixedValue: """Functor for Dirichlet boundary conditions""" def __init__(self, value, axis): self.value = value axis_dict = {'x':0, 'y':1, 'z':2} self.axis = axis_dict[axis] def operator(self, node, flags, primal, coord): primal[self.axis] = self.value flags[self.axis] = True #--------------------------------------------------------------------- class FromStress: """Functor for Neumann boundary conditions""" def __init__(self, stress): self.stress = stress def operator(self, quad_point, dual, coord, normals): dual[:] = np.dot(self.stress,normals) ###################################################################### def main(): os.system('gmsh -order 2 -2 -o mesh_dcb_2d.msh mesh_dcb_2d.geo') - print "" aka.initialize("input_test.dat") mesh = aka.Mesh(2) mesh.read('mesh_dcb_2d.msh') mesh.createGroupsFromStringMeshData("physical_names") model = aka.SolidMechanicsModel(mesh, 2) model.initFull() model.applyDirichletBC(FixedValue(0.0, 'x'), "edge") stress = np.array([[1, 0], [0, 0]]) blocked_nodes = mesh.getElementGroup("edge").getNodes().flatten() boundary = model.getBlockedDOFs() # Testing that nodes are correctly blocked for n in blocked_nodes: if not boundary[n, 0]: return -1 boundary.fill(False) model.applyNeumannBC(FromStress(stress), "edge") force = model.getForce() # Checking that nodes have a force in the correct direction for n in blocked_nodes: if not force[n, 0] > 0: return -1 aka.finalize() return 0 if __name__ == "__main__": sys.exit(main()) diff --git a/test/test_python_interface/test_mesh_interface.py b/test/test_python_interface/test_mesh_interface.py index 6cf2f5a5c..d4e600658 100644 --- a/test/test_python_interface/test_mesh_interface.py +++ b/test/test_python_interface/test_mesh_interface.py @@ -1,56 +1,55 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # =============================================================================== # @file test_mesh_interface.py # # @author Lucas Frérot <lucas.frerot@epfl.ch> # # @date creation: Mon Feb 01 2016 # # @brief Testing the Mesh python interface # # @section LICENSE # # Copyright (©) 2016 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 <http://www.gnu.org/licenses/>. # # =============================================================================== - +from __future__ import print_function import sys import os import akantu as aka def main(): os.system('gmsh -order 2 -2 -o mesh_dcb_2d.msh mesh_dcb_2d.geo') - print "" aka.initialize() mesh = aka.Mesh(2) mesh.read('mesh_dcb_2d.msh') # Tests the getNbElement() function if mesh.getNbElement(aka._quadrangle_8) != mesh.getNbElementByDimension(2): - print "Number of elements wrong, should be {}".format(mesh.getNbElementByDimension(2)) + print("Number of elements wrong, should be {}".format(mesh.getNbElementByDimension(2))) return -1 # TODO test the other functions in Mesh aka.finalize() return 0 if __name__ == "__main__": sys.exit(main()) diff --git a/test/test_python_interface/test_multiple_init.py b/test/test_python_interface/test_multiple_init.py index 709a9e0c7..9ffc14a5b 100755 --- a/test/test_python_interface/test_multiple_init.py +++ b/test/test_python_interface/test_multiple_init.py @@ -1,58 +1,57 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # =============================================================================== # @file test_multiple_init.py # # @author Fabian Barras <fabian.barras@epfl.ch> # # @date creation: Tue Jan 5 2016 # # @brief Testing multiple initialize calls through Python # # @section LICENSE # # Copyright (©) 2014 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 <http://www.gnu.org/licenses/>. # # =============================================================================== - +from __future__ import print_function import sys import os import akantu as aka os.system('gmsh -order 2 -2 -o mesh_dcb_2d.msh mesh_dcb_2d.geo') aka.initialize('input_test.dat') -print 'First initialisation' +print('First initialisation') mesh = aka.Mesh(2) mesh.read('mesh_dcb_2d.msh') model = aka.SolidMechanicsModel(mesh) model.initFull(aka.SolidMechanicsModelOptions(aka._static)) del model del mesh -print 'Second initialisation' +print('Second initialisation') mesh = aka.Mesh(2) mesh.read('mesh_dcb_2d.msh') model = aka.SolidMechanicsModel(mesh) model.initFull(aka.SolidMechanicsModelOptions(aka._static)) del model del mesh -aka.finalize() -print 'All right' +print('All right')