diff --git a/CMakeLists.txt b/CMakeLists.txt index 751f460..8f90787 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,255 +1,246 @@ #################################################### # # # SpecMiCP : CMakeLists.txt # # # #################################################### project(specmicp) cmake_minimum_required(VERSION 2.8.8) # Configuration options # ====================== # For an explanation of the options see the INSTALL file option(SPECMICP_USE_OPENMP "Thread parallelisation of specmicp instances if available" ON) option(SPECMICP_NO_DEBUG "Disable SpecMiCP assert" OFF) option(SPECMICP_BUILD_STATIC "Build static libraries" OFF) option(SPECMICP_BUILD_EXAMPLE "Build the examples" ON) -option(SPECMICP_BUILD_CYTHON "Build the cython module" ON) option(SPECMICP_DEBUG_EQUATION_FD_JACOBIAN "Use a finite difference jacobian is specmicp" OFF) # PGO sequence option(SPECMICP_PROFILE_GENERATE "Generate the profile for PGO optimization" OFF) option(SPECMICP_PROFILE_USE "Use the generated profile for PGO optimization" OFF) # global variables # ================ set(SPECMICP_VERSION 0.0.3) # External Package # ================ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/cmake) # OpenMP #------- # not required but recommended if(SPECMICP_USE_OPENMP) find_package(OpenMP) endif() # Boost # ----- find_package(Boost REQUIRED) include_directories(${Boost_INCLUDE_DIR}) # Eigen # ----- find_package(Eigen3 REQUIRED) # This module comes from the Eigen3 Package include_directories(${EIGEN3_INCLUDE_DIR}) # Eigen unsuported # GMRES.h is really the file we are using/looking for # If it doesn't exist then the solver will not be included in the list of the parse solvers if(EXISTS "${EIGEN3_INCLUDE_DIR}/unsupported/Eigen/src/IterativeSolvers/GMRES.h") add_definitions(-DEIGEN_UNSUPPORTED_FOUND) INCLUDE_DIRECTORIES("${EIGEN3_INCLUDE_DIR}/unsupported/") endif() add_custom_target(cmake_incl SOURCES cmake/FindSpecMiCP.cmake) # sanitizer include(SanitizerBuild) # compilation flags # ================= # c++11 # ----- include(CheckCXXCompilerFlag) if(NOT CX11_FLAG) check_cxx_compiler_flag("-std=c++11" HAS_CXX11) if(NOT HAS_CXX11) message(FATAL_ERROR "A c++11 compatible compiler is necessary") else() set(CXX11_FLAG "-std=c++11") endif() endif() # -fvisibility=hidden # --------------------- # check if the compiler supports it check_cxx_compiler_flag("-fvisibility=hidden" HAS_VISIBILITY_HIDDEN) # define a set of files to be compiled with the -fvisibility=hidden flag macro(set_visibility_hidden_flag) if (HAS_VISIBILITY_HIDDEN) foreach(file ${ARGN}) set_source_files_properties(${file} PROPERTIES COMPILE_FLAGS -fvisibility=hidden) endforeach() endif() endmacro() file(COPY pgo_sequence.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) file(COPY reactmicp.qsub DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) if(CMAKE_COMPILER_IS_GNUCXX) if(SPECMICP_PROFILE_GENERATE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-generate") if (SPECMICP_USE_OPENMP AND OPENMP_FOUND) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-correction") endif() endif() if(SPECMICP_PROFILE_USE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-use -Wno-error=coverage-mismatch") if (SPECMICP_USE_OPENMP AND OPENMP_FOUND) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-correction") endif() endif() endif() if(UNIX) # Use ld.gold if it is available and isn't disabled explicitly # Ref : https://bugs.webkit.org/show_bug.cgi?id=137953 if(CMAKE_COMPILER_IS_GNUCXX) option(USE_LD_GOLD "Use GNU gold linker" ON) if (USE_LD_GOLD) execute_process(COMMAND ${CMAKE_C_COMPILER} -fuse-ld=gold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION) if ("${LD_VERSION}" MATCHES "GNU gold") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fuse-ld=gold") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=gold") else () message(WARNING "GNU gold linker isn't available, using the default system linker.") endif () endif () endif() # Generic options SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX11_FLAG}") if (OPENMP_FOUND) SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -pedantic") ##SET(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG") message(STATUS "c++ flags ${CMAKE_CXX_FLAGS}") else() message(WARNING "not tested !") endif() # Directories ######################################################################### # 3rd party # ========= # JsonCPP # ------- set(JSONCPP_DIR ${PROJECT_SOURCE_DIR}/3rdparty/jsoncpp/) add_custom_target(3rdparty_header SOURCES ${JSONCPP_DIR}/json/json.h ${JSONCPP_DIR}/json/json-forwards.h ) include_directories(${JSONCPP_DIR}) # installation dir # ---------------- # http://www.cmake.org/pipermail/cmake/2010-February/035466.html # compute default library install dir if(UNIX) # library # ------ set (_DEFAULT_LIBRARY_INSTALL_DIR lib) if (EXISTS "${CMAKE_INSTALL_PREFIX}/lib32/" AND CMAKE_SIZEOF_VOID_P EQUAL 4) set (_DEFAULT_LIBRARY_INSTALL_DIR lib32) elif (EXISTS "${CMAKE_INSTALL_PREFIX}/lib64/" AND CMAKE_SIZEOF_VOID_P EQUAL 8) set (_DEFAULT_LIBRARY_INSTALL_DIR lib64) endif () # the library install dir set(LIBRARY_INSTALL_DIR "${_DEFAULT_LIBRARY_INSTALL_DIR}" CACHE PATH "Installation directory for libraries") set(STATIC_LIBRARY_INSTALL_DIR "${_DEFAULT_LIBRARY_INSTALL_DIR}/static" CACHE PATH "Installation directory for static libraries") # make the library install dir an absolute path (can be important e.g. when using CONFIGURE_FILE to embed # the library installation directory into a file) if(NOT IS_ABSOLUTE "${LIBRARY_INSTALL_DIR}") set(LIBRARY_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/${LIBRARY_INSTALL_DIR}") endif() if(NOT IS_ABSOLUTE "${STATIC_LIBRARY_INSTALL_DIR}") set(STATIC_LIBRARY_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/${STATIC_LIBRARY_INSTALL_DIR}") endif() # include #-------- set(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/include/specmicp") # share #------ set(SHARE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/share/specmicp") else() message(WARNING "not tested !") endif() enable_testing(true) # CPP API : SpecMiCP / ReactMiCP ######################################################################### # the main source directory - the c++ api set(SPECMICP_CPP_API ${CMAKE_CURRENT_SOURCE_DIR}/src) include_directories(${SPECMICP_CPP_API}) add_subdirectory( ${SPECMICP_CPP_API} ) # Database ######################################################################### add_subdirectory( data ) # Documentation ######################################################################### # "common" documentation # ----------------------- set( DOCS_LIST ${CMAKE_CURRENT_SOURCE_DIR}/README.md ${CMAKE_CURRENT_SOURCE_DIR}/INSTALL ${CMAKE_CURRENT_SOURCE_DIR}/COPYING ) add_custom_target(docs SOURCES ${DOCS_LIST}) install(FILES ${DOCS_LIST} DESTINATION ${SHARE_INSTALL_DIR} ) install(FILES reactmicp.qsub DESTINATION ${SHARE_INSTALL_DIR} ) # Doxygen documentation # --------------------- add_subdirectory( doc ) # the cmake find module # --------------------- install(FILES cmake/FindSpecMiCP.cmake DESTINATION ${SHARE_INSTALL_DIR}/cmake ) -# The following modules have their own CMakeLists.txt - -# Python interface -######################################################################### -if (SPECMICP_BUILD_CYTHON) - add_subdirectory( cython ) -endif() - # Tests ######################################################################### add_subdirectory( tests ) # Examples ######################################################################### add_subdirectory( examples ) diff --git a/INSTALL b/INSTALL index 805a411..0a06ac3 100644 --- a/INSTALL +++ b/INSTALL @@ -1,93 +1,87 @@ Building SpecMiCP ----------------- SpecMiCP uses CMake[1] as build system, to build it, in the specmicp directory, run : cmake . make To customize build, see the cmake documentation[2] and the following informations : Requirements : ============== - C++11 compiler (tested with gcc 4.8.3 and 4,9.2 and clang 3.6.0) - Boost [3] (tested with boost 1.55 and higher) - Eigen [4] (>=3.2) Requirements for the documentation : ------------------------------------ - Doxygen[5] The tests require Catch[6] but it is downloaded automatically by Cmake in the project directory if needed. Configuration Options : ======================= These options are used by CMake to configure the project - SPECMICP_NO_DEBUG - bool (default OFF) - if true, remove assert used in specmicp - SPECMICP_USE_OPENMP : - bool (default ON) - use OpenMP to parallelize code - SPECMICP_DEBUG_EQUATION_FD_JACOBIAN - bool (default OFF) - use a finite difference jacobian in specmicp - - PYTHON_VERSION_3 - - bool (default ON) - - if ON, compile cython module for python 3 - - SPECMICP_BUILD_STATIC - bool (default OFF) - if ON, also build static libraries - SPECMICP_BUILD_EXAMPLE - bool (default ON) - if ON, build the examples - - SPECMICP_BUILD_CYTHON - -bool (default ON) - - if ON, build the cython/python module Examples of configuration : mkdir build; cd build cmake .. -DSPECMICP_USE_OPENMP=ON -DCMAKE_C_COMPILER=[C compiler] -DCMAKE_CXX_COMPILER=[C++11 compiler] -DCMAKE_BUILD_TYPE=Release Other example : to install specmicp in '/opt/local' mkdir build cd build cmake .. -DSPECMICP_BUILD_EXAMPLE=ON -DPYTHON_VERSION_3=OFF -DSPECMICP_USE_OPENMP=ON -DCMAKE_INSTALL_PREFIX=/opt/local -DCMAKE_BUILD_TYPE=release make && make doc_html make install For a custom version of eigen 3: -DEIGEN3_INCLUDE_DIR=[eigen3 directory] For a custom version of boost : -DBoost_NO_BOOST_CMAKE=true -DBOOSTROOT=[boost directory] Tests ===== The tests can be executed with through the ctest command ctest [--output-on-failure] ctest is part of the cmake framework. +The commands `make check` and `make test` will also work. [1]: http://www.cmake.org/ [2]: http://www.cmake.org/cmake/help/v3.0/ [3]: http://www.boost.org/ [4]: http://eigen.tuxfamily.org/ [5]: http://www.stack.nl/~dimitri/doxygen/ [6]: https://github.com/philsquared/Catch diff --git a/README.md b/README.md index 3e0e258..61d8702 100644 --- a/README.md +++ b/README.md @@ -1,107 +1,113 @@ SpecMiCP / ReactMiCP ==================== Overview -------- SpecMiCP is a speciation solver to find the equilibrium state of a chemical system. The system is based on a mixed complementarity formulation of the equilibrium condition for minerals. For a mineral with volume fraction Sm, the equilibrium condition is : Sm >= 0, -log(IAPm/K) >= 0, -Sm*log(IAPm/K) = 0 where IAPm is the ion activity product and K the equilibrium constant. This condition is reformulated using the penalized Fischer-Burmeister C-function and the system is solved using a semismooth method. ReactMiCP is a reactive transport solver built on top of specmicp. It uses the operator splitting approach to couple transport and chemistry. Modules ------- SpecMiCP is not (yet) a program but a set of libraries that can be used to solve specific problems. The following modules are already available : - **specmicp** : *core* of the library, set the system, and solve it - **reactmicp** : the reactive transport solver - **database** : manage the database, parse it from a file, swap the basis, select the correct species, ... - **micpsolver** : Solve a Mixed Complementarity problem - **odeint** : integration methods for solving ordinary differential equations (for problem involving kinetics for example) - **dfpm** : a finite element module -- **specmicp-cython** : a python interface to the SpecMiCP API The **micpsolver** and **odeint** modules can be use independantly. Examples of use are provided in the examples directory. Using SpecMiCP ============== Examples -------- To build and install SpecMiCP/ReactMiCP see the INSTALL file. To learn how to use the API the best is to look at the examples. The starting point should be the leaching in CO2-saturated examples : examples/reactmicp/saturated_react/carbonation.cpp. This file is heavily commented. Example of use of the Python interface can be found in the tests/cython directory. Use in your own project ----------------------- A cmake module can be used to find SpecMiCP in your own project. It will be installed at <prefix>/share/specmicp/cmake/FindSpecMiCP.cmake The python module can be used directly if it is in your python path. Documentation ------------- The API is documented with Doxygen and the documentation can be generated with the command : make doc A (maybe outdated) version of the doc can be found [here][3]. Warning ------- The code is in development and the API is not considered stable yet. +Python binding +-------------- + +A python binding is available at the following address : + +https://bitbucket.org/specmicp/specmicppy + About ===== SpecMiCP is developped by F. Georget (fabieng aT princeton DoT edu). It is part of my Ph.D. work. The purpose of the PhD is to develop a reactive transport model to model the coupling between hydration, drying and carbonation in cement paste. This Ph.D. is funded by [Princeton university][6], [Lafarge][4] and the [CSTB][5]. References : - F. Georget, J. H. Prévost, and R. J. Vanderbei. A speciation solver for cement paste modeling and the semismooth Newton method . Cement and Concrete Research, 68(0):139--147, 2015. - F. Georget, J. H. Prévost and B. Huet Validation of a reactive transport solver based on a semismooth speciation solver (submitted to Computational Geosciences) A list of the references used in the code can be found in the [documentation][7]. [2]: http://www.empa.ch/plugin/template/empa/*/62204/---/l=1 [3]: http://www.princeton.edu/~fabieng/specmicpdoc/index.html [4]: http://www.lafarge.com/en [5]: http://www.cstb.fr/ [6]: http://princeton.edu [7]: http://www.princeton.edu/~fabieng/specmicpdoc/citelist.html diff --git a/cmake/FindCython.cmake b/cmake/FindCython.cmake deleted file mode 100644 index 04aed1f..0000000 --- a/cmake/FindCython.cmake +++ /dev/null @@ -1,44 +0,0 @@ -# Find the Cython compiler. -# -# This code sets the following variables: -# -# CYTHON_EXECUTABLE -# -# See also UseCython.cmake - -#============================================================================= -# Copyright 2011 Kitware, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -#============================================================================= - -# Use the Cython executable that lives next to the Python executable -# if it is a local installation. -find_package( PythonInterp ) -if( PYTHONINTERP_FOUND ) - get_filename_component( _python_path ${PYTHON_EXECUTABLE} PATH ) - find_program( CYTHON_EXECUTABLE - NAMES cython cython.bat cython3 - HINTS ${_python_path} - ) -else() - find_program( CYTHON_EXECUTABLE - NAMES cython cython.bat cython3 - ) -endif() - - -include( FindPackageHandleStandardArgs ) -FIND_PACKAGE_HANDLE_STANDARD_ARGS( Cython REQUIRED_VARS CYTHON_EXECUTABLE ) - -mark_as_advanced( CYTHON_EXECUTABLE ) diff --git a/cmake/UseCython.cmake b/cmake/UseCython.cmake deleted file mode 100644 index 86aa7d8..0000000 --- a/cmake/UseCython.cmake +++ /dev/null @@ -1,295 +0,0 @@ -# Define a function to create Cython modules. -# -# For more information on the Cython project, see http://cython.org/. -# "Cython is a language that makes writing C extensions for the Python language -# as easy as Python itself." -# -# This file defines a CMake function to build a Cython Python module. -# To use it, first include this file. -# -# include( UseCython ) -# -# Then call cython_add_module to create a module. -# -# cython_add_module( <module_name> <src1> <src2> ... <srcN> ) -# -# To create a standalone executable, the function -# -# cython_add_standalone_executable( <executable_name> [MAIN_MODULE src1] <src1> <src2> ... <srcN> ) -# -# To avoid dependence on Python, set the PYTHON_LIBRARY cache variable to point -# to a static library. If a MAIN_MODULE source is specified, -# the "if __name__ == '__main__':" from that module is used as the C main() method -# for the executable. If MAIN_MODULE, the source with the same basename as -# <executable_name> is assumed to be the MAIN_MODULE. -# -# Where <module_name> is the name of the resulting Python module and -# <src1> <src2> ... are source files to be compiled into the module, e.g. *.pyx, -# *.py, *.c, *.cxx, etc. A CMake target is created with name <module_name>. This can -# be used for target_link_libraries(), etc. -# -# The sample paths set with the CMake include_directories() command will be used -# for include directories to search for *.pxd when running the Cython complire. -# -# Cache variables that effect the behavior include: -# -# CYTHON_ANNOTATE -# CYTHON_NO_DOCSTRINGS -# CYTHON_FLAGS -# -# Source file properties that effect the build process are -# -# CYTHON_IS_CXX -# -# If this is set of a *.pyx file with CMake set_source_files_properties() -# command, the file will be compiled as a C++ file. -# -# See also FindCython.cmake - -#============================================================================= -# Copyright 2011 Kitware, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -#============================================================================= - -# Configuration options. -set( CYTHON_ANNOTATE OFF - CACHE BOOL "Create an annotated .html file when compiling *.pyx." ) -set( CYTHON_NO_DOCSTRINGS OFF - CACHE BOOL "Strip docstrings from the compiled module." ) -set( CYTHON_FLAGS "" CACHE STRING - "Extra flags to the cython compiler." ) -mark_as_advanced( CYTHON_ANNOTATE CYTHON_NO_DOCSTRINGS CYTHON_FLAGS ) - -find_package( Cython REQUIRED ) -find_package( PythonLibs REQUIRED ) - -set( CYTHON_CXX_EXTENSION "cxx" ) -set( CYTHON_C_EXTENSION "c" ) - -# Create a *.c or *.cxx file from a *.pyx file. -# Input the generated file basename. The generate file will put into the variable -# placed in the "generated_file" argument. Finally all the *.py and *.pyx files. -function( compile_pyx _name generated_file ) - # Default to assuming all files are C. - set( cxx_arg "" ) - set( extension ${CYTHON_C_EXTENSION} ) - set( pyx_lang "C" ) - set( comment "Compiling Cython C source for ${_name}..." ) - - set( cython_include_directories "" ) - set( pxd_dependencies "" ) - set( c_header_dependencies "" ) - set( pyx_locations "" ) - - foreach( pyx_file ${ARGN} ) - get_filename_component( pyx_file_basename "${pyx_file}" NAME_WE ) - - # Determine if it is a C or C++ file. - get_source_file_property( property_is_cxx ${pyx_file} CYTHON_IS_CXX ) - if( ${property_is_cxx} ) - set( cxx_arg "--cplus" ) - set( extension ${CYTHON_CXX_EXTENSION} ) - set( pyx_lang "CXX" ) - set( comment "Compiling Cython CXX source for ${_name}..." ) - endif() - - # Get the include directories. - get_source_file_property( pyx_location ${pyx_file} LOCATION ) - get_filename_component( pyx_path ${pyx_location} PATH ) - get_directory_property( cmake_include_directories DIRECTORY ${pyx_path} INCLUDE_DIRECTORIES ) - list( APPEND cython_include_directories ${cmake_include_directories} ) - list( APPEND pyx_locations "${pyx_location}" ) - - # Determine dependencies. - # Add the pxd file will the same name as the given pyx file. - unset( corresponding_pxd_file CACHE ) - find_file( corresponding_pxd_file ${pyx_file_basename}.pxd - PATHS "${pyx_path}" ${cmake_include_directories} - NO_DEFAULT_PATH ) - if( corresponding_pxd_file ) - list( APPEND pxd_dependencies "${corresponding_pxd_file}" ) - endif() - - # pxd files to check for additional dependencies. - set( pxds_to_check "${pyx_file}" "${pxd_dependencies}" ) - set( pxds_checked "" ) - set( number_pxds_to_check 1 ) - while( ${number_pxds_to_check} GREATER 0 ) - foreach( pxd ${pxds_to_check} ) - list( APPEND pxds_checked "${pxd}" ) - list( REMOVE_ITEM pxds_to_check "${pxd}" ) - - # check for C header dependencies - file( STRINGS "${pxd}" extern_from_statements - REGEX "cdef[ ]+extern[ ]+from.*$" ) - foreach( statement ${extern_from_statements} ) - # Had trouble getting the quote in the regex - string( REGEX REPLACE "cdef[ ]+extern[ ]+from[ ]+[\"]([^\"]+)[\"].*" "\\1" header "${statement}" ) - unset( header_location CACHE ) - find_file( header_location ${header} PATHS ${cmake_include_directories} ) - if( header_location ) - list( FIND c_header_dependencies "${header_location}" header_idx ) - if( ${header_idx} LESS 0 ) - list( APPEND c_header_dependencies "${header_location}" ) - endif() - endif() - endforeach() - - # check for pxd dependencies - - # Look for cimport statements. - set( module_dependencies "" ) - file( STRINGS "${pxd}" cimport_statements REGEX cimport ) - foreach( statement ${cimport_statements} ) - if( ${statement} MATCHES from ) - string( REGEX REPLACE "from[ ]+([^ ]+).*" "\\1" module "${statement}" ) - else() - string( REGEX REPLACE "cimport[ ]+([^ ]+).*" "\\1" module "${statement}" ) - endif() - list( APPEND module_dependencies ${module} ) - endforeach() - list( REMOVE_DUPLICATES module_dependencies ) - # Add the module to the files to check, if appropriate. - foreach( module ${module_dependencies} ) - unset( pxd_location CACHE ) - find_file( pxd_location ${module}.pxd - PATHS "${pyx_path}" ${cmake_include_directories} NO_DEFAULT_PATH ) - if( pxd_location ) - list( FIND pxds_checked ${pxd_location} pxd_idx ) - if( ${pxd_idx} LESS 0 ) - list( FIND pxds_to_check ${pxd_location} pxd_idx ) - if( ${pxd_idx} LESS 0 ) - list( APPEND pxds_to_check ${pxd_location} ) - list( APPEND pxd_dependencies ${pxd_location} ) - endif() # if it is not already going to be checked - endif() # if it has not already been checked - endif() # if pxd file can be found - endforeach() # for each module dependency discovered - endforeach() # for each pxd file to check - list( LENGTH pxds_to_check number_pxds_to_check ) - endwhile() - endforeach() # pyx_file - - # Set additional flags. - if( CYTHON_ANNOTATE ) - set( annotate_arg "--annotate" ) - endif() - - if( CYTHON_NO_DOCSTRINGS ) - set( no_docstrings_arg "--no-docstrings" ) - endif() - - if( "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" OR - "${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo" ) - set( cython_debug_arg "--gdb" ) - endif() - - if( "${PYTHONLIBS_VERSION_STRING}" MATCHES "^2." ) - set( version_arg "-2" ) - elseif( "${PYTHONLIBS_VERSION_STRING}" MATCHES "^3." ) - set( version_arg "-3" ) - else() - set( version_arg ) - endif() - - # Include directory arguments. - list( REMOVE_DUPLICATES cython_include_directories ) - set( include_directory_arg "" ) - foreach( _include_dir ${cython_include_directories} ) - set( include_directory_arg ${include_directory_arg} "-I" "${_include_dir}" ) - endforeach() - - # Determining generated file name. - set( _generated_file "${CMAKE_CURRENT_BINARY_DIR}/${_name}.${extension}" ) - set_source_files_properties( ${_generated_file} PROPERTIES GENERATED TRUE ) - set( ${generated_file} ${_generated_file} PARENT_SCOPE ) - - list( REMOVE_DUPLICATES pxd_dependencies ) - list( REMOVE_DUPLICATES c_header_dependencies ) - - # Add the command to run the compiler. - add_custom_command( OUTPUT ${_generated_file} - COMMAND ${CYTHON_EXECUTABLE} - ARGS ${cxx_arg} ${include_directory_arg} ${version_arg} - ${annotate_arg} ${no_docstrings_arg} ${cython_debug_arg} ${CYTHON_FLAGS} - --output-file ${_generated_file} ${pyx_locations} - DEPENDS ${pyx_locations} ${pxd_dependencies} - IMPLICIT_DEPENDS ${pyx_lang} ${c_header_dependencies} - COMMENT ${comment} - ) - - # Remove their visibility to the user. - set( corresponding_pxd_file "" CACHE INTERNAL "" ) - set( header_location "" CACHE INTERNAL "" ) - set( pxd_location "" CACHE INTERNAL "" ) -endfunction() - -# cython_add_module( <name> src1 src2 ... srcN ) -# Build the Cython Python module. -function( cython_add_module _name ) - set( pyx_module_sources "" ) - set( other_module_sources "" ) - foreach( _file ${ARGN} ) - if( ${_file} MATCHES ".*\\.py[x]?$" ) - list( APPEND pyx_module_sources ${_file} ) - else() - list( APPEND other_module_sources ${_file} ) - endif() - endforeach() - compile_pyx( ${_name} generated_file ${pyx_module_sources} ) - include_directories( ${PYTHON_INCLUDE_DIRS} ) - python_add_module( ${_name} ${generated_file} ${other_module_sources} ) - if( APPLE ) - set_target_properties( ${_name} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup" ) - else() - target_link_libraries( ${_name} ${PYTHON_LIBRARIES} ) - endif() -endfunction() - -include( CMakeParseArguments ) -# cython_add_standalone_executable( _name [MAIN_MODULE src3.py] src1 src2 ... srcN ) -# Creates a standalone executable the given sources. -function( cython_add_standalone_executable _name ) - set( pyx_module_sources "" ) - set( other_module_sources "" ) - set( main_module "" ) - cmake_parse_arguments( cython_arguments "" "MAIN_MODULE" "" ${ARGN} ) - include_directories( ${PYTHON_INCLUDE_DIRS} ) - foreach( _file ${cython_arguments_UNPARSED_ARGUMENTS} ) - if( ${_file} MATCHES ".*\\.py[x]?$" ) - get_filename_component( _file_we ${_file} NAME_WE ) - if( "${_file_we}" STREQUAL "${_name}" ) - set( main_module "${_file}" ) - elseif( NOT "${_file}" STREQUAL "${cython_arguments_MAIN_MODULE}" ) - set( PYTHON_MODULE_${_file_we}_static_BUILD_SHARED OFF ) - compile_pyx( "${_file_we}_static" generated_file "${_file}" ) - list( APPEND pyx_module_sources "${generated_file}" ) - endif() - else() - list( APPEND other_module_sources ${_file} ) - endif() - endforeach() - - if( cython_arguments_MAIN_MODULE ) - set( main_module ${cython_arguments_MAIN_MODULE} ) - endif() - if( NOT main_module ) - message( FATAL_ERROR "main module not found." ) - endif() - get_filename_component( main_module_we "${main_module}" NAME_WE ) - set( CYTHON_FLAGS ${CYTHON_FLAGS} --embed ) - compile_pyx( "${main_module_we}_static" generated_file ${main_module} ) - add_executable( ${_name} ${generated_file} ${pyx_module_sources} ${other_module_sources} ) - target_link_libraries( ${_name} ${PYTHON_LIBRARIES} ${pyx_module_libs} ) -endfunction() diff --git a/cython/CMakeLists.txt b/cython/CMakeLists.txt deleted file mode 100644 index 0c83da1..0000000 --- a/cython/CMakeLists.txt +++ /dev/null @@ -1,91 +0,0 @@ -# ======================= # -# # -# Python specmicp lib # -# # -# ======================= # - -# Build the cython interface -# ========================== - -# Import the correct version of python - -option(PYTHON_VERSION_3 "Version of python for cython compilation" ON) - -if (PYTHON_VERSION_3) - find_package(PythonInterp 3 REQUIRED) - find_package(PythonLibs 3 REQUIRED) -else() - find_package(PythonInterp 2.7 REQUIRED) - find_package(PythonLibs 2.7 REQUIRED) -endif() - -include_directories(${PYTHON_INCLUDE_PATH}) - -# include cython only once python is configured -include(UseCython) - -# main variables -# =============== - -# directories -# ----------- -set(PY_SPECMICP_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/specmicp) -set(PY_SPECMICP_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/specmicp) -set(PY_INCLUDES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/includes) - - -# common includes -# =============== - -add_custom_target(cython_includes SOURCES - ${PY_INCLUDES_DIR}/memory.pxd - ${PY_INCLUDES_DIR}/eigen_set.hpp - ${PY_INCLUDES_DIR}/eigen.pxd -) - -# SpecMiCP module -# =============== -add_subdirectory(specmicp) - - -# setup.py -set(CYTHON_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) -configure_file(setup.py.in ${CYTHON_BINARY_DIR}/setup.py @ONLY) -configure_file(install_python.cmake.in ${CYTHON_BINARY_DIR}/install_python.cmake @ONLY) -install(SCRIPT "${CYTHON_BINARY_DIR}/install_python.cmake") - -# ========== # -# # -# TEST # -# # -# ========== # - -# Prelude -# ======= - -# directories -# ----------- -set(TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../tests/cython) -set(BINARY_TEST_DIR ${PROJECT_BINARY_DIR}/tests) - -# variables to configure the scripts -# ---------------------------------- -set(python_module_path ${CMAKE_CURRENT_BINARY_DIR}) -set(database_path ${CMAKE_CURRENT_BINARY_DIR}/../data/cemdata_specmicp.js) - -# macro to configure the scripts -# ------------------------------- -macro(configure_python_test test_name) -configure_file(${TEST_DIR}/${test_name} ${BINARY_TEST_DIR}${CMAKE_FILES_DIRECTORY}/${test_name} @ONLY) -file(COPY ${BINARY_TEST_DIR}${CMAKE_FILES_DIRECTORY}/${test_name} - DESTINATION ${BINARY_TEST_DIR} - FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ - GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) -endmacro(configure_python_test) - -# Scripts -# ======= -# database unittest -configure_python_test(database.py) -# test specmicp -configure_python_test(test_specmicp.py) diff --git a/cython/includes/eigen.pxd b/cython/includes/eigen.pxd deleted file mode 100644 index 9281328..0000000 --- a/cython/includes/eigen.pxd +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton University -# All rights reserved. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# * Neither the name of SpecMiCP nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -# Includes from Eigen -# -# This is kept simple on purpose -cdef extern from "<Eigen/Dense>" namespace "Eigen": - cdef cppclass Matrix[T, U, V]: - Matrix() - T& operator()(int, int) - T& operator()(int) - - # A matrix - cdef cppclass MatrixXd: - MatrixXd() - MatrixXd(int, int) - MatrixXd(const MatrixXd& other) - void setZero() - void setZero(int, int) - float& operator()(int, int) # read access - - # a vector - cdef cppclass VectorXd: - VectorXd() - VectorXd(int) - VectorXd(const VectorXd& other) - void setZero() - void setZero(int) - - float& operator()(int) # read access - -# write -cdef extern from "eigen_set.hpp": - cdef void vector_setitem(VectorXd&, int row, float value) - cdef void vector_additem(VectorXd&, int row, float value) - cdef void matrix_setitem(MatrixXd&, int row, int col, float value) - cdef void matrix_additem(MatrixXd&, int row, int col, float value) diff --git a/cython/includes/eigen_set.hpp b/cython/includes/eigen_set.hpp deleted file mode 100644 index 2b5bda1..0000000 --- a/cython/includes/eigen_set.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/*------------------------------------------------------- - -Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton University -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the Princeton University nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------------------------------------------------------*/ - -#ifndef SPECMICP_CYTHON_EIGEN -#define SPECMICP_CYTHON_EIGEN - -#include <Eigen/Core> - -// Cython do not accept left-value references -// this is a workaround to set an value in a vector or a matrix - -inline void vector_setitem(Eigen::VectorXd& vec, int row, double value) { - vec(row) = value; -} - -inline void vector_additem(Eigen::VectorXd& vec, int row, double value) { - vec(row) += value; -} - - -inline void matrix_setitem(Eigen::MatrixXd& mat, int row, int col, double value) { - mat(row, col) = value; -} - -inline void matrix_additem(Eigen::MatrixXd& mat, int row, int col, double value) { - mat(row, col) += value; -} - -#endif // SPECMICP_CYTHON_EIGEN - diff --git a/cython/includes/memory.pxd b/cython/includes/memory.pxd deleted file mode 100644 index f1f3575..0000000 --- a/cython/includes/memory.pxd +++ /dev/null @@ -1,14 +0,0 @@ -# definition from <memory> -# -cdef extern from "<memory>" namespace "std": - # - # The shared ptr - # note : there is no overloading of operator-> - # the true object is accessed through the get() member function - # - cdef cppclass shared_ptr[T]: - shared_ptr() - shared_ptr(shared_ptr[T]) - T* get() - - shared_ptr[T] make_shared[T]() diff --git a/cython/install_python.cmake.in b/cython/install_python.cmake.in deleted file mode 100644 index baf2c6e..0000000 --- a/cython/install_python.cmake.in +++ /dev/null @@ -1,9 +0,0 @@ -execute_process(COMMAND @PYTHON_EXECUTABLE@ setup.py install --prefix @CMAKE_INSTALL_PREFIX@ - RESULT_VARIABLE retcode - ERROR_VARIABLE error_setup_py - OUTPUT_VARIABLE output_setup_py - WORKING_DIRECTORY @CYTHON_BINARY_DIR@ - ) -message(STATUS ${retcode}) -message(STATUS ${output_setup_py}) -message(STATUS ${error_setup_py}) diff --git a/cython/setup.py.in b/cython/setup.py.in deleted file mode 100644 index 6226bef..0000000 --- a/cython/setup.py.in +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python - -from distutils.core import setup - -setup(name='specmicp', - version='@SPECMICP_VERSION@', - description='Python interface for SpecMiCP ', - author='Fabien Georget', - author_email='fabieng@princeton.edu', - url='https://bitbucket.org/specmicp/specmicp', - packages=['specmicp'], - package_dir={'specmicp': 'specmicp'}, - package_data={'specmicp': ['*.so']} - ) \ No newline at end of file diff --git a/cython/specmicp/CMakeLists.txt b/cython/specmicp/CMakeLists.txt deleted file mode 100644 index 6160f68..0000000 --- a/cython/specmicp/CMakeLists.txt +++ /dev/null @@ -1,123 +0,0 @@ -# Build the python module : SpecMiCP -# ================================== - -set(PY_INCLUDES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../includes) - -include_directories(${PY_INCLUDES_DIR}) -include_directories(${EIGEN3_INCLUDE_DIR}) -include_directories(${PROJECT_SOURCE_DIR}) -include_directories(${JSONCPP_DIR}) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) - -set(cython_specmicp_files - __init__.py - database.pxd - database.pyx - solution.pxd - solution.pyx - constraints.pxd - constraints.pyx - solver.pxd - solver.pyx - is_solver_successful.hpp - set_units.hpp - init_log.hpp - logger.pxd - logger.pyx - cement_hydration.py - - units.pxd - solver_options.pxd - -) - - -#add_library(specmicp_cython_database SHARED ${DATABASE_LIBFILE}) -#add_library(specmicp_cython_specmicp SHARED ${SPECMICP_LIBFILE}) - -# database -# --------- - - -set_source_files_properties( - database.pyx - PROPERTIES CYTHON_IS_CXX TRUE ) - -cython_add_module(database database.pyx) -target_link_libraries(database specmicp_database specmicp) - -# solution -# -------- - -set_source_files_properties( - solution.pyx - PROPERTIES CYTHON_IS_CXX TRUE ) - -cython_add_module(solution solution.pyx) -target_link_libraries(solution specmicp_database specmicp) - -# constraints -# ----------- -set_source_files_properties( - constraints.pyx - PROPERTIES CYTHON_IS_CXX TRUE ) - -cython_add_module(constraints constraints.pyx) -target_link_libraries(constraints specmicp_database specmicp) - -# solver -# ----- - -set_source_files_properties( - solver.pyx - PROPERTIES CYTHON_IS_CXX TRUE -) - -cython_add_module(solver solver.pyx) -target_link_libraries(solver specmicp_database specmicp) - - -# logger -# ----- - -set_source_files_properties( - logger.pyx - PROPERTIES CYTHON_IS_CXX TRUE -) - -cython_add_module(logger logger.pyx) - - - -# specmicp module -# --------------- - -set(PURE_PYTHON_FILES - __init__.py - cement_hydration.py -) - -add_custom_target(cython_specmicp ALL - DEPENDS database solution constraints solver logger ${PURE_PYTHON_FILES} - COMMENT "Built the python specmicp module" - SOURCES ${cython_specmicp_files} -) - - -macro(COPY_PURE_PYTHON_FILE in_file out_file target) - if(${in_file} IS_NEWER_THAN ${out_file}) - add_custom_command ( - TARGET ${target} - COMMAND ${CMAKE_COMMAND} - ARGS -E copy ${in_file} ${out_file} - ) - endif() -endmacro(COPY_PURE_PYTHON_FILE) - - - -foreach(in_file ${PURE_PYTHON_FILES}) - COPY_PURE_PYTHON_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${in_file} ${CMAKE_CURRENT_BINARY_DIR}/${in_file} cython_specmicp) -endforeach() - - diff --git a/cython/specmicp/__init__.py b/cython/specmicp/__init__.py deleted file mode 100644 index 1cb6f47..0000000 --- a/cython/specmicp/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/cython/specmicp/cement_hydration.py b/cython/specmicp/cement_hydration.py deleted file mode 100644 index c73a333..0000000 --- a/cython/specmicp/cement_hydration.py +++ /dev/null @@ -1,281 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -import specmicp.database as database -import specmicp.constraints as formulation -import specmicp.solver - -MASS_PERCENT_INDEX = 0 -HYDRATION_INDEX = 1 - - -def hydration( - minerals, - wc, - database_path="", - database_manager=None, - aqueous_species=None, - percent_v_entrained_air=0.0, - list_minerals_to_keep=None, - list_extra_component=[], - length_unit="meter", - previous_sol=None, - saturated_system=False - ): - """Thermodynamic Cement hydration - - Return a SpecMiCPSolution - The first argument is a dictionary : - {label: (mass_percent, hydration degree)} - - A new database is created for each p - - Example : - >>> sol = hydration( - {"C3S": (0.8, 1.0), "C3A": (0.1, 1.0), "C4AF": (0.1, 1.0)}, - 0.4, - "../data/cemdata.js", - percent_v_entrained_air=0.0) - - """ - if database_manager is None: - db = database.DatabaseManager(database_path) - swapping = { - "H[+]": "HO[-]", - "Al[3+]": "Al(OH)4[-]", - "Fe[2+]": "Fe(OH)4[-]", - "Si(OH)4": "SiO(OH)3[-]" - } - db.swap_components(swapping) - db.remove_gas_phases() - else: - db = database_manager - - - if length_unit == "meter": - scaling = 1.0 - elif length_unit == "decimeter": - scaling = 1e3 - elif length_unit == "centimer": - scaling = 1e6 - else: - raise ValueError("Unknown length unit") - - scaling_M = 1.0 - - rho_minerals = [] - is_kinetic = [] - - # find the cement mass - # -------------------- - sum_for_cement_mass = 0.0 - - for (label, value) in minerals.items(): - try: - idm = db.mineral_label_to_id(label) - rho_minerals.append(scaling_M/scaling*db.density_mineral(idm)) - is_kinetic.append(False) - except ValueError: - idm = db.mineral_kinetic_label_to_id(label) - rho_minerals.append(scaling_M/scaling*db.density_mineral_kinetic(idm)) - is_kinetic.append(True) - sum_for_cement_mass += value[MASS_PERCENT_INDEX] / rho_minerals[-1] - - sum_for_cement_mass += wc / (997.0 / scaling) - - mc = (1.0 - percent_v_entrained_air) / sum_for_cement_mass - inert_volume = 0.0 - - # set the formulation - # ------------------- - system = formulation.SpecMiCPFormulation(db) - - for (index, (label, value)) in enumerate(minerals.items()): - reactant_mass = value[MASS_PERCENT_INDEX] * mc - concentration = value[HYDRATION_INDEX] * reactant_mass - inert = (1.0 - value[HYDRATION_INDEX]) * reactant_mass - if is_kinetic[index]: - concentration /= scaling_M*db.molar_mass_mineral_kinetic(idm) - inert /= rho_minerals[index] - else: - concentration /= scaling_M*db.molar_mass_mineral(idm) - inert /= rho_minerals[index] - system.add_mineral(label, concentration) - inert_volume += inert - - system.set_inert_volume_fraction(inert_volume) - system.set_mass_solution(wc * mc) - - if aqueous_species is not None: - for (label, value) in aqueous_species.items(): - system.add_aqueous_species(label, value) - - if list_minerals_to_keep is not None: - system.set_list_minerals(list_minerals_to_keep) - - system.initialize_system() - if saturated_system: - system.set_saturated_system() - system.set_charge_keeper("HO[-]") - - - # solve the problem - # ----------------- - the_solver = specmicp.solver.SpecMiCPSolver(db, system, previous_sol) - the_solver.set_length_unit(length_unit) - the_solver.set_maximum_step_length(20, 100) - the_solver.enable_non_monotone_linesearch() - the_solver.disable_condition_check() - the_solver.set_tolerances(1e-8, 1e-12) - the_solver.set_non_ideality_tolerance(1e-12) - if previous_sol is None: - map_init = {"HO[-]": -2.0, "Ca[2+]": -2.0, "SiO(OH)3[-]": -5.0} - extra_components = {"Al(OH)4[-]": -3.0, "SO4[2-]": -3.0, "Fe(OH)4[-]": -4.0} - for (label, value) in extra_components.items(): - try: - _ = db.component_label_to_id(label) - map_init[label] = value - except ValueError: - pass - the_solver.initialize_variables(0.5, map_init) - the_solver.solve() - - # return the solution - # ------------------- - return the_solver.get_solution() - - -def hydration_oxyde( - oxyde_formulation, - density_cement, - wc, - loss_of_ignition, - database_path="", - database_manager=None, - aqueous_species=None, - percent_v_entrained_air=0.0, - list_minerals_to_keep=None, - list_extra_component=[], - length_unit="meter", - previous_sol=None, - saturated_system=False, - degree_hydration=1.0 - ): - """Thermodynamic Cement hydration - - No hydration degree - - Return a SpecMiCPSolution - The first argument is a dictionary : - {label: (mass_percent, hydration degree)} - - A new database is created for each p - - """ - if database_manager is None: - db = database.DatabaseManager(database_path) - swapping = { - "H[+]": "HO[-]", - "Al[3+]": "Al(OH)4[-]", - "Fe[2+]": "Fe(OH)4[-]", - "Si(OH)4": "SiO(OH)3[-]" - } - db.swap_components(swapping) - db.remove_gas_phases() - else: - db = database_manager - - - if length_unit == "meter": - scaling = 1.0 - elif length_unit == "decimeter": - scaling = 1e3 - elif length_unit == "centimer": - scaling = 1e6 - else: - raise ValueError("Unknown length unit") - - scaling_M = 1.0 - - - # find the cement mass - # -------------------- - - sum_for_cement_mass = 1.0/density_cement + wc / (997.0 / scaling) - - mc = (1.0 - percent_v_entrained_air) / sum_for_cement_mass - - # set the formulation - # ------------------- - system = formulation.SpecMiCPFormulation(db) - - for (index, (label, value)) in enumerate(oxyde_formulation.items()): - concentration = value * mc * degree_hydration - concentration /= scaling_M*db.l_molar_mass_mineral_kinetic(label) - system.add_mineral(label, concentration) - system.set_inert_volume_fraction(mc*(1.0-degree_hydration)/density_cement) - system.set_mass_solution(wc * mc + loss_of_ignition * mc) - - if aqueous_species is not None: - for (label, value) in aqueous_species.items(): - system.add_aqueous_species(label, value) - - if list_minerals_to_keep is not None: - system.set_list_minerals(list_minerals_to_keep) - - system.initialize_system() - if saturated_system: - system.set_saturated_system() - system.set_charge_keeper("HO[-]") - - - # solve the problem - # ----------------- - the_solver = specmicp.solver.SpecMiCPSolver(db, system, previous_sol) - the_solver.set_length_unit(length_unit) - the_solver.set_maximum_step_length(20, 100) - the_solver.enable_non_monotone_linesearch() - the_solver.disable_condition_check() - the_solver.set_tolerances(1e-8, 1e-12) - the_solver.set_non_ideality_tolerance(1e-12) - if previous_sol is None: - map_init = {"HO[-]": -2.0, "Ca[2+]": -2.0, "SiO(OH)3[-]": -5.0} - extra_components = {"Al(OH)4[-]": -3.0, "SO4[2-]": -3.0, "Fe(OH)4[-]": -4.0} - for (label, value) in extra_components.items(): - try: - _ = db.component_label_to_id(label) - map_init[label] = value - except ValueError: - pass - the_solver.initialize_variables(0.5, map_init) - the_solver.solve() - - # return the solution - # ------------------- - return the_solver.get_solution() diff --git a/cython/specmicp/constraints.pxd b/cython/specmicp/constraints.pxd deleted file mode 100644 index 2c45607..0000000 --- a/cython/specmicp/constraints.pxd +++ /dev/null @@ -1,92 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -from eigen cimport VectorXd -from libcpp.map cimport map as cmap -from libcpp.string cimport string -from libcpp.vector cimport vector - -from memory cimport shared_ptr -from database cimport DatabaseManager, DataContainer - -# The constraints -# --------------- -cdef extern from "specmicp/adimensional/adimensional_system_structs.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemConstraints: - AdimensionalSystemConstraints() - AdimensionalSystemConstraints(const AdimensionalSystemConstraints& other) - - VectorXd total_concentrations - - void set_total_concentrations(const VectorXd&) - - void enable_conservation_water() - void disable_conservation_water() - void set_saturated_system() - - void disable_surface_model() - void enable_surface_model(double) - - void set_charge_keeper(int) - void add_fixed_fugacity_gas(int, int, float) - void add_fixed_activity_component(int, double) - - void set_inert_volume_fraction(double) - -# The formulation of the problem -# ------------------------------ -cdef extern from "specmicp/problem_solver/formulation.hpp" namespace "specmicp": - cdef cppclass Formulation: - Formulation() - void set_mass_solution(double) - void add_aqueous_species(const string&, double) except + - void add_mineral(const string&, double) except + - void keep_component(const string&) - void set_minerals_list(const vector[string]& list) - -# Dissolve the formulation -# ------------------------ -cdef extern from "specmicp/problem_solver/dissolver.hpp" namespace "specmicp": - cdef cppclass Dissolver: - Dissolver(shared_ptr[DataContainer]) - VectorXd dissolve(const Formulation&) except + - VectorXd get_total_concentration() - -# Wrapper for the constraints -# --------------------------- -cdef class SpecMiCPConstraints: - cdef DatabaseManager database - cdef AdimensionalSystemConstraints* constraints - cdef AdimensionalSystemConstraints* _get(self) - -# Wrapper for the formulation -# --------------------------- -cdef class SpecMiCPFormulation(SpecMiCPConstraints): - cdef Formulation* formulation diff --git a/cython/specmicp/constraints.pyx b/cython/specmicp/constraints.pyx deleted file mode 100644 index 8f702f9..0000000 --- a/cython/specmicp/constraints.pyx +++ /dev/null @@ -1,184 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from database cimport DatabaseManager -from constraints cimport SpecMiCPConstraints, AdimensionalSystemConstraints, SpecMiCPFormulation -from eigen cimport VectorXd, vector_setitem, vector_additem -from libcpp.utility cimport pair -from cython.operator cimport dereference - -cdef class SpecMiCPConstraints: - """A class managing the SpecMiCP constraints""" - - def __cinit__(self, DatabaseManager database not None): - self.database = database - self.constraints = new AdimensionalSystemConstraints() - def __dealloc__(self): - del self.constraints - cdef AdimensionalSystemConstraints* _get(self): - return self.constraints - - # Total concentrations - # -------------------- - - def set_total_concentrations(self, dictionary_total_concs): - """Set the total concentrations - - dictionary_total_concs is a dictionary mapping the labels of components - to their total concentrations. - """ - cdef VectorXd total_concs - cdef int index - total_concs.setZero(self.database.nb_component) - for (key, value) in dictionary_total_concs.items(): - index = self.database.component_label_to_id(key) - vector_setitem(total_concs, index, value) - self.constraints.set_total_concentrations(total_concs) - - def add_total_concentrations(self, dictionary_total_concs): - """Set the total concentrations - - dictionary_total_concs is a dictionary mapping the labels of components - to their total concentrations. - """ - cdef int index - for (key, value) in dictionary_total_concs.items(): - index = self.database.component_label_to_id(key) - vector_additem(self.constraints.total_concentrations, index, value) - - def get_total_concentration(self, label): - """Return the total concentration for "label" """ - index = self.database.component_label_to_id(label) - return self.constraints.total_concentrations(index) - - # Water conservation - # ------------------ - - def enable_conservation_water(self): - """Enable the conservation of water""" - self.constraints.enable_conservation_water() - def disable_conservation_water(self): - """Disable the conservation of water. - - No equation is solved for the water component in this case.""" - self.constraints.disable_conservation_water() - def set_saturated_system(self): - """The system is saturated with water""" - self.constraints.set_saturated_system() - - # Surface model - # ------------- - - def enable_surface_model(self, site_concentrations): - """Enable the surface sorption model. - - The total concentration of sorption site is 'site_concentrations'""" - self.constraints.enable_surface_model(site_concentrations) - def disable_surface_model(self): - """Disable the surface sorption model""" - self.constraints.disable_surface_model() - - # components - # ---------- - - def set_charge_keeper(self, label): - """Set the charge keeper to be 'label' - - The charge keeper is in charge of the electroneutrality equation""" - cdef int index - index = self.database.component_label_to_id(label) - self.constraints.set_charge_keeper(index) - def add_fixed_fugacity_gas(self, gas_label, component_label, log_fugacity): - """Set 'gas_label' to be a fixed fugacity gas""" - cdef int g_index, c_index - g_index = self.database.gas_label_to_id(gas_label) - c_index = self.database.component_label_to_id(component_label) - self.constraints.add_fixed_fugacity_gas(g_index, c_index, log_fugacity) - def add_fixed_activity_component(self, component_label, log_activity): - """Set 'component_label' to have a fixed fugacity""" - cdef int c_index - c_index = self.database.component_label_to_id(component_label) - self.constraints.add_fixed_activity_component(c_index, log_activity) - - # Inert volume - # ------------ - - def set_inert_volume_fraction(self, volume_fraction_inert): - """Set the volume fraction of inert materials""" - self.constraints.set_inert_volume_fraction(volume_fraction_inert) - -cdef class SpecMiCPFormulation(SpecMiCPConstraints): - """The formulation of a problem""" - def __cinit__(self, DatabaseManager database): - self.formulation = new Formulation() - def __dealloc__(self): - del self.formulation - - def set_mass_solution(self, mass_solution): - """Set the mass of the solution""" - self.formulation.set_mass_solution(mass_solution) - def add_aqueous_species(self, label, concentration): - """Add an aqueous species to the system. - - An aqueous species can be in that case a component or a secondary - aqueous species. - - 'concentration' is in moles per volume - """ - self.formulation.add_aqueous_species(label, concentration) - def add_mineral(self, label, concentration): - """Add a mineral species to the system. - - The mineral can be governed by equilibrium or by kinetics. - - 'concentration' is in moles per volume - """ - self.formulation.add_mineral(label, concentration) - def keep_component(self, label): - """Keep the component 'label' in the database - even if it does not exist in the initial system. - - This must be used if the component will be used later in the computation - """ - self.formulation.keep_component(label) - def set_list_minerals(self, list_minerals): - """Set the list of minerals at equilibrium - - If this function is not called, or the size of the list is zero, - all minerals in the database will be used. - """ - cdef vector[string] list = list_minerals - self.formulation.set_minerals_list(list) - - def initialize_system(self): - """Initialize the system by dissolving the formulation""" - cdef Dissolver* dissolver = new Dissolver(self.database.get_raw_db()) - cdef VectorXd total_conc = dissolver.dissolve(dereference(self.formulation)) - self._get().set_total_concentrations(total_conc) - del dissolver diff --git a/cython/specmicp/database.pxd b/cython/specmicp/database.pxd deleted file mode 100644 index a2a2e13..0000000 --- a/cython/specmicp/database.pxd +++ /dev/null @@ -1,130 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from libcpp.string cimport string -from libcpp.vector cimport vector -from libcpp.map cimport map as cmap -from libcpp cimport bool -from memory cimport shared_ptr -from eigen cimport MatrixXd, VectorXd - - -# The raw container -cdef extern from "database/data_container.hpp" namespace "specmicp::database": - cdef cppclass DataContainer: - int water_index(); - int electron_index(); - - # basis - # ----- - int nb_component() - int nb_aqueous_components() - int get_id_component(string) - string get_label_component(int) - - # aqueous - # ------- - int nb_aqueous() - int get_id_aqueous(string) - string get_label_aqueous(int) - double nu_aqueous(int, int) - double logk_aqueous(int) - - # mineral - # ------- - int nb_mineral() - int get_id_mineral(string) - string get_label_mineral(int) - double nu_mineral(int, int) - double logk_mineral(int) - double molar_mass_mineral(int) - double molar_volume_mineral(int) - - int nb_mineral_kinetic() - int get_id_mineral_kinetic(string) - string get_label_mineral_kinetic(int) - double nu_mineral_kinetic(int, int) - double logk_mineral_kinetic(int) - double molar_mass_mineral_kinetic(int) - double molar_volume_mineral_kinetic(int) - - # gas - # --- - int nb_gas() - int get_id_gas(string) - string get_label_gas(int) - double nu_gas(int, int) - double logk_gas(int) - - -# The database manager -# Used to create and modify the database -cdef extern from "database/database.hpp" namespace "specmicp::database": - cdef cppclass Database: - # cython-cpp interface - list of methods that we can access - # Database should be the only module accessible from python - Database() - Database(shared_ptr[DataContainer]) - Database(string) except + - void parse_database(string) except + - shared_ptr[DataContainer] get_database() - void swap_components(cmap[string, string]) except + - void minerals_keep_only(vector[string]) except + - bool is_valid() - void remove_gas_phases() - void add_gas_phases(string) - void remove_solid_phases() - void add_solid_phases(string) - void remove_sorbed_species() - void add_sorbed_species(string) - # The following methods are from - # specmicp::database::DatabaseModule - int component_label_to_id(string) - int safe_component_label_to_id(string) except + - int aqueous_label_to_id(string) - int safe_aqueous_label_to_id(string) except + - int mineral_label_to_id(string) - int safe_mineral_label_to_id(string) except + - int mineral_kinetic_label_to_id(string) - int safe_mineral_kinetic_label_to_id(string) except + - int gas_label_to_id(string) - int safe_gas_label_to_id(string) except + - - -# header -cdef class DatabaseManager: - """ The Python database handler - - Use this class for checking values in the database - or switching basis/dropping minerals or components... - """ - cdef Database *database - cdef void init_database(self, shared_ptr[DataContainer] raw_db) - cdef shared_ptr[DataContainer] container - cdef shared_ptr[DataContainer] get_raw_db(self) - cdef DataContainer* _get(self) diff --git a/cython/specmicp/database.pyx b/cython/specmicp/database.pyx deleted file mode 100644 index 61fafe2..0000000 --- a/cython/specmicp/database.pyx +++ /dev/null @@ -1,470 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -from libcpp.map cimport map as cmap -from libcpp.pair cimport pair - -from memory cimport shared_ptr -from database cimport Database, DataContainer - - -# Used to indicate that something does not exist -cdef enum: - no_species = -1 - -cdef class DatabaseManager: - """ The Python database handler - - Use this class for checking values in the database - or switching basis/dropping minerals or components... - """ - def __cinit__(self, bytes filepath): - """filepath is the path to the database file""" - if filepath: - self.database = new Database(<string> filepath) - else: - self.database = new Database() - self.container = self.database.get_database() - def __dealloc__(self): - del self.database - cdef void init_database(self, shared_ptr[DataContainer] raw_db): - del self.database - self.database = new Database(raw_db) - self.container = self.database.get_database() - cdef shared_ptr[DataContainer] get_raw_db(self): - return self.container - cdef DataContainer* _get(self): - return self.container.get() - - def is_valid(self): - """Return true of the database is valid. - - If it isn't valid, something went wrong. - """ - return self.database.is_valid(); - - - def remove_sorbed_species(self): - """Remove all the sorbed species in the database.""" - self.database.remove_sorbed_species() - - def add_sorbed_species(self, bytes input_sorbed): - """ Add sorbed species in the database - - 'input_sporbed' is a JSON list of sorbed species formatted as in the - database - """ - self.database.add_sorbed_species(input_sorbed) - - # --------- # - # Component # - # --------- # - - property nb_component: - """The number of component in the database.""" - def __get__(self): return self._get().nb_component() - - def component_check_bounds(self, int idc): - """Check if 'idc' is a correct index for a component. - - Raises a ValueError if it is not correct.""" - if (idc >= self.nb_component or idc < 0): - raise ValueError("'"+str(idc)+ - "' is not a valid index for a component") - - # labels and id - # -------------- - def component_label_to_id(self, bytes comp): - """ Return the id of a component.""" - cdef int ans = self.database.component_label_to_id(comp) - if (ans == no_species): - raise ValueError("Species : '"+comp.decode()+"' is not a component.") - return ans - def component_id_to_label(self, int idc): - """ Return the label of a component.""" - if (idc >= self.nb_component): - raise ValueError("'"+str(idc)+ - "' is not a valid index for a component") - return bytes(self._get().get_label_component(idc)) - - def print_basis(self): - """Print the components in the basis, with their ID""" - print("The basis is :") - cdef int i - for i in range(self.nb_component): - print(" - "+str(i)+" : "+bytes(self._get().get_label_component(i)).decode()) - - # basis switch - # ------------ - - def swap_components(self, dict swapping): - """Swap components in the basis - - swapping is a dictionnary where the keys are the labels of the - components to replace and the values are the labels of the secondary - species to add in the basis. - - Raise value errors if the labels are invalid - """ - cdef cmap[string,string] input_map - cdef int idsp - for (key, value) in swapping.items(): - idsp = self.component_label_to_id(key) - if (idsp == no_species): - raise ValueError("'"+key.decode()+"' is not a valid component.") - idsp = self.aqueous_label_to_id(value) - if (idsp == no_species): - raise ValueError("'"+key.decode()+ - "' is not a valid secondary aqueous species.") - input_map.insert(pair[string, string](key, value)) - self.database.swap_components(input_map) - - # --------------- # - # Aqueous species # - # --------------- # - - property nb_aqueous: - """The number of secondary aqueous species in the database""" - def __get__(self): return self._get().nb_aqueous() - - def aqueous_check_bounds(self, int ida): - """Check if 'ida' is a correct index for a secondary aqueous species. - - Raises a ValueError if it is not correct.""" - if (ida >= self.nb_aqueous or ida < 0): - raise ValueError("'"+str(ida)+ - "' is not a valid index for a secondary aqueous species") - - # labels and id - # ------------- - def aqueous_id_to_label(self, int ids): - self.aqueous_check_bounds(ids) - return bytes(self._get().get_label_aqueous(ids)) - - def aqueous_label_to_id(self, bytes aqueous): - """ Return the id of a secondary aqueous species""" - cdef int ans = self.database.aqueous_label_to_id(aqueous) - if (ans == no_species): - raise ValueError("Species : '"+aqueous.decode()+ - "' is not a secondary aqueous species.") - return ans - - def print_aqueous(self): - """ Print the secondary species""" - print("The secondary aqueous species are :") - cdef int i - for i in range(self.nb_aqueous): - print(" - "+str(i)+" : "+bytes(self._get().get_label_aqueous(i)).decode()) - - # properties - # ---------- - - def nu_aqueous(self, int ids, int idc): - """Return stoichiometric coefficient of a secondary aqueous species""" - self.aqueous_check_bounds(ids) - self.component_check_bounds(idc) - return self._get().nu_aqueous(ids, idc) - def l_nu_aqueous(self, bytes aqueous, bytes component): - """Return stoichiometric coefficient of a secondary aqueous species""" - return self._get().nu_aqueous(self.aqueous_label_to_id(aqueous), - self.component_label_to_id(component)) - - def logk_aqueous(self, int ids): - """Return the equilibrium constant of a secondary aqueous species""" - self.aqueous_check_bounds(ids) - return self._get().logk_aqueous(ids) - def l_logk_aqueous(self, bytes aqueous): - """Return the equilibrium constant of a secondary aqueous species""" - return self._get().logk_aqueous(self.aqueous_label_to_id(aqueous)) - - # ------------ # - # Solid phases # - # ------------ # - - def remove_solid_phases(self): - """Remove all the solid phases in the database. - """ - self.database.remove_solid_phases() - - def add_solid_phases(self, bytes input_solid_phases): - """Add some solid phases in the database. - - 'input_sorbed' is a JSON list of minerals formatted as in the database - """ - self.database.add_solid_phases(input_solid_phases) - - # Equilibrium - # ======= - - property nb_mineral: - """The number of mineral in the database""" - def __get__(self): - return self._get().nb_mineral() - - def mineral_check_bounds(self, int idm): - """Check if 'idm' is a correct index for a mineral. - - Raises a ValueError if it is not correct.""" - if (idm >= self.nb_mineral or idm < 0): - raise ValueError("'"+str(idm)+ - "' is not a valid index for a mineral") - - - # labels and id - # ------------- - - def mineral_id_to_label(self, int idm): - """Return the label of a mineral.""" - self.mineral_check_bounds(idm) - return bytes(self._get().get_label_mineral(idm)) - - def mineral_label_to_id(self, bytes mineral): - """ Return the id of a mineral""" - ans = self.database.mineral_label_to_id(mineral) - if (ans == no_species): - raise ValueError("Species : '"+mineral.decode()+ - "' is not a solid phase at equilibrium in the database.") - return ans - - def print_minerals(self): - """ Print the solid phases at equilibrium""" - print("The solid phases at equilibrium are :") - cdef int i - for i in range(self.nb_mineral): - print(" - "+str(i)+" : "+bytes(self._get().get_label_mineral(i)).decode()) - - def minerals_keep_only(self, list_mineral_to_keep): - """Keep only the solid phases in 'list_mineral_to_keep'""" - # we first verify that the list is valid - for label in list_mineral_to_keep: - self.mineral_label_to_id(label) # just check that it is not raising any error - self.database.minerals_keep_only(list_mineral_to_keep) - - # properties - # ---------- - - def logk_mineral(self, int idm): - """Return the equilibrium constant of a solid phase""" - self.mineral_check_bounds(idm) - return self._get().logk_mineral(idm) - def l_logk_mineral(self, bytes mineral): - """Return the equilibrium constant of a solid phase""" - return self._get().logk_mineral(self.mineral_label_to_id(mineral)) - - def nu_mineral(self, int idm, int idc): - """Return stoichometric coefficient of a mineral""" - self.mineral_check_bounds(idm) - self.component_check_bounds(idc) - return self._get().nu_mineral(idm, idc) - def l_nu_mineral(self, bytes mineral, bytes component): - """Return stoichometric coefficient of a mineral""" - return self._get().nu_mineral(self.mineral_label_to_id(mineral), - self.component_label_to_id(component)) - - def molar_mass_mineral(self, int idm): - """Return the molar mass (kg/mol) of mineral 'idm'""" - self.mineral_check_bounds(idm) - return self._get().molar_mass_mineral(idm) - def l_molar_mass_mineral(self, bytes mineral): - """Return the molar mass (kg/mol) of 'mineral'""" - return self.molar_mass_mineral(self.mineral_label_to_id(mineral)) - - def molar_volume_mineral(self, int idm): - """Return the molar volume (m^3/mol) of mineral 'idm'""" - self.mineral_check_bounds(idm) - return self._get().molar_volume_mineral(idm) - def l_molar_volume_mineral(self, bytes mineral): - """Return the molar volume (m^3/mol) of 'mineral'""" - return self.molar_volume_mineral(self.mineral_label_to_id(mineral)) - - def density_mineral(self, int idm): - """Return the density (kg/m^3) of a mineral 'idm'""" - return (self._get().molar_mass_mineral(idm) - / self._get().molar_volume_mineral(idm)) - def l_density_mineral(self, bytes mineral): - """Return the density (kg/m^3) of a mineral 'idm'""" - return self.density_mineral( - self.mineral_label_to_id(mineral)) - - # Kinetic - # =========== - - property nb_mineral_kinetic: - """The number of mineral governed by kinetics in the database""" - def __get__(self): - return self._get().nb_mineral_kinetic() - - def mineral_kinetic_check_bounds(self, int idm): - """Check if 'idm' is a correct index for a kinetic mineral. - - Raises a ValueError if it is not correct.""" - if (idm >= self.nb_mineral_kinetic or idm < 0): - raise ValueError("'"+str(idm)+ - "' is not a valid index for a kinetic mineral") - - - # labels and id - # ------------- - - def mineral_kinetic_id_to_label(self, int idm): - """Return the label of a mineral.""" - self.mineral_kinetic_check_bounds(idm) - return bytes(self._get().get_label_mineral_kinetic(idm)) - - def mineral_kinetic_label_to_id(self, bytes mineral): - """ Return the id of a mineral governed by kinetics""" - ans = self.database.mineral_kinetic_label_to_id(mineral) - if (ans == no_species): - raise ValueError("Species : '"+mineral.decode()+ - "' is not a solid phase at equilibrium in the database.") - return ans - - - def print_minerals_kinetic(self): - """ Print the solid phases governed by kinetic""" - print("The solid phases governed by kinetics law are :") - cdef int i - for i in range(self.nb_mineral_kinetic): - print(" - "+str(i)+" : "+bytes(self._get().get_label_mineral_kinetic(i)).decode()) - - # properties - # ---------- - - def logk_mineral_kinetic(self, int idm): - """Return the equilibrium constant of a solid phase""" - self.mineral_kinetic_check_bounds(idm) - return self._get().logk_mineral_kinetic(idm) - def l_logk_mineral_kinetic(self, bytes mineral): - """Return the equilibrium constant of a solid phase""" - return self._get().logk_mineral_kinetic( - self.mineral_kinetic_label_to_id(mineral)) - - def nu_mineral_kinetic(self, int idm, int idc): - """Return stoichometric coefficient of a mineral""" - self.mineral_kinetic_check_bounds(idm) - self.component_check_bounds(idc) - return self._get().nu_mineral_kinetic(idm, idc) - def l_nu_mineral_kinetic(self, bytes mineral, bytes component): - """Return stoichometric coefficient of a mineral""" - return self._get().nu_mineral_kinetic( - self.mineral_kinetic_label_to_id(mineral), - self.component_label_to_id(component)) - - def molar_mass_mineral_kinetic(self, int idm): - """Return the molar mass (kg/mol) of mineral 'idm'""" - self.mineral_kinetic_check_bounds(idm) - return self._get().molar_mass_mineral_kinetic(idm) - def l_molar_mass_mineral_kinetic(self, bytes mineral): - """Return the molar mass (kg/mol) of 'mineral'""" - return self.molar_mass_mineral_kinetic( - self.mineral_kinetic_label_to_id(mineral)) - - def molar_volume_mineral_kinetic(self, int idm): - """Return the molar volume (m^3/mol) of mineral 'idm'""" - self.mineral_kinetic_check_bounds(idm) - return self._get().molar_volume_mineral_kinetic(idm) - def l_molar_volume_mineral_kinetic(self, bytes mineral): - """Return the molar volume (m^3/mol) of 'mineral'""" - return self.molar_volume_mineral_kinetic( - self.mineral_kinetic_label_to_id(mineral)) - - def density_mineral_kinetic(self, int idm): - """Return the density (kg/m^3) of a mineral 'idm'""" - return (self._get().molar_mass_mineral_kinetic(idm) - / self._get().molar_volume_mineral_kinetic(idm)) - def l_density_mineral_kinetic(self, bytes mineral): - """Return the density (kg/m^3) of a mineral 'idm'""" - return self.density_mineral_kinetic( - self.mineral_kinetic_label_to_id(mineral)) - - - # ======== - # Gas - # ======== - - property nb_gas: - """The number of gas in the database""" - def __get__(self): - return self._get().nb_gas() - - def gas_check_bounds(self, int idg): - """Check if idg is a correct index for a gas""" - if (idg >= self.nb_gas or idg < 0): - raise ValueError("'"+str(idg)+ - "' is not a valid index for a gas") - - def gas_id_to_label(self, int idg): - """Return the label of a gas.""" - self.gas_check_bounds(idg) - return bytes(self._get().get_label_gas(idg)) - - def gas_label_to_id(self, bytes gas): - """ Return the id of a mineral""" - ans = self.database.gas_label_to_id(gas) - if (ans == no_species): - raise ValueError("Species : '"+gas.decode()+ - "' is not a gas in the database.") - return ans - - def remove_gas_phases(self): - """Remove all the gas species in the database.""" - self.database.remove_gas_phases() - - def add_gas_phases(self, bytes input_gas_phases): - """Add some gas into the database. - - 'input_gas_phases' is a JSON list of gas formatted as in the database. - """ - self.database.add_gas_phases(input_gas_phases) - - def nu_gas(self, int idg, int idc): - """Return the stoichiometric coefficient of 'idc' in 'idg' dissolution - reaction.""" - self.gas_check_bounds(idg) - self.component_check_bounds(idc) - return self._get().nu_gas(idg, idc) - - def l_nu_gas(self, bytes gas, bytes component): - """Return the stoihiometric coefficient of 'component' in the 'gas' - dissolution reaction.""" - return self._get().nu_gas(self.gas_label_to_id(gas), - self.component_label_to_id(component)) - - def logk_gas(self, int idg): - """Return the equilibrium constant of a gas""" - self.gas_check_bounds(idg) - if (idg >= self.nb_gas or idg < 0): - raise ValueError("Index : '"+str(idg) - +"'is not valid for a gas.") - return self._get().logk_mineral(idg) - - def l_logk_gas(self, bytes gas): - """Return the equilibrium constant of a gas""" - return self._get().logk_gas(self.gas_label_to_id(gas)) \ No newline at end of file diff --git a/cython/specmicp/init_log.hpp b/cython/specmicp/init_log.hpp deleted file mode 100644 index ba11b17..0000000 --- a/cython/specmicp/init_log.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/*------------------------------------------------------------------------------- - -Copyright (c) 2014,2015 F. Georget <fabieng@princeton.edu>, Princeton University -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------------------------------------------------------------------*/ - -#ifndef SPECMICP_CYTHON_INITLOG_HPP -#define SPECMICP_CYTHON_INITLOG_HPP - -#include "utils/log.hpp" -#include <iostream> - -namespace specmicp { - - -inline void init_logger_cout_debug() { - init_logger(&std::cout, specmicp::logger::Debug); -} - -inline void init_logger_cout_warning() { - init_logger(&std::cout, specmicp::logger::Warning); -} - -inline void init_logger_cout_error() { - init_logger(&std::cout, specmicp::logger::Error); -} - -inline void init_logger_cerr_debug() { - init_logger(&std::cerr, specmicp::logger::Debug); -} - -inline void init_logger_cerr_warning() { - init_logger(&std::cerr, specmicp::logger::Warning); -} - -inline void init_logger_cerr_error() { - init_logger(&std::cerr, specmicp::logger::Error); -} - - - -} // end namespace specmicp - -#endif // SPECMICP_CYTHON_INITLOG_HPP diff --git a/cython/specmicp/is_solver_successful.hpp b/cython/specmicp/is_solver_successful.hpp deleted file mode 100644 index e4ed6f4..0000000 --- a/cython/specmicp/is_solver_successful.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/*------------------------------------------------------------------------------- - -Copyright (c) 2014,2015 F. Georget <fabieng@princeton.edu>, Princeton University -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------------------------------------------------------------------*/ - - -#ifndef SPECMICP_CYTHON_SUCCESSFUL_SOLVER -#define SPECMICP_CYTHON_SUCCESSFUL_SOLVER - -#include "micpsolver/micpsolver_structs.hpp" -#include <type_traits> - -// just for cython - -namespace specmicp { -namespace micpsolver { - -//! \brief Return true if the solver is successful -inline bool is_solver_successful(MiCPSolverReturnCode return_code) -{ - return (return_code > MiCPSolverReturnCode::Success); -} - -//! \brief Cast the return code to an int -inline std::underlying_type<MiCPSolverReturnCode>::type cast_return_code(MiCPSolverReturnCode return_code) -{ - return static_cast<std::underlying_type<MiCPSolverReturnCode>::type>(return_code); -} - -} // end namespace micpsolver -} // end namespace specmicp - -#endif //SPECMICP_CYTHON_SUCCESSFUL_SOLVER diff --git a/cython/specmicp/logger.pxd b/cython/specmicp/logger.pxd deleted file mode 100644 index 155e2d2..0000000 --- a/cython/specmicp/logger.pxd +++ /dev/null @@ -1,35 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -cdef extern from "init_log.hpp" namespace "specmicp": - void c_init_looger_cout_debug "specmicp::init_logger_cout_debug" () - void c_init_logger_cout_warning "specmicp::init_logger_cout_warning" () - void c_init_logger_cout_error "specmicp::init_logger_cout_error" () - void c_init_logger_cerr_debug "specmicp::init_logger_cerr_debug" () - void c_init_logger_cerr_warning "specmicp::init_logger_cerr_warning" () - void c_init_logger_cerr_error "specmicp::init_logger_cerr_error" () diff --git a/cython/specmicp/logger.pyx b/cython/specmicp/logger.pyx deleted file mode 100644 index 0335e74..0000000 --- a/cython/specmicp/logger.pyx +++ /dev/null @@ -1,47 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -cimport logger as lg - -def init_logger_cout_debug(): - lg.c_init_logger_cout_debug() - -def init_logger_cout_warning(): - lg.c_init_logger_cout_warning() - -def init_logger_cout_error(): - lg.c_init_logger_cout_error() - -def init_logger_cerr_debug(): - lg.c_init_logger_cerr_debug() - -def init_logger_cerr_warning(): - lg.c_init_logger_cerr_warning() - -def init_logger_cerr_error(): - lg.c_init_logger_cerr_error() diff --git a/cython/specmicp/set_units.hpp b/cython/specmicp/set_units.hpp deleted file mode 100644 index 9123954..0000000 --- a/cython/specmicp/set_units.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/*------------------------------------------------------------------------------- - -Copyright (c) 2014,2015 F. Georget <fabieng@princeton.edu>, Princeton University -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------------------------------------------------------------------*/ - -#ifndef SPECMICP_CYTHON_SETUNITS -#define SPECMICP_CYTHON_SETUNITS - -#include "physics/units.hpp" - -namespace specmicp { -namespace units { - -inline void set_meter(LengthUnit& length) {length = LengthUnit::meter;} -inline void set_decimeter(LengthUnit& length) {length = LengthUnit::decimeter;} -inline void set_centimeter(LengthUnit& length) {length = LengthUnit::centimeter;} - -} // end namespace units -} // end namespace specmicp - -#endif diff --git a/cython/specmicp/solution.pxd b/cython/specmicp/solution.pxd deleted file mode 100644 index f5cd3eb..0000000 --- a/cython/specmicp/solution.pxd +++ /dev/null @@ -1,102 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from libcpp cimport bool -from memory cimport shared_ptr -from database cimport DataContainer, DatabaseManager -from units cimport UnitsSet -from eigen cimport VectorXd - -# The solution -# ------------- -# note: access is restrictive since the user should use -# the extractor class to acces the data -cdef extern from "specmicp/adimensional/adimensional_system_solution.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemSolution: - AdimensionalSystemSolution() - AdimensionalSystemSolution(const AdimensionalSystemSolution&) - bool is_valid - -# The solution extractor -# ---------------------- -cdef extern from "specmicp/adimensional/adimensional_system_solution_extractor.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemSolutionExtractor: - AdimensionalSystemSolutionExtractor( - const AdimensionalSystemSolution&, - shared_ptr[DataContainer], - UnitsSet - ) - - double volume_fraction_water() - double density_water() - double saturation_water() - double saturation_gas_phase() - double porosity() - double pE() - double Eh() - double molality_component(int) - double activity_component(int) - double volume_fraction_mineral(int) - double mole_concentration_mineral(int) - double mass_concentration_mineral(int) - double saturation_index(int) - double free_surface_concentration() - double ionic_strength() - double pH() - double molality_aqueous(int) - double activity_aqueous(int) - double fugacity_gas(int) - double molality_sorbed_species(int) - double total_aqueous_concentration(int) - double total_solid_concentration(int) - double total_immobile_concentration(int) - double volume_fraction_inert() - VectorXd get_main_variables() - shared_ptr[DataContainer] get_database() - - -# Cython wrapper -# -------------- -# the extractor only contains a reference to the solution -# so we need to store the solution also -cdef class SpecMiCPSolution: - cdef AdimensionalSystemSolution* solution - cdef AdimensionalSystemSolutionExtractor* extractor - cdef DatabaseManager db - - cdef void set_solution( - self, - const AdimensionalSystemSolution& solution, - shared_ptr[DataContainer] database, - UnitsSet units_set - ) - cdef AdimensionalSystemSolution* _get(self) - cdef VectorXd get_main_variables(self) - - diff --git a/cython/specmicp/solution.pyx b/cython/specmicp/solution.pyx deleted file mode 100644 index c3f2318..0000000 --- a/cython/specmicp/solution.pyx +++ /dev/null @@ -1,208 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from solution cimport SpecMiCPSolution -from cython.operator cimport dereference -from specmicp.database cimport DataContainer, DatabaseManager -from units cimport UnitsSet - -cdef class SpecMiCPSolution: - """Contain a solution from the SpecMiCP solver - - It correspond to the AdimensionalSystemSolutionExtractor of the c++ API - - This class should only be created by the SpecMiCP solver. - """ - - def __dealloc__(self): - if self.extractor: - del self.extractor - if self.solution: - del self.solution - cdef void set_solution( - self, - const AdimensionalSystemSolution& solution, - shared_ptr[DataContainer] database, - UnitsSet units_set - ): - """Set the solution -- only callable from cython code !""" - self.solution = new AdimensionalSystemSolution(solution) - self.extractor = new AdimensionalSystemSolutionExtractor( - dereference(self.solution), - database, - units_set - ) - self.db = DatabaseManager(b"") - self.db.init_database(self.extractor.get_database()) - - cdef AdimensionalSystemSolution* _get(self): - """Return the solution, only callable from cython code""" - return self.solution - - cdef VectorXd get_main_variables(self): - """Return the vector of main variables""" - return self.extractor.get_main_variables() - - # water and gas volume fraction - # ----------------------------- - def volume_fraction_water(self): - """Return the volume fraction of water""" - return self.extractor.volume_fraction_water() - def density_water(self): - """Return the density of water (in the correct units)""" - return self.extractor.density_water() - def porosity(self): - """Return the porosity""" - return self.extractor.porosity() - def saturation_water(self): - """Return the saturation of the liquid phase""" - return self.extractor.saturation_water() - def saturation_gas_phase(self): - """Return the saturation of the gas phase""" - return self.extractor.saturation_gas_phase() - def volume_fraction_inert(self): - """Return the volume fraction of inert phases""" - return self.extractor.volume_fraction_inert() - # solution properties - # ------------------- - def pE(self): - """Return pE""" - return self.extractor.pE() - def Eh(self): - """Return Eh""" - return self.extractor.Eh() - def pH(self): - """Return the pH of the solution""" - return self.extractor.pH() - def ionic_strength(self): - """Return the ionic strength of the solution""" - return self.extractor.ionic_strength() - # components - def molality_component(self, index): - """Return molality of component 'index'""" - return self.extractor.molality_component(index) - def l_molality_component(self, label): - """Return molality of component 'label'""" - idc = self.db.component_label_to_id(label) - return self.extractor.molality_component(idc) - def activity_component(self, index): - """Return the molality of component 'index'""" - return self.extractor.activity_component(index) - def l_activity_component(self, label): - """Return the molality of component 'label'""" - idc = self.db.component_label_to_id(label) - return self.extractor.activity_component(idc) - # minerals - # -------- - def volume_fraction_mineral(self, index): - """Return the volume fraction of mineral 'index'""" - return self.extractor.volume_fraction_mineral(index) - def l_volume_fraction_mineral(self, label): - """Return the volume fraction of mineral 'label'""" - idm = self.db.mineral_label_to_id(label) - return self.extractor.volume_fraction_mineral(idm) - def mole_concentration_mineral(self, index): - """Return the concentration (mol/V) of mineral 'index'""" - return self.extractor.mole_concentration_mineral(index) - def l_mole_concentration_mineral(self, label): - """Return the concentration (mol/V) of mineral 'label'""" - idm = self.db.mineral_label_to_id(label) - return self.extractor.mole_concentration_mineral(idm) - def mass_concentration_mineral(self, index): - """Return the concentration (M/V) of mineral 'index'""" - return self.extractor.mass_concentration_mineral(index) - def l_mass_concentration_mineral(self, label): - """Return the concentration (M/V) of mineral 'label'""" - idm = self.db.mineral_label_to_id(label) - return self.extractor.mass_concentration_mineral(label) - def saturation_index(self, index): - """Return the saturation index of mineral 'index'""" - return self.extractor.saturation_index(index) - def l_saturation_index(self, label): - """Return the saturation index of mineral 'index'""" - idm = self.db.mineral_label_to_id(label) - return self.extractor.saturation_index(idm) - # aqueous species - # --------------- - def molality_aqueous(self, index): - """Return the molality of aqueous 'index'""" - return self.extractor.molality_aqueous(index) - def l_molality_aqueous(self, label): - """Return the molality of aqueous 'index'""" - ida= self.db.aqueous_label_to_id(label) - return self.extractor.molality_aqueous(ida) - def activity_aqueous(self, index): - """Return the activity of aqueous 'index'""" - return self.extractor.activity_aqueous(index) - def l_activity_aqueous(self, label): - """Return the activity of aqueous 'index'""" - ida= self.db.aqueous_label_to_id(label) - return self.extractor.activity_aqueous(ida) - # gas - # --- - def fugacity_gas(self, index): - """Return the fugacity of gas 'index'""" - return self.extractor.fugacity_gas(index) - # sorption model - # -------------- - def concentration_free_surface_sites(self): - """Return the concentration of free surface sites""" - return self.extractor.free_surface_concentration() - def molality_sorbed_species(self, index): - """Return the molality of sorbed_species 'index'""" - return self.extractor.molality_sorbed_species(index) - # total concentrations - # -------------------- - def total_aqueous_concentration(self, index): - """Return the total aqueous concentration of component 'index'""" - return self.extractor.total_aqueous_concentration(index) - def l_total_aqueous_concentration(self, label): - """Return the total aqueous concentration of component 'index'""" - idc = self.db.component_label_to_id(label) - return self.extractor.total_aqueous_concentration(idc) - def total_solid_concentration(self, index): - """Return the total solid concentration of component 'index'""" - return self.extractor.total_solid_concentration(index) - def l_total_solid_concentration(self, label): - """Return the total solid concentration of component 'index'""" - idc = self.db.component_label_to_id(label) - return self.extractor.total_solid_concentration(idc) - def total_immobile_concentration(self, index): - """Return the total immobile (solid+sorbed) concentration of component - 'index'""" - return self.extractor.total_immobile_concentration(index) - def l_total_immobile_concentration(self, label): - """Return the total immobile (solid+sorbed) concentration of component - 'label'""" - idc = self.db.component_label_to_id(label) - return self.extractor.total_immobile_concentration(idc) - - - def get_database(self): - """Return the database""" - return self.db diff --git a/cython/specmicp/solver.pxd b/cython/specmicp/solver.pxd deleted file mode 100644 index 3aa591a..0000000 --- a/cython/specmicp/solver.pxd +++ /dev/null @@ -1,72 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -from libcpp.map cimport map as cmap -from libcpp cimport bool -from libcpp.string cimport string -from eigen cimport VectorXd -from memory cimport shared_ptr -from database cimport DatabaseManager, DataContainer - -from solution cimport AdimensionalSystemSolution -from constraints cimport AdimensionalSystemConstraints -from solver_options cimport MiCPPerformance, AdimensionalSystemSolverOptions, AdimensionalSystemOptions, MiCPSolverOptions - -# The SpecMiCP Solver -# ------------------- -cdef extern from "specmicp/adimensional/adimensional_system_solver.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemSolver: - AdimensionalSystemSolver( - shared_ptr[DataContainer], - const AdimensionalSystemConstraints& - ) - AdimensionalSystemSolver( - shared_ptr[DataContainer], - const AdimensionalSystemConstraints&, - const AdimensionalSystemSolution& - ) - - MiCPPerformance solve(VectorXd&, bool) nogil except +, - AdimensionalSystemSolution get_raw_solution(VectorXd&) - void run_pcfm(VectorXd&) - void initialise_variables(VectorXd&, double, cmap[string, double]) - void initialise_variables(VectorXd&, double, double) - - AdimensionalSystemSolverOptions& get_options() nogil # read-only - -# Wrapper to the solver -# --------------------- -cdef class SpecMiCPSolver: - cdef DatabaseManager database - cdef AdimensionalSystemSolver* solver - cdef VectorXd* variables - cdef bool is_solved - - cdef AdimensionalSystemSolverOptions* get_options(self) nogil - cdef AdimensionalSystemOptions* get_system_options(self) nogil - cdef MiCPSolverOptions* get_micpsolver_options(self) nogil diff --git a/cython/specmicp/solver.pyx b/cython/specmicp/solver.pyx deleted file mode 100644 index b5b79c0..0000000 --- a/cython/specmicp/solver.pyx +++ /dev/null @@ -1,255 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from libcpp.map cimport map as cmap -from libcpp.string cimport string -from libcpp.utility cimport pair -from solver cimport SpecMiCPSolver, AdimensionalSystemSolver -from database cimport DatabaseManager -from constraints cimport SpecMiCPConstraints, AdimensionalSystemConstraints -from solver_options cimport MiCPSolverReturnCode, MiCPPerformance, is_solver_successful -from solution cimport SpecMiCPSolution -cimport units -from cython.operator cimport dereference - -cdef class SpecMiCPSolver: - def __cinit__( - self, - DatabaseManager database not None, - SpecMiCPConstraints constraints not None, - SpecMiCPSolution solution - ): - """Initialisation""" - self.is_solved = False - self.database = database - if solution is None: - self.solver = new AdimensionalSystemSolver( - database.get_raw_db(), - dereference(constraints._get()) - ) - else: - self.solver = new AdimensionalSystemSolver( - database.get_raw_db(), - dereference(constraints._get()), - dereference(solution._get()) - ) - self.variables = new VectorXd(solution.get_main_variables()) - - def __dealloc__(self): - if self.solver: - del self.solver - if self.variables: - del self.variables - - cdef AdimensionalSystemSolverOptions* get_options(self) nogil: - """Return the options""" - return &(self.solver.get_options()) - - cdef AdimensionalSystemOptions* get_system_options(self) nogil: - """Return the options of the SpecMiCP program""" - return &(self.solver.get_options().system_options) - - cdef MiCPSolverOptions* get_micpsolver_options(self) nogil: - """Return the MiCPSolver options""" - return &(self.solver.get_options().solver_options) - - def get_solution(self): - """Return the solution""" - if not self.solver: - raise RuntimeError("No solver") - if not self.is_solved: - raise RuntimeError("No solution available") - solution = SpecMiCPSolution() - solution.set_solution( - self.solver.get_raw_solution(dereference(self.variables)), - self.database.get_raw_db(), - self.solver.get_options().units_set - ) - return solution - - def initialize_variables(self, water_saturation, log_molalities_component): - """Initialize the variables - - The log_molalities_component can be - - a double : the initial value gor the log_10 of the molalities - - a dictionnary {"label component": log_molalities} - """ - cdef cmap[string, double] map_comp - if not self.variables: - self.variables = new VectorXd() - if hasattr(log_molalities_component, "items"): - for (key, value) in log_molalities_component.items(): - map_comp.insert(pair[string, double](key, value)) - self.solver.initialise_variables(dereference(self.variables), - float(water_saturation), - map_comp) - else: - self.solver.initialise_variables(dereference(self.variables), - float(water_saturation), - float(log_molalities_component) - ) - - def solve(self, initialize=True): - """Solve the problem""" - cdef MiCPPerformance perf - cdef bool init = initialize - if not self.variables: - self.variables = new VectorXd() - with nogil: - perf = self.solver.solve(dereference(self.variables), init) - if not is_solver_successful(perf.return_code): - raise RuntimeError("Error - the system cannot be solved.") - self.is_solved = True - - # Options - # ======= - - # adimensionalsolver options - # -------------------------- - - def set_length_unit(self, length_unit): - """Set the length unit""" - if length_unit in ("m", "meter"): - units.set_meter(self.get_options().units_set.length) - elif length_unit in ("dm", "decimeter"): - units.set_decimeter(self.get_options().units_set.length) - elif length_unit in ("cm", "centimeter"): - units.set_centimeter(self.get_options().units_set.length) - else: - raise ValueError("Unit : " + str(length_unit) + "is not recognized") - - def enable_restart(self): - """Allow the solve to be restarted in case of failure""" - self.get_options().allow_restart = True - def disable_restart(self): - """Failure to solve the problem is critical""" - self.get_options().allow_restart = False - - def enable_pcfm(self): - """Enable the positive continuous fraction method""" - self.get_options().use_pcfm = True - def disable_pcfm(self): - """Disable the positive continuous fraction method""" - self.get_options().use_pcfm = False - - # System options - # --------------- - - def enable_non_ideality(self): - """Enable the nonideality model of the aqueous solution""" - self.get_system_options().non_ideality = True - def disable_non_ideality(self): - """Disable the nonideality model of the aqueous solution""" - self.get_system_options().non_ideality = False - - def set_non_ideality_max_iterations(self, max_iterations): - """Set the maximum iterations allowed for the non ideality model""" - self.get_system_options().non_ideality_max_iter = int(max_iterations) - - def set_non_ideality_tolerance(self, tolerance): - """Set the tolerance for the non ideality model""" - self.get_system_options().non_ideality_tolerance = float(tolerance) - - def set_non_ideality_start_factor(self, start_factor): - """A factor that governs the non-ideality computation""" - self.get_system_options().start_non_ideality_computation = float(start_factor) - - def set_under_relaxation_factor(self, factor): - """Set the under relaxtion factor """ - self.get_system_options().under_relaxation_factor = float(factor) - - def set_restart_concentration(self, log_molality): - """Set the molality used to re-initialize the problem in case of failure""" - self.get_system_options().restart_concentration = float(log_molality) - - def set_new_component_concentration(self, log_molality): - """Set the concentration for a new component""" - self.get_system_options().new_component_concentration = float(log_molality) - - def set_cutoff_total_concentrations(self, cutoff): - """Set the cutoff for the total concentrations""" - self.get_system_options().cutoff_total_concentration = float(cutoff) - - # MiCPSolver options - # ------------------ - - def set_tolerance(self, residuals_tol): - """Set the residuals tolerance""" - self.get_micpsolver_options().set_tolerance(residuals_tol) - def set_tolerances(self, residuals_tol, step_tol): - """"Set the residuals and the step tolerances""" - self.get_micpsolver_options().set_tolerance(residuals_tol, step_tol) - - def set_maximum_iterations(self, max_iterations): - """Set the maximum number of operations""" - self.get_micpsolver_options().set_maximum_iterations(max_iterations) - - def set_maximum_step_length(self, max_step_length, max_iter_at_max_length=None): - """Set the maximum step length""" - if max_iter_at_max_length is not None: - self.get_micpsolver_options().set_maximum_step_length( - max_step_length, max_iter_at_max_length) - else: - self.get_micpsolver_options().set_maximum_step_length( - max_step_length) - - def disable_descent_direction(self): - """Disable the descent direction condition""" - self.get_micpsolver_options().disable_descent_direction() - def enable_descent_direction(self, factor, power): - """Enable the descent direction condition""" - self.get_micpsolver_options().enable_descent_direction(factor, power) - - def disable_condition_check(self): - """Disable the descent direction""" - self.get_micpsolver_options().disable_condition_check() - def enable_condition_check(self, threshold): - """Enable the condition check""" - self.get_micpsolver_options().enable_condition_check(threshold) - - def disable_non_monotone_linesearch(self): - """Disable the non monotone linesearch""" - self.get_micpsolver_options().disable_non_monotone_linesearch() - def enable_non_monotone_linesearch(self): - """Enable the non monotone linesearch""" - self.get_micpsolver_options().enable_non_monotone_linesearch() - - def disable_jacobian_scaling(self): - """Disable the Jacobian scaling""" - self.get_micpsolver_options().disable_scaling() - def enable_jacobian_scaling(self): - """Enable the Jacobian scaling""" - self.get_micpsolver_options().enable_scaling() - - def disable_crashing(self): - """Disable the crashing""" - self.get_micpsolver_options().disable_crashing() - def enable_crashing(self): - """Enable the crashing""" - self.get_micpsolver_options().enable_crashing() diff --git a/cython/specmicp/solver_options.pxd b/cython/specmicp/solver_options.pxd deleted file mode 100644 index e3ecc86..0000000 --- a/cython/specmicp/solver_options.pxd +++ /dev/null @@ -1,123 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -from libcpp cimport bool -from units cimport UnitsSet - -cdef extern from "micpsolver/micpsolver_structs.hpp" namespace "specmicp::micpsolver": - cdef cppclass MiCPSolverOptions: - MiCPSolverOptions() - int max_iter - double fvectol - double steptol - double condition_limit - double penalization_factor - double maxstep - int maxiter_maxstep - double factor_descent_condition - double power_descent_condition - bool use_crashing - double coeff_accept_newton_step - bool use_scaling - double factor_gradient_search_direction - double projection_min_variable - double threshold_stationary_point - int max_factorization_step - - void set_maximum_iterations(int) - void set_maximum_step_length(double) - void set_maximum_step_length(double, int) - void disable_descent_direction() - void enable_descent_direction(double, double) - void disable_condition_check() - void enable_condition_check(double) - void disable_non_monotone_linesearch() - void enable_scaling() - void disable_scaling() - void enable_crashing() - void disable_crashing() - void enable_non_monotone_linesearch() - void set_tolerance(double) - void set_tolerance(double, double) - - - cdef enum MiCPSolverReturnCode: - LolItsNotSupposedToHappen "specmicp::micpsolver::MiCPSolverReturnCode::LolItsNotSupposedToHappen" - MaxStepTakenTooManyTimes "specmicp::micpsolver::MiCPSolverReturnCode::MaxStepTakenTooManyTimes" - FailedToSolveLinearSystem "specmicp::micpsolver::MiCPSolverReturnCode::FailedToSolveLinearSystem" - MaxIterations "specmicp::micpsolver::MiCPSolverReturnCode::MaxIterations" - StationaryPoint "specmicp::micpsolver::MiCPSolverReturnCode::StationaryPoint" - NotConvergedYet "specmicp::micpsolver::MiCPSolverReturnCode::NotConvergedYet" - Success "specmicp::micpsolver::MiCPSolverReturnCode::Success" - ResidualMinimized "specmicp::micpsolver::MiCPSolverReturnCode::ResidualMinimized" - ErrorMinimized "specmicp::micpsolver::MiCPSolverReturnCode::ErrorMinimized" - - cdef cppclass MiCPPerformance: - MiCPPerformance() - int nb_call_residuals - int nb_call_jacobian - int nb_factorization - int nb_gradient_step - int nb_crashing_iterations - int nb_iterations - bool max_taken - int nb_max_taken - int nb_consecutive_max_taken - MiCPSolverReturnCode return_code - - cdef enum NCPfunction: - penFB_function "specmicp::micpsolver::NCPfunction::penalizedFB" - min_function "specmicp::micpsolver::NCPfunction::min" - -cdef extern from "is_solver_successful.hpp" namespace "specmicp::micpsolver": - cdef bool is_solver_successful(MiCPSolverReturnCode) - cdef int cast_return_code(MiCPSolverReturnCode) - -cdef extern from "specmicp/adimensional/adimensional_system_structs.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemOptions: - bool non_ideality - int non_ideality_max_iter - double scaling_electron - double non_ideality_tolerance - double under_relaxation_factor - double restart_concentration - double new_component_concentration - double start_non_ideality_computation - double cutoff_total_concentration - -cdef extern from "specmicp/adimensional/adimensional_system_solver_structs.hpp" namespace "specmicp": - cdef cppclass AdimensionalSystemSolverOptions: - AdimensionalSystemSolverOptions() - MiCPSolverOptions solver_options - AdimensionalSystemOptions system_options - UnitsSet units_set - bool allow_restart - bool use_pcfm - bool force_pcfm - diff --git a/cython/specmicp/units.pxd b/cython/specmicp/units.pxd deleted file mode 100644 index 146421a..0000000 --- a/cython/specmicp/units.pxd +++ /dev/null @@ -1,49 +0,0 @@ -#Copyright (c) 2014,2015 Fabien Georget <fabieng@princeton.edu>, Princeton -#University #All rights reserved. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -#1. Redistributions of source code must retain the above copyright notice, this -#list of conditions and the following disclaimer. -# -#2. Redistributions in binary form must reproduce the above copyright notice, -#this list of conditions and the following disclaimer in the documentation -#and/or other materials provided with the distribution. -# -#3. Neither the name of the copyright holder nor the names of its contributors -#may be used to endorse or promote products derived from this software without -#specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -#OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -cdef extern from "physics/units.hpp" namespace "specmicp::units": - cdef enum LengthUnit: - meter "specmicp::units::LengthUnit::meter" - decimeter "specmicp::units::LengthUnit::decimeter" - centimeter "specmicp::units::LengthUnit::centimeter" - - cdef enum MassUnit: - kilogram "specmicp::units::MassUnit::kilogram" - gram "specmicp::units::MassUnit::gram" - - cdef cppclass UnitsSet: - UnitsSet() - MassUnit mass - LengthUnit length - -# These are the function that allows us to overcome the "enum class" cython incompatibility -cdef extern from "set_units.hpp" namespace "specmicp::units": - void set_meter(LengthUnit&) - void set_decimeter(LengthUnit&) - void set_centimeter(LengthUnit&) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 69ca1d7..9f8b24d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,93 +1,78 @@ ################## Tests ######################################## include(CatchTest) set(PROJECT_TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${PROJECT_TEST_DIR}) add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND}) # make check is also valid # Catch test #=========== # MiCPSolver # ---------- set(MICPSOLVER_TEST_DIR micpsolver) add_catch_test(NAME micpsolver SOURCES ${MICPSOLVER_TEST_DIR}/test_micpsolver.cpp ${MICPSOLVER_TEST_DIR}/condition_number.cpp ${MICPSOLVER_TEST_DIR}/ncp_functions.cpp ${MICPSOLVER_TEST_DIR}/micpsolver.cpp ) # ODEInt # ---------- set(ODEINT_TEST_DIR odeint) add_catch_test(NAME odeint SOURCES ${ODEINT_TEST_DIR}/test_odeint.cpp ${ODEINT_TEST_DIR}/butchertableau.cpp ${ODEINT_TEST_DIR}/embeddedrungekutta.cpp ) # Database # -------- add_subdirectory(database) # Specmicp : Adim system # ---------------------- add_catch_test(NAME specmicp_adim SOURCES specmicp/adim/test_specmicp_adim.cpp specmicp/adim/adimensional_system.cpp specmicp/adim/adimensional_system_solver.cpp specmicp/adim/adimensional_system_conditions.cpp specmicp/adim/adimensional_system_problem_solver.cpp specmicp/adim/adimensional_system_thermocarbo.cpp specmicp/adim/adimensional_system_carboalu.cpp specmicp/adim/adimensional_system_pcfm.cpp specmicp/adim/adimensional_system_oxydoreduc.cpp LINK_LIBRARIES specmicp_static specmicp_database_static ) # Specmicp : Adim Kinetics # ------------------------ set(ADIMKINETICS_TEST_DIR ${PROJECT_TEST_DIR}/specmicp/adim_kinetics) add_catch_test(NAME specmicp_adim_kinetics SOURCES ${ADIMKINETICS_TEST_DIR}/test_specmicp_adim_kinetics.cpp ${ADIMKINETICS_TEST_DIR}/kinetics_variables.cpp LINK_LIBRARIES specmicp_static specmicp_database_static ) # Reactmicp # --------- add_subdirectory( reactmicp ) - -# cython test -# ----------- - -# the cython tests are generated from the cython/CMakeLists.txt file - -if (SPECMICP_BUILD_CYTHON) - add_test(NAME database_py - COMMAND ${PYTHON_EXECUTABLE} "database.py" - ) - - add_test(NAME test_specmicp_py - COMMAND ${PYTHON_EXECUTABLE} "test_specmicp.py" - ) -endif()