diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index 04b727722..9b26ccf3a 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -1,301 +1,305 @@ #=============================================================================== # @file CMakeLists.txt # # @author Nicolas Richart # # @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 . # #=============================================================================== #=============================================================================== # 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 2.7 REQUIRED) mark_as_advanced(SWIG_EXECUTABLE) package_get_all_include_directories( AKANTU_LIBRARY_INCLUDE_DIRS ) package_get_all_external_informations( AKANTU_EXTERNAL_INCLUDE_DIR AKANTU_EXTERNAL_LIBRARIES ) 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}") - string(STRIP "${AKANTU_EXTRA_CXX_FLAGS}" _tmp_flags) - string(REGEX REPLACE " +" "', '" _flags "${_tmp_flags} -Wno-maybe-uninitialized") + 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(_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'], + libraries=['akantu${CMAKE_DEBUG_POSTFIX}'], library_dirs=['${PROJECT_BINARY_DIR}/src'], - extra_compile_args=['${_flags}'])], + extra_compile_args=['${_flags}', '-std=c++14'])], ) ") 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 # ) install(CODE "execute_process( COMMAND ${PYTHON_EXECUTABLE} ./setup.py ${_quiet} install --prefix=${AKANTU_PYTHON_INSTALL_PREFIX} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} )" COMPONENT python) package_declare_extra_files_to_package(python_interface ${_deps} ${PROJECT_SOURCE_DIR}/python/${AKANTU_SWIG_MODULES}) endif() diff --git a/python/swig/aka_array.i b/python/swig/aka_array.i index 117f261fb..5012a68a5 100644 --- a/python/swig/aka_array.i +++ b/python/swig/aka_array.i @@ -1,248 +1,251 @@ /** * @file aka_array.i * * @author Guillaume Anciaux * @author Nicolas Richart * * @date creation: Fri Dec 12 2014 * @date last modification: Wed Nov 11 2015 * * @brief wrapper for arrays * * @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 . * */ %{ #define SWIG_FILE_WITH_INIT #include "aka_array.hh" #include "aka_types.hh" %} %include "typemaps.i" namespace akantu { %ignore Array::operator=; %ignore Array::operator[]; %ignore Array::operator(); %ignore Array::set; %ignore Array::begin; %ignore Array::end; %ignore Array::begin_reinterpret; %ignore Array::end_reinterpret; + %ignore ArrayBase::getSize; + %ignore Array::operator*=; + %ignore Array::operator*; }; %include "aka_array.hh" namespace akantu { %ignore TensorProxy::operator=; %ignore TensorProxy::operator[]; %ignore TensorProxy::operator(); %ignore Tensor3Proxy::operator=; %ignore Tensor3Proxy::operator[]; %ignore Tensor3Proxy::operator(); %ignore TensorStorage::operator=; %ignore TensorStorage::operator[]; %ignore TensorStorage::operator(); %ignore VectorProxy::operator=; %ignore VectorProxy::operator[]; %ignore VectorProxy::operator(); %ignore MatrixProxy::operator=; %ignore MatrixProxy::operator[]; %ignore MatrixProxy::operator(); %ignore Matrix::operator=; %ignore Matrix::operator[]; %ignore Matrix::operator(); %ignore Tensor3::operator=; %ignore Tensor3::operator[]; %ignore Tensor3::operator(); %ignore Vector::operator=; %ignore Vector::operator[]; %ignore Vector::operator(); %ignore Vector::solve; }; %include "aka_types.hh" namespace akantu { %template(RArray) Array; %template(UArray) Array; %template(BArray) Array; %template(RVector) Vector; }; %include "numpy.i" %init %{ import_array(); %} %inline %{ namespace akantu{ template class ArrayForPython : public Array{ public: ArrayForPython(T * wrapped_memory, - UInt size = 0, + UInt size_ = 0, UInt nb_component = 1, const ID & id = "") : Array(0,nb_component,id){ this->values = wrapped_memory; - this->size = size; + this->size_ = size_; }; ~ArrayForPython(){ this->values = NULL; }; void resize(UInt new_size){ - AKANTU_DEBUG_ASSERT(this->size == new_size,"cannot resize a temporary vector"); + AKANTU_DEBUG_ASSERT(this->size_ == new_size,"cannot resize a temporary vector"); } }; } template int getPythonDataTypeCode(){ AKANTU_EXCEPTION("undefined type");} template <> int getPythonDataTypeCode(){ int data_typecode = NPY_NOTYPE; size_t s = sizeof(bool); switch(s) { case 1: data_typecode = NPY_BOOL; break; case 2: data_typecode = NPY_UINT16; break; case 4: data_typecode = NPY_UINT32; break; case 8: data_typecode = NPY_UINT64; break; } return data_typecode; } template <> int getPythonDataTypeCode(){return NPY_DOUBLE;} template <> int getPythonDataTypeCode(){return NPY_LONGDOUBLE;} template <> int getPythonDataTypeCode(){return NPY_FLOAT;} template <> int getPythonDataTypeCode(){ int data_typecode = NPY_NOTYPE; size_t s = sizeof(unsigned long); switch(s) { case 2: data_typecode = NPY_UINT16; break; case 4: data_typecode = NPY_UINT32; break; case 8: data_typecode = NPY_UINT64; break; } return data_typecode; } template <> int getPythonDataTypeCode(){ int data_typecode = NPY_NOTYPE; size_t s = sizeof(akantu::UInt); switch(s) { case 2: data_typecode = NPY_UINT16; break; case 4: data_typecode = NPY_UINT32; break; case 8: data_typecode = NPY_UINT64; break; } return data_typecode; } template <> int getPythonDataTypeCode(){ int data_typecode = NPY_NOTYPE; size_t s = sizeof(int); switch(s) { case 2: data_typecode = NPY_INT16; break; case 4: data_typecode = NPY_INT32; break; case 8: data_typecode = NPY_INT64; break; } return data_typecode; } int getSizeOfPythonType(int type_num){ switch (type_num){ case NPY_INT16 : return 2;break; case NPY_UINT16: return 2;break; case NPY_INT32 : return 4;break; case NPY_UINT32: return 4;break; case NPY_INT64 : return 8;break; case NPY_UINT64: return 8;break; case NPY_FLOAT: return sizeof(float);break; case NPY_DOUBLE: return sizeof(double);break; case NPY_LONGDOUBLE: return sizeof(long double);break; } return 0; } std::string getPythonTypeName(int type_num){ switch (type_num){ case NPY_INT16 : return "NPY_INT16" ;break; case NPY_UINT16: return "NPY_UINT16";break; case NPY_INT32 : return "NPY_INT32" ;break; case NPY_UINT32: return "NPY_UINT32";break; case NPY_INT64 : return "NPY_INT64" ;break; case NPY_UINT64: return "NPY_UINT64";break; case NPY_FLOAT: return "NPY_FLOAT" ;break; case NPY_DOUBLE: return "NPY_DOUBLE";break; case NPY_LONGDOUBLE: return "NPY_LONGDOUBLE";break; } return 0; } template void checkDataType(int type_num){ AKANTU_DEBUG_ASSERT(type_num == getPythonDataTypeCode(), "incompatible types between numpy and input function: " << type_num << " != " << getPythonDataTypeCode() << std::endl << getSizeOfPythonType(type_num) << " != " << sizeof(T) << std::endl << "The numpy array is of type " << getPythonTypeName(type_num)); } %} %define %akantu_array_typemaps(DATA_TYPE) %typemap(out, fragment="NumPy_Fragments") (akantu::Array< DATA_TYPE > &) { int data_typecode = getPythonDataTypeCode< DATA_TYPE >(); - npy_intp dims[2] = {npy_intp($1->getSize()), npy_intp($1->getNbComponent())}; + npy_intp dims[2] = {npy_intp($1->size()), npy_intp($1->getNbComponent())}; PyObject* obj = PyArray_SimpleNewFromData(2, dims, data_typecode, $1->storage()); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result, obj); } %typemap(in) akantu::Array< DATA_TYPE > & { if (!PyArray_Check($input)) { AKANTU_EXCEPTION("incompatible input which is not a numpy"); } else { PyArray_Descr * numpy_type = (PyArray_Descr*)PyArray_DESCR((PyArrayObject*)$input); int type_num = numpy_type->type_num; checkDataType< DATA_TYPE >(type_num); UInt _n = PyArray_NDIM((PyArrayObject*)$input); if (_n != 2) AKANTU_EXCEPTION("incompatible numpy dimension " << _n); npy_intp * ndims = PyArray_DIMS((PyArrayObject*)$input); akantu::UInt sz = ndims[0]; akantu::UInt nb_components = ndims[1]; PyArrayIterObject *iter = (PyArrayIterObject *)PyArray_IterNew($input); if (iter == NULL) AKANTU_EXCEPTION("Python internal error"); $1 = new akantu::ArrayForPython< DATA_TYPE >((DATA_TYPE*)(iter->dataptr),sz,nb_components,"tmp_array_for_python"); } } %enddef %akantu_array_typemaps(double ) %akantu_array_typemaps(float ) %akantu_array_typemaps(unsigned int) %akantu_array_typemaps(unsigned long) %akantu_array_typemaps(int ) %akantu_array_typemaps(bool ) diff --git a/python/swig/aka_common.i b/python/swig/aka_common.i index 95984de36..239a2fbc6 100644 --- a/python/swig/aka_common.i +++ b/python/swig/aka_common.i @@ -1,124 +1,125 @@ /** * @file aka_common.i * * @author Guillaume Anciaux * @author Fabian Barras * @author Nicolas Richart * * @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 . * */ %{ - #include "aka_common.hh" - #include "aka_csr.hh" - #include "element.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 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); } } %} %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) %} %include "aka_config.hh" %include "aka_common.hh" %include "aka_element_classes_info.hh" %include "element.hh" diff --git a/python/swig/material.i b/python/swig/material.i index 904b44bfa..c1d3b152c 100644 --- a/python/swig/material.i +++ b/python/swig/material.i @@ -1,49 +1,50 @@ /** * @file material.i * * @author Nicolas Richart * * @brief material wrapper * * @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 . * */ %{ #include "solid_mechanics_model.hh" #include "material_python.hh" %} namespace akantu { %ignore Material::onNodesAdded; %ignore Material::onNodesRemoved; %ignore Material::onElementsAdded; %ignore Material::onElementsRemoved; %ignore Material::onElementsChanged; + %ignore Material::getParam; } %include "material.hh" %extend akantu::Material { Array & getArrayReal(const ID & id, const ElementType & type, const GhostType & ghost_type = _not_ghost) { return $self->getArray(id, type, ghost_type); } } diff --git a/python/swig/mesh.i b/python/swig/mesh.i index 57ede82de..e38371843 100644 --- a/python/swig/mesh.i +++ b/python/swig/mesh.i @@ -1,177 +1,177 @@ /** * @file mesh.i * * @author Guillaume Anciaux * @author Fabian Barras * @author Aurelia Isabel Cuba Ramos * @author Nicolas Richart * * @date creation: Fri Dec 12 2014 * @date last modification: Wed Jan 13 2016 * * @brief mesh wrapper * * @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 . * */ %{ #include "mesh.hh" #include "node_group.hh" #include "solid_mechanics_model.hh" -#include "dumpable_inline_impl.hh" +//#include "dumpable_inline_impl.hh" using akantu::IntegrationPoint; using akantu::Vector; using akantu::ElementTypeMapArray; using akantu::MatrixProxy; using akantu::Matrix; using akantu::UInt; using akantu::Real; using akantu::Array; using akantu::SolidMechanicsModel; %} namespace akantu { %ignore NewNodesEvent; %ignore RemovedNodesEvent; %ignore NewElementsEvent; %ignore RemovedElementsEvent; %ignore MeshEventHandler; %ignore MeshEvent< UInt >; %ignore MeshEvent< Element >; %ignore Mesh::extractNodalCoordinatesFromPBCElement; %ignore Mesh::getGroupDumer; %ignore Mesh::getFacetLocalConnectivity; %ignore Mesh::getAllFacetTypes; %ignore Mesh::getCommunicator; + %ignore GroupManager::getElementGroups; } print_self(Mesh) // Swig considers enums to be ints, and it creates a conflict with two versions of getNbElement() %rename(getNbElementByDimension) akantu::Mesh::getNbElement(const UInt spatial_dimension = _all_dimensions, const GhostType& ghost_type = _not_ghost, const ElementKind& kind = _ek_not_defined) const; %extend akantu::Mesh { void resizeMesh(UInt nb_nodes, UInt nb_element, const ElementType & type) { Array & nodes = const_cast &>($self->getNodes()); nodes.resize(nb_nodes); $self->addConnectivityType(type); Array & connectivity = const_cast &>($self->getConnectivity(type)); connectivity.resize(nb_element); } #if defined(AKANTU_COHESIVE_ELEMENT) Array & getCohesiveBarycenter(SpacialDirection dir) { UInt spatial_dimension = $self->getSpatialDimension(); ElementTypeMapArray & barycenter = $self->registerData("barycenter"); $self->initElementTypeMapArray(barycenter, 1, spatial_dimension, false, akantu::_ek_cohesive, true); akantu::ElementType type = *($self->firstType( spatial_dimension, akantu::_not_ghost, akantu::_ek_cohesive)); Vector bary(spatial_dimension); Array & bary_coh = barycenter(type); for (UInt i = 0; i < $self->getNbElement(type); ++i) { bary.clear(); $self->getBarycenter(i, type, bary.storage()); bary_coh(i) = bary(dir); } return bary_coh; } #endif } %extend akantu::GroupManager { void createGroupsFromStringMeshData(const std::string & dataset_name) { $self->createGroupsFromMeshData(dataset_name); } void createGroupsFromUIntMeshData(const std::string & dataset_name) { $self->createGroupsFromMeshData(dataset_name); } } %extend akantu::NodeGroup { akantu::Array & getGroupedNodes(akantu::Array & surface_array, Mesh & mesh) { akantu::Array group_node = $self->getNodes(); akantu::Array & full_array = mesh.getNodes(); - surface_array.resize(group_node.getSize()); + surface_array.resize(group_node.size()); - for (UInt i = 0; i < group_node.getSize(); ++i) { + for (UInt i = 0; i < group_node.size(); ++i) { for (UInt cmp = 0; cmp < full_array.getNbComponent(); ++cmp) { surface_array(i,cmp) = full_array(group_node(i),cmp); } } akantu::Array & res(surface_array); return res; } akantu::Array & getGroupedArray(akantu::Array & surface_array, akantu::SolidMechanicsModel & model, int type) { akantu::Array * full_array; switch (type) { case 0 : full_array = new akantu::Array(model.getDisplacement()); break; case 1 : full_array = new akantu::Array(model.getVelocity()); break; case 2 : full_array = new akantu::Array(model.getForce()); break; } akantu::Array group_node = $self->getNodes(); - surface_array.resize(group_node.getSize()); + surface_array.resize(group_node.size()); - for (UInt i = 0; i < group_node.getSize(); ++i) { + for (UInt i = 0; i < group_node.size(); ++i) { for (UInt cmp = 0; cmp < full_array->getNbComponent(); ++cmp) { surface_array(i,cmp) = (*full_array)(group_node(i),cmp); } } akantu::Array & res(surface_array); return res; } } %include "group_manager.hh" - %include "element_group.hh" %include "node_group.hh" %include "dumper_iohelper.hh" %include "dumpable_iohelper.hh" %include "mesh.hh" namespace akantu{ %extend Dumpable { void addDumpFieldExternalReal(const std::string & field_id, const Array & field){ $self->addDumpFieldExternal(field_id,field); } } } diff --git a/python/swig/mesh_utils.i b/python/swig/mesh_utils.i index e5984ff34..31a551364 100644 --- a/python/swig/mesh_utils.i +++ b/python/swig/mesh_utils.i @@ -1,40 +1,43 @@ /** * @file mesh_utils.i * * @author Guillaume Anciaux * @author Nicolas Richart * * @date creation: Fri Dec 12 2014 * @date last modification: Thu Jul 23 2015 * * @brief mesh_utils wrapper * * @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 . * */ -namespace akantu { - %ignore MeshPartition::getPartitions; - %ignore MeshPartition::getPartition; - %ignore MeshPartition::getGhostPartitionCSR; -} +%{ +#include "mesh_utils.hh" +%} +/* namespace akantu { */ +/* %ignore MeshPartition::getPartitions; */ +/* %ignore MeshPartition::getPartition; */ +/* %ignore MeshPartition::getGhostPartitionCSR; */ +/* } */ -%include "mesh_partition.hh" +/* %include "mesh_partition.hh" */ %include "mesh_utils.hh" diff --git a/python/swig/model.i b/python/swig/model.i index 8775f3504..d08eaa605 100644 --- a/python/swig/model.i +++ b/python/swig/model.i @@ -1,80 +1,85 @@ /** * @file model.i * * @author Guillaume Anciaux * @author Aurelia Isabel Cuba Ramos * @author Nicolas Richart * * @date creation: Fri Dec 12 2014 * @date last modification: Wed Nov 11 2015 * * @brief model wrapper * * @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 . * */ %{ #include "boundary_condition_python_functor.hh" %} namespace akantu { %ignore Model::createSynchronizerRegistry; + %ignore Model::getSynchronizerRegistry; %ignore Model::createParallelSynch; %ignore Model::getDOFSynchronizer; - //%ignore Model::getSynchronizerRegistry; %ignore Model::registerFEEngineObject; %ignore Model::unregisterFEEngineObject; %ignore Model::getFEEngineBoundary; // %ignore Model::getFEEngine; %ignore Model::getFEEngineClass; %ignore Model::getFEEngineClassBoundary; %ignore Model::setParser; - + %ignore Model::updateDataForNonLocalCriterion; %ignore IntegrationPoint::operator=; %ignore FEEngine::getNbIntegrationPoints; %ignore FEEngine::getShapes; %ignore FEEngine::getShapesDerivatives; %ignore FEEngine::getIntegrationPoints; %ignore FEEngine::getIGFEMElementTypes; %ignore FEEngine::interpolateOnIntegrationPoints(const Array &,ElementTypeMapArray &,const ElementTypeMapArray *) const; %ignore FEEngine::interpolateOnIntegrationPoints(const Array &,ElementTypeMapArray &) const; %ignore FEEngine::interpolateOnIntegrationPoints(const Array &,Array &,UInt,const ElementType&,const GhostType &,const Array< UInt > &) const; %ignore FEEngine::interpolateOnIntegrationPoints(const Array &,Array &,UInt,const ElementType&,const GhostType &) const; - + %ignore FEEngine::onNodesAdded; + %ignore FEEngine::onNodesRemoved; + %ignore FEEngine::onElementsAdded; + %ignore FEEngine::onElementsChanged; + %ignore FEEngine::onElementsRemoved; + %ignore FEEngine::elementTypes; } %include "sparse_matrix.i" %include "fe_engine.hh" %rename(FreeBoundaryDirichlet) akantu::BC::Dirichlet::FreeBoundary; %rename(FreeBoundaryNeumann) akantu::BC::Neumann::FreeBoundary; %rename(PythonBoundary) akantu::BC::Dirichlet::PythonFunctor; %include "boundary_condition_functor.hh" %include "boundary_condition.hh" %include "boundary_condition_python_functor.hh" %include "communication_buffer.hh" %include "data_accessor.hh" -%include "synchronizer.hh" -%include "synchronizer_registry.hh" +//%include "synchronizer.hh" +//%include "synchronizer_registry.hh" %include "model.hh" diff --git a/python/swig/solid_mechanics_model.i b/python/swig/solid_mechanics_model.i index f9fe96049..05b07aeb6 100644 --- a/python/swig/solid_mechanics_model.i +++ b/python/swig/solid_mechanics_model.i @@ -1,225 +1,205 @@ /** * @file solid_mechanics_model.i * * @author Guillaume Anciaux * @author Fabian Barras * @author Nicolas Richart * * @date creation: Fri Dec 12 2014 * @date last modification: Wed Jan 06 2016 * * @brief solid mechanics model wrapper * * @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 . * */ %{ #include "solid_mechanics_model.hh" #include "sparse_matrix.hh" #include "boundary_condition.hh" #include "boundary_condition_functor.hh" #include "boundary_condition_python_functor.hh" #include "material_selector.hh" #include "material_python.hh" %} namespace akantu { %ignore SolidMechanicsModel::initFEEngineBoundary; %ignore SolidMechanicsModel::initParallel; %ignore SolidMechanicsModel::initArrays; %ignore SolidMechanicsModel::initModel; %ignore SolidMechanicsModel::initPBC; ignore SolidMechanicsModel::initExplicit; %ignore SolidMechanicsModel::isExplicit; %ignore SolidMechanicsModel::updateCurrentPosition; %ignore SolidMechanicsModel::updateAcceleration; %ignore SolidMechanicsModel::updateIncrement; %ignore SolidMechanicsModel::updatePreviousDisplacement; %ignore SolidMechanicsModel::saveStressAndStrainBeforeDamage; %ignore SolidMechanicsModel::updateEnergiesAfterDamage; %ignore SolidMechanicsModel::solveLumped; %ignore SolidMechanicsModel::explicitPred; %ignore SolidMechanicsModel::explicitCorr; %ignore SolidMechanicsModel::initSolver; %ignore SolidMechanicsModel::initImplicit; %ignore SolidMechanicsModel::initialAcceleration; %ignore SolidMechanicsModel::testConvergence; %ignore SolidMechanicsModel::testConvergenceIncrement; %ignore SolidMechanicsModel::testConvergenceResidual; %ignore SolidMechanicsModel::initVelocityDampingMatrix; %ignore SolidMechanicsModel::getNbDataForElements; %ignore SolidMechanicsModel::packElementData; %ignore SolidMechanicsModel::unpackElementData; %ignore SolidMechanicsModel::getNbDataToPack; %ignore SolidMechanicsModel::getNbDataToUnpack; %ignore SolidMechanicsModel::packData; %ignore SolidMechanicsModel::unpackData; %ignore SolidMechanicsModel::setMaterialSelector; %ignore SolidMechanicsModel::getSolver; %ignore SolidMechanicsModel::getSynchronizer; %ignore Dumpable::registerExternalDumper; %ignore Material::onNodesAdded; %ignore Material::onNodesRemoved; %ignore Material::onElementsAdded; %ignore Material::onElementsRemoved; %ignore Material::onElementsChanged; } %template(SolidMechanicsBoundaryCondition) akantu::BoundaryCondition; %include "dumpable.hh" print_self(SolidMechanicsModel) %include "material.i" %include "solid_mechanics_model.hh" +%inline %{ + namespace akantu{ + void registerNewPythonMaterial(PyObject * obj, const akantu::ID & mat_type) { + + + MaterialFactory::getInstance().registerAllocator( + mat_type, + [obj](UInt, const ID &, SolidMechanicsModel & model, + const ID & id) -> std::unique_ptr + { + return std::make_unique(model, obj, id); + } + ); + } + } +%} + %extend akantu::SolidMechanicsModel { /* ------------------------------------------------------------------------ */ void setPhysicalNamesMaterialSelector(){ - akantu::MeshDataMaterialSelector * selector = new - akantu::MeshDataMaterialSelector("physical_names", *self); - self->setMaterialSelector(*selector); + AKANTU_EXCEPTION("API change: This method needs to be fixed."); + /* akantu::MeshDataMaterialSelector * selector = new */ + /* akantu::MeshDataMaterialSelector("physical_names", *self); */ + /* self->setMaterialSelector(*selector); */ } /* ------------------------------------------------------------------------ */ - bool testConvergenceSccRes(Real tolerance) { - Real error = 0; - bool res = self->testConvergence(tolerance, error); - return res; + void getResidual() { + AKANTU_EXCEPTION("Deprecated function. You should replace:\n" + "model.getResidual()\n" + "with\n" + "model.getInternalForce()\n"); } - /* ------------------------------------------------------------------------ */ - void solveStaticDisplacement(Real tolerance, UInt max_iteration) { - $self->solveStatic(tolerance, max_iteration); - } - - /* ------------------------------------------------------------------------ */ - /// register an empty material of a given type void registerNewPythonMaterial(PyObject * obj, const akantu::ID & mat_type) { - std::pair - sub_sect = akantu::getStaticParser().getSubSections(akantu::_st_material); - - akantu::Parser::const_section_iterator it = sub_sect.first; - for (; it != sub_sect.second; ++it) { - if (it->getName() == mat_type) { - - AKANTU_DEBUG_ASSERT($self->materials_names_to_id.find(mat_type) == - $self->materials_names_to_id.end(), - "A material with this name '" - << mat_type << "' has already been registered. " - << "Please use unique names for materials"); - - UInt mat_count = $self->materials.size(); - $self->materials_names_to_id[mat_type] = mat_count; - - std::stringstream sstr_mat; - sstr_mat << $self->getID() << ":" << mat_count << ":" << mat_type; - akantu::ID mat_id = sstr_mat.str(); - - akantu::Material * material = new akantu::MaterialPython(*$self, obj, mat_id); - $self->materials.push_back(material); - - material->parseSection(*it); - } - } + AKANTU_EXCEPTION("Deprecated function. You should replace:\n" + "model.registerNewPythonMaterial(obj, mat_id)\n" + "with\n" + "akantu.registerNewPythonMaterial(obj, mat_id)\n\n" + "This MUST be done before instanciating the model."); + + /* std::pair */ + /* sub_sect = akantu::getStaticParser().getSubSections(akantu::_st_material); */ + + /* akantu::Parser::const_section_iterator it = sub_sect.first; */ + /* for (; it != sub_sect.second; ++it) { */ + /* if (it->getName() == mat_type) { */ + + /* AKANTU_DEBUG_ASSERT($self->materials_names_to_id.find(mat_type) == */ + /* $self->materials_names_to_id.end(), */ + /* "A material with this name '" */ + /* << mat_type << "' has already been registered. " */ + /* << "Please use unique names for materials"); */ + + /* UInt mat_count = $self->materials.size(); */ + /* $self->materials_names_to_id[mat_type] = mat_count; */ + + /* std::stringstream sstr_mat; */ + /* sstr_mat << $self->getID() << ":" << mat_count << ":" << mat_type; */ + /* akantu::ID mat_id = sstr_mat.str(); */ + + /* akantu::Material * material = new akantu::MaterialPython(*$self, obj, mat_id); */ + /* $self->materials.push_back(material); */ + + /* material->parseSection(*it); */ + /* } */ + /* } */ } /* ------------------------------------------------------------------------ */ void applyDirichletBC(PyObject * func_obj, const std::string & group_name) { akantu::BC::PythonFunctorDirichlet functor(func_obj); $self->applyBC(functor, group_name); } /* ------------------------------------------------------------------------ */ void applyNeumannBC(PyObject * func_obj, const std::string & group_name) { akantu::BC::PythonFunctorNeumann functor(func_obj); $self->applyBC(functor, group_name); } - /* ------------------------------------------------------------------------ */ - void solveDisplCorr(bool need_factorize, bool has_profile_changed) { - akantu::Array & increment = $self->getIncrement(); - - $self->solve( - increment, 1., need_factorize, has_profile_changed); - } - - /* ------------------------------------------------------------------------ */ - void clearDispl() { - akantu::Array & displ = $self->getDisplacement(); - displ.clear(); - } - - /* ------------------------------------------------------------------------ */ - void solveStep_TgModifIncr(Real tolerance, UInt max_iteration) { - $self->solveStep(tolerance, max_iteration); - } - - /* ------------------------------------------------------------------------ */ - void solveStep_TgIncr(Real tolerance, Real & error, UInt max_iteration) { - - $self->solveStep(tolerance, error, max_iteration); - } - - /* ------------------------------------------------------------------------ */ - void clearDisplVeloAcc() { - akantu::Array & displ = $self->getDisplacement(); - akantu::Array & velo = $self->getVelocity(); - akantu::Array & acc = $self->getAcceleration(); - - displ.clear(); - velo.clear(); - acc.clear(); - } - /* ------------------------------------------------------------------------ */ void applyUniformPressure(Real pressure, const std::string surface_name) { UInt spatial_dimension = $self->getSpatialDimension(); akantu::Matrix surface_stress(spatial_dimension, spatial_dimension, 0.0); for (UInt i = 0; i < spatial_dimension; ++i) { surface_stress(i, i) = -pressure; } $self->applyBC(akantu::BC::Neumann::FromStress(surface_stress), surface_name); } /* ------------------------------------------------------------------------ */ void blockDOF(const std::string surface_name, SpacialDirection direction) { $self->applyBC(akantu::BC::Dirichlet::FixedValue(0.0, direction), surface_name); } } + diff --git a/python/swig/sparse_matrix.i b/python/swig/sparse_matrix.i index 50acfc688..f3c2dc6b0 100644 --- a/python/swig/sparse_matrix.i +++ b/python/swig/sparse_matrix.i @@ -1,34 +1,34 @@ %include "sparse_matrix.hh" %pythoncode %{ import scipy.sparse import numpy as _np class AkantuSparseMatrix (scipy.sparse.coo_matrix) : def __init__(self,aka_sparse): self.aka_sparse = aka_sparse matrix_type = self.aka_sparse.getSparseMatrixType() - sz = self.aka_sparse.getSize() + sz = self.aka_sparse.size() row = self.aka_sparse.getIRN()[:,0] -1 col = self.aka_sparse.getJCN()[:,0] -1 data = self.aka_sparse.getA()[:,0] row = row.copy() col = col.copy() data = data.copy() if matrix_type == _symmetric: non_diags = (row != col) row_sup = col[non_diags] col_sup = row[non_diags] data_sup = data[non_diags] col = _np.concatenate((col,col_sup)) row = _np.concatenate((row,row_sup)) data = _np.concatenate((data,data_sup)) scipy.sparse.coo_matrix.__init__(self,(data, (row,col)),shape=(sz,sz)) %} diff --git a/src/common/aka_array_tmpl.hh b/src/common/aka_array_tmpl.hh index 90c468ab8..97fefce38 100644 --- a/src/common/aka_array_tmpl.hh +++ b/src/common/aka_array_tmpl.hh @@ -1,1275 +1,1279 @@ /** * @file aka_array_tmpl.hh * * @author Nicolas Richart * * @date creation: Thu Jul 15 2010 * @date last modification: Fri Jan 22 2016 * * @brief Inline functions of the classes Array and ArrayBase * * @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 . * */ /* -------------------------------------------------------------------------- */ /* Inline Functions Array */ /* -------------------------------------------------------------------------- */ #include "aka_array.hh" /* -------------------------------------------------------------------------- */ #include /* -------------------------------------------------------------------------- */ #ifndef __AKANTU_AKA_ARRAY_TMPL_HH__ #define __AKANTU_AKA_ARRAY_TMPL_HH__ namespace akantu { namespace debug { struct ArrayException : public Exception {}; } // namespace debug /* -------------------------------------------------------------------------- */ template inline T & Array::operator()(UInt i, UInt j) { AKANTU_DEBUG_ASSERT(size_ > 0, "The array \"" << id << "\" is empty"); AKANTU_DEBUG_ASSERT((i < size_) && (j < nb_component), "The value at position [" << i << "," << j << "] is out of range in array \"" << id << "\""); return values[i * nb_component + j]; } /* -------------------------------------------------------------------------- */ template inline const T & Array::operator()(UInt i, UInt j) const { AKANTU_DEBUG_ASSERT(size_ > 0, "The array \"" << id << "\" is empty"); AKANTU_DEBUG_ASSERT((i < size_) && (j < nb_component), "The value at position [" << i << "," << j << "] is out of range in array \"" << id << "\""); return values[i * nb_component + j]; } template inline T & Array::operator[](UInt i) { AKANTU_DEBUG_ASSERT(size_ > 0, "The array \"" << id << "\" is empty"); AKANTU_DEBUG_ASSERT((i < size_ * nb_component), "The value at position [" << i << "] is out of range in array \"" << id << "\""); return values[i]; } /* -------------------------------------------------------------------------- */ template inline const T & Array::operator[](UInt i) const { AKANTU_DEBUG_ASSERT(size_ > 0, "The array \"" << id << "\" is empty"); AKANTU_DEBUG_ASSERT((i < size_ * nb_component), "The value at position [" << i << "] is out of range in array \"" << id << "\""); return values[i]; } /* -------------------------------------------------------------------------- */ /** * append a tuple to the array with the value value for all components * @param value the new last tuple or the array will contain nb_component copies * of value */ template inline void Array::push_back(const T & value) { resizeUnitialized(size_ + 1, true, value); } /* -------------------------------------------------------------------------- */ /** * append a tuple to the array * @param new_elem a C-array containing the values to be copied to the end of * the array */ // template // inline void Array::push_back(const T new_elem[]) { // UInt pos = size_; // resizeUnitialized(size_ + 1, false); // T * tmp = values + nb_component * pos; // std::uninitialized_copy(new_elem, new_elem + nb_component, tmp); // } /* -------------------------------------------------------------------------- */ #ifndef SWIG /** * append a matrix or a vector to the array * @param new_elem a reference to a Matrix or Vector */ template template