pax_global_header00006660000000000000000000000064141215206570014515gustar00rootroot0000000000000052 comment=a287a1c1a9b03cde1fe609b433ad9a284d8228c7 tools-2021.2/000077500000000000000000000000001412152065700127435ustar00rootroot00000000000000tools-2021.2/CHANGELOG.rst000066400000000000000000000143711412152065700147720ustar00rootroot00000000000000For more detailed information about the changes see the history of the `repository `__. Version 2021.2 (released 19.09.21) ================================== - changed tolerance for getting element names from mass (#378) - format code with clang-12.0.1 (#380) Version 2021.1 (released 18.07.21) ================================== - fix build on F34 and openSUSE (#361) - add support for oneapi mkl (#363, #369) Version 2021 (released 13.03.21) ================================ - fix CI on rawhide (#336) - add auto-cancel workflow to GitHub Actions (#343) - remove unused ext/alloc_traits.h from tests (#354) Version 2021-rc.1 (released 15.01.21) ===================================== - add support of txt2tqs 3.4 (#208) - fix MKL:: target creation (#207, #265, #269, #270) - use local includes (#204) - add more support for units (#200) - add methods to update user input with defaults (#222) - fix usage of PROJECT\_SOURCE\_DIR in cmake (#230) - fix merging calculator defaults (#226, #227) - document cmake options and packages (#231) - make fftw3 a public dependency (#235) - rename WITH\_RC\_FILES to INSTALL\_RC\_FILES (#236) - check calculator input options (#232, #233) - allow calculator choices to be a list (#239) - inject defaults into calculator values (#241) - fixed bug introduced by defaults injection (#241, #242) - make votca\_compare always executable in builddir (#244) - add rel. compare to votca\_compare (#143) - standardize header formatting (#246) - move CI to GitHub Ations (#251, #254, #256, #258, #260, #274, #275, #296, #321) - improve mkl detection (#257, #299) - clean up installed cmake find modules (#263) - update codacy badge (#264) - add mkl builds to CI (#267, #271) - convert markdown files to rst files (#272) - enable CXX only in CMake (#273) - format code with clang-10 (#277) - fix clang-9 conversion warning (#276) - add class to writeand read matrices (#290) - Bump required CMake version to 3.12 (#301) - refactored getenv() into separate function (#302) - use unique_ptr in factory (#303) Version 1.6.4 (released 12.01.21) ================================= - no changes Version 1.6.3 (released 09.12.20) ================================= - switch to ghcr.io for CI (#297) - use master .clang-format in format action (#304, #307) - strip windows line endings in readers (#309) Version 1.6.2 *SuperGitta* (released 22.08.20) ================================= - format code with clang-10 (#278) - move CI to GitHub Actions (#280, #285, #287) - fix build with mkl (#283) Version 1.6.1 (released 21.06.20) ================================= - fix build with mkl (#229) - fix build with non-system libfftw (#234) - fix CI on Ubuntu-20.04 (#237) - fix bug related to calling c abs instead of c++ fabs (#248) - updated floating point comparison in akimaspline.h (#248) - fix compile error in structure parameters by adding hash function (#248) Version 1.6 *SuperPelagia* (released 17.04.20) ============================================== - fix clang-10 warnings (#217) - clean up VOTCARC.\* (#220) - fix exported target with mkl (#223, #224) Version 1.6\_rc2 (released 10.02.20) ==================================== - fix inheritance bug in cmake files (#197) - fix bug in table class (#196) - fix build on 32-bit archs (#199) - remove old doxygen target (#211) Version 1.6\_rc1 (released 04.12.19) ==================================== - replaced fftw with Eigen3 fft - replaced random with std::random implementation - added many unit tests - formated code with clang-format - major cmake refactor Version 1.5.1 (released 20.11.19) ================================= - switch votca\_compare to python3 - more clear error message for xmlreader - fix build on CentOs7 Version 1.5 *SuperVictor* (released 31.01.19) ============================================= - enable gitlab CI Version 1.5\_rc3 (released 19.01.19) ==================================== - travis: fixed bug in building tags Version 1.5\_rc2 (released 16.01.19) ==================================== - histogramnew: refactor to fix memory lead Version 1.5\_rc1 (released 28.12.18) ==================================== - added unit testing - Eigen added as a dependency - removed GSL dependency Version 1.2.2 ============= - cmake: allow static fftw and gsl - added dummy c function for cmake - fixed conflicting type headers (real was defined) Version 1.2.1 ============= - fixed soname of libs - improved cmake checks and error messages - fixed pkg-config file Version 1.2 (SuperDoris) ======================== - changed buildsystem to cmake - added database class through sqlite3 Version 1.1.2 ============= - fixed head of votca-tools manpage Version 1.1.1 ============= - just a bugfix release Version 1.1 (SuperAnn) ====================== - added thread class - added spline class, with akima spline, linear spline - added man7 page - random.cc: avoid calling of exit() - added lexical cast class Version 1.0.1 ============= - fixed a bug in VOTCARC.csh for empty LD\_LIBRARY\_PATH - completion file has moved back to csg - added --disable-rc-files to configure - updated bundled libtool to 2.2.10 Version 1.0 =========== - added libvotca\_expat to allow compiling without expat - allow comments in tables - added application class to create standardized applications - all boost dependecy are now in tools - fixes in table format, flags is always last row now - allow compling without fftw (needed for csg\_boltzmann only) - allow compling without gsl (needed for csg\_resample and csg\_fmatch) Version 1.0\_rc5 ================ - using libexpat instead of libxml2 - added libvotca\_boost to allow compiling without boost - using pkg-config to detect package flags - compiles under AIX with xlC - added VOTCARC to initialize all votca parts - updated configure, see --help Version 1.0\_rc4 ================ - using libtool to build shared libs Version 1.0\_rc3 ================ - corrected bug in tokenizer - fixed a bug in calculation of version string - some fixes concerning autotools Version 1.0\_rc2 ================ - fixed typo in calculation of version string - added NOTICE and LICENSE to the dist tarball Version 1.0\_rc1 ================ - initial version tools-2021.2/CMakeLists.txt000066400000000000000000000120001412152065700154740ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.12) project(votca-tools LANGUAGES CXX) set(PROJECT_VERSION "2021.2") string(REGEX REPLACE "[-.].*$" "" SOVERSION "${PROJECT_VERSION}") if (NOT ${SOVERSION} MATCHES "^[0-9]+$") message(FATAL_ERROR "Could not determine SOVERSION (${SOVERSION}) from ${PROJECT_VERSION}") endif (NOT ${SOVERSION} MATCHES "^[0-9]+$") set(PROJECT_CONTACT "https://github.com/votca/tools/issues") # Cmake modules/macros are in a subdirectory to keep this file cleaner set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules) if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS) #release comes with -O3 by default set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS) ###################################################################### # compiler tests # these need ot be done early (before further tests). ##################################################################### include(CheckCXXCompilerFlag) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11 ######################################################################## # User input options # ######################################################################## option(BUILD_SHARED_LIBS "Build shared libs" ON) include(GNUInstallDirs) include(FeatureSummary) option(ENABLE_TESTING "Build and enable testing stuff" OFF) add_feature_info(ENABLE_TESTING ENABLE_TESTING "Enable unit tests") if(ENABLE_TESTING) enable_testing() include(FindPackageHandleStandardArgs) find_program(VALGRIND_EXECUTABLE "valgrind") find_package_handle_standard_args(VALGRIND REQUIRED_VARS VALGRIND_EXECUTABLE) endif(ENABLE_TESTING) ######################################################################## #Find external packages ######################################################################## if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/.git) find_package(Git) set_package_properties(Git PROPERTIES TYPE OPTIONAL PURPOSE "Generates version for development version") endif(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/.git) find_package(Threads REQUIRED) set_package_properties(Threads PROPERTIES TYPE REQUIRED PURPOSE "Used for thread parallelization") find_package(Boost 1.53.0 REQUIRED COMPONENTS program_options filesystem system ) set_package_properties(Boost PROPERTIES TYPE REQUIRED PURPOSE "Extended C++ libraries") option(BUILD_MANPAGES "Build manpages (might lead to problem on system without rpath" ON) add_feature_info(BUILD_MANPAGES BUILD_MANPAGES "Build manpages (disable for cross-compile)") #define this target here, so that individual man pages can append to it. add_custom_target(manpages ALL) ######################################################################## # Checks what linear algebra packages are installed # ######################################################################## set(MKL_THREAD_LAYER "Intel OpenMP" CACHE STRING "The thread layer to choose for MKL") find_package(MKL) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set_package_properties(MKL PROPERTIES TYPE OPTIONAL PURPOSE "Enables accelerated performance with MKL") endif (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) find_package(Eigen3 3.3.0 NO_MODULE REQUIRED) set_package_properties(Eigen3 PROPERTIES TYPE REQUIRED PURPOSE "C++ vector data structures") message(STATUS "Found Eigen3: ${Eigen3_DIR}") if(MKL_FOUND) # MKL has its internal fftw3 implementation unset(FFTW3_FOUND) else() find_package(FFTW3) set_package_properties(FFTW3 PROPERTIES TYPE RECOMMENDED PURPOSE "Enables FFT functionality") endif() ######################################################################## # Basic system tests (standard libraries, headers, functions, types) # ######################################################################## include(CheckIncludeFileCXX) foreach(HEADER cassert cmath fstream functional iostream limits list map ostream sstream stack stdexcept string vector) check_include_file_cxx(${HEADER} FOUND_${HEADER}) if(NOT FOUND_${HEADER}) message(FATAL_ERROR "Could not find needed header - ${HEADER}") endif(NOT FOUND_${HEADER}) endforeach(HEADER) set(MATH_LIBRARIES "m" CACHE STRING "math library") mark_as_advanced( MATH_LIBRARIES ) ###################################### # Include the following subdirectory # ###################################### add_subdirectory(src) add_subdirectory(include/votca/tools) add_subdirectory(scripts) add_subdirectory(share/man) configure_file(${PROJECT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake IMMEDIATE @ONLY) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) feature_summary(INCLUDE_QUIET_PACKAGES WHAT ALL) endif (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) tools-2021.2/CMakeModules/000077500000000000000000000000001412152065700152545ustar00rootroot00000000000000tools-2021.2/CMakeModules/FindFFTW3.cmake000066400000000000000000000036121412152065700177120ustar00rootroot00000000000000# - Find fftw3 # Find the native FFTW3 headers and libraries. # # FFTW3_INCLUDE_DIRS - where to find fftw3.h, etc. # FFTW3_LIBRARIES - List of libraries when using fftw3. # FFTW3_FOUND - True if fftw3 found. # # Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) # # 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. # find_package(PkgConfig) if(COMMAND set_package_properties) set_package_properties(PkgConfig PROPERTIES TYPE RECOMMENDED PURPOSE "Used to detect fftw package") endif() pkg_check_modules(PC_FFTW3 fftw3) find_path(FFTW3_INCLUDE_DIR fftw3.h HINTS ${PC_FFTW3_INCLUDE_DIRS}) find_library(FFTW3_LIBRARY NAMES fftw3 HINTS ${PC_FFTW3_LIBRARY_DIRS} ) include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set FFTW3_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(FFTW3 DEFAULT_MSG FFTW3_LIBRARY FFTW3_INCLUDE_DIR ) # Copy the results to the output variables and target. if(FFTW3_FOUND) set(FFTW3_LIBRARIES ${FFTW3_LIBRARY} ) set(FFTW3_INCLUDE_DIRS ${FFTW3_INCLUDE_DIR} ) if(NOT TARGET FFTW3::fftw3) add_library(FFTW3::fftw3 UNKNOWN IMPORTED) set_target_properties(FFTW3::fftw3 PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "${FFTW3_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${FFTW3_INCLUDE_DIRS}") endif() endif() mark_as_advanced(FFTW3_INCLUDE_DIR FFTW3_LIBRARY ) tools-2021.2/CMakeModules/FindMKL.cmake000066400000000000000000000410521412152065700175040ustar00rootroot00000000000000# Copyright (c) 2018, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. The complete license # agreement can be obtained at: http://arrayfire.com/licenses/BSD-3-Clause # # A FindMKL script based on the recommendations by the Intel's Link Line # Advisor. It currently only tested on the 2018 version of MKL on Windows, # Linux, and OSX but it should work on older versions. # # To use this module call the mklvars.(sh,bat) script before you call cmake. This # script is located in the bin folder of your mkl installation. This will set the # MKLROOT environment variable which will be used to find the libraries on your system. # # Example: # set(MKL_THREAD_LAYER "TBB") # find_package(MKL) # # add_executable(myapp main.cpp) # target_link_libraries(myapp PRIVATE MKL::Shared) # # This module bases its behavior based on the following variables: # # ``MKL_THREAD_LAYER`` # The threading layer that needs to be used by the MKL library. This # Defines which library will be used to parallelize the MKL kernels. Possible # options are TBB(Default), GNU OpenMP, Intel OpenMP, Sequential # # This module provides the following :prop_tgt:'IMPORTED' targets: # # ``MKL::Shared`` # Target used to define and link all MKL libraries required by Intel's Link # Line Advisor. This usually the only thing you need to link against unless # you want to link against the single dynamic library version of MKL # (libmkl_rt.so) # # ``MKL::Static`` # Target used to define and link all MKL libraries required by Intel's Link # Line Advisor for a static build. This will still link the threading libraries # using dynamic linking as advised by the Intel Link Advisor # # Optional: # # ``MKL::ThreadLayer{_STATIC}`` # Target used to define the threading layer(TBB, OpenMP, etc.) based on # MKL_THREAD_LAYER variable. # # ``MKL::ThreadingLibrary`` # Target used to define the threading library(libtbb, libomp, etc) that the # application will need to link against. # # ``MKL::Interface`` # Target used to determine which interface library to use(32bit int or 64bit # int). # # ``MKL::Core`` # Target for the dynamic library dispatcher # # ``MKL::RT`` # Target for the single dynamic library # # ``MKL::{mkl_def;mkl_mc;mkl_mc3;mkl_avx;mkl_avx2;mkl_avx512}{_STATIC}`` # Targets for MKL kernel libraries. include(CheckTypeSize) include(FindPackageHandleStandardArgs) find_package(OpenMP QUIET) check_type_size("int" INT_SIZE BUILTIN_TYPES_ONLY LANGUAGE CXX) set(MKL_THREAD_LAYER "TBB" CACHE STRING "The thread layer to choose for MKL") set_property(CACHE MKL_THREAD_LAYER PROPERTY STRINGS "TBB" "GNU OpenMP" "Intel OpenMP" "Sequential") message(STATUS "MKL: Thread Layer(${MKL_THREAD_LAYER}) Interface(${INT_SIZE}-byte Integer)") if(NOT MKL_THREAD_LAYER STREQUAL MKL_THREAD_LAYER_LAST) unset(MKL::ThreadLayer CACHE) unset(MKL::ThreadingLibrary CACHE) unset(MKL_ThreadLayer_LINK_LIBRARY CACHE) unset(MKL_ThreadLayer_STATIC_LINK_LIBRARY CACHE) unset(MKL_ThreadLayer_DLL_LIBRARY CACHE) unset(MKL_ThreadingLibrary_LINK_LIBRARY CACHE) unset(MKL_ThreadingLibrary_STATIC_LINK_LIBRARY CACHE) unset(MKL_ThreadingLibrary_DLL_LIBRARY CACHE) set(MKL_THREAD_LAYER_LAST ${MKL_THREAD_LAYER} CACHE INTERNAL "" FORCE) endif() find_path(MKL_INCLUDE_DIR NAMES mkl.h mkl_blas.h mkl_cblas.h PATHS /opt/intel /opt/intel/mkl /opt/intel/oneapi/mkl/latest $ENV{MKLROOT} /opt/intel/compilers_and_libraries/linux/mkl /usr/include/mkl PATH_SUFFIXES include IntelSWTools/compilers_and_libraries/windows/mkl/include ) if(MKL_INCLUDE_DIR) mark_as_advanced(MKL_INCLUDE_DIR) endif() function(find_version) set(options "") set(single_args VAR FILE REGEX) set(multi_args "") cmake_parse_arguments(find_version "${options}" "${single_args}" "${multi_args}" ${ARGN}) file(READ ${find_version_FILE} VERSION_FILE_CONTENTS) string(REGEX MATCH ${find_version_REGEX} VERSION_LINE "${VERSION_FILE_CONTENTS}") set(${ARGV0} ${CMAKE_MATCH_1} PARENT_SCOPE) endfunction() if(MKL_INCLUDE_DIR) find_file(MKL_VERSION_HEADER NAMES mkl_version.h PATHS ${MKL_INCLUDE_DIR}) find_version(MKL_MAJOR_VERSION FILE ${MKL_VERSION_HEADER} REGEX "__INTEL_MKL__ * ([0-9]+)") find_version(MKL_MINOR_VERSION FILE ${MKL_VERSION_HEADER} REGEX "__INTEL_MKL_MINOR__ * ([0-9]+)") find_version(MKL_UPDATE_VERSION FILE ${MKL_VERSION_HEADER} REGEX "__INTEL_MKL_UPDATE__ * ([0-9]+)") find_version(MKL_VERSION_MACRO FILE ${MKL_VERSION_HEADER} REGEX "INTEL_MKL_VERSION * ([0-9]+)") set(MKL_VERSION_STRING ${MKL_MAJOR_VERSION}.${MKL_MINOR_VERSION}.${MKL_UPDATE_VERSION}) mark_as_advanced(MKL_VERSION_HEADER) endif() find_path(MKL_FFTW_INCLUDE_DIR NAMES fftw3_mkl.h HINTS ${MKL_INCLUDE_DIR}/fftw) if(MKL_FFTW_INCLUDE_DIR) mark_as_advanced(MKL_FFTW_INCLUDE_DIR) endif() if(WIN32) if(${MSVC_VERSION} GREATER_EQUAL 1900) set(msvc_dir "vc_mt") set(shared_suffix "_dll") set(md_suffix "md") else() message(WARNING "MKL: MS Version not supported for MKL") endif() endif() if(WIN32) set(ENV_LIBRARY_PATHS "$ENV{LIB}") if (${CMAKE_VERSION} VERSION_GREATER 3.14) message(VERBOSE "MKL environment variable(LIB): ${ENV_LIBRARY_PATHS}") endif() else() string(REGEX REPLACE ":" ";" ENV_LIBRARY_PATHS "$ENV{LIBRARY_PATH}") if (${CMAKE_VERSION} VERSION_GREATER 3.14) message(VERBOSE "MKL environment variable(LIBRARY_PATH): ${ENV_LIBRARY_PATHS}") endif() endif() # Finds and creates libraries for MKL with the MKL:: prefix # # Parameters: # NAME: A variable name describing the library # LIBRARY_NAME: The library that needs to be searched # # OPTIONS: # DLL_ONLY On Windows do not search for .lib files. Ignored in other # platforms # SEARCH_STATIC Search for static versions of the libraries as well as the # dynamic libraries # # Output Libraries: # MKL::${NAME} # MKL::${NAME}_STATIC # # Output Variables # MKL_${NAME}_LINK_LIBRARY: on Unix: *.so on Windows *.lib # MKL_${NAME}_STATIC_LINK_LIBRARY: on Unix: *.a on Windows *.lib # MKL_${NAME}_DLL_LIBRARY: on Unix: "" on Windows *.dll function(find_mkl_library) set(options "SEARCH_STATIC;DLL_ONLY") set(single_args NAME LIBRARY_NAME) set(multi_args "") cmake_parse_arguments(mkl_args "${options}" "${single_args}" "${multi_args}" ${ARGN}) if(TARGET MKL::${mkl_args_NAME}) return() endif() add_library(MKL::${mkl_args_NAME} SHARED IMPORTED) add_library(MKL::${mkl_args_NAME}_STATIC STATIC IMPORTED) if(NOT (WIN32 AND mkl_args_DLL_ONLY)) find_library(MKL_${mkl_args_NAME}_LINK_LIBRARY NAMES ${mkl_args_LIBRARY_NAME}${shared_suffix} ${mkl_args_LIBRARY_NAME}${md_suffix} lib${mkl_args_LIBRARY_NAME}${md_suffix} ${mkl_args_LIBRARY_NAME} PATHS /opt/intel/mkl/lib /opt/intel/tbb/lib /opt/intel/lib /opt/intel/oneapi/mkl/latest/lib /opt/intel/oneapi/compiler/latest/linux/compiler/lib /opt/intel/oneapi/lib $ENV{MKLROOT}/lib ${ENV_LIBRARY_PATHS} /opt/intel/compilers_and_libraries/linux/mkl/lib PATH_SUFFIXES IntelSWTools/compilers_and_libraries/windows/mkl/lib/intel64 IntelSWTools/compilers_and_libraries/windows/compiler/lib/intel64 IntelSWTools/compilers_and_libraries/windows/tbb/lib/intel64/${msvc_dir} "" intel64 intel64/gcc4.7) if(MKL_${mkl_args_NAME}_LINK_LIBRARY) if (CMAKE_VERSION VERSION_GREATER 3.14) message(VERBOSE "MKL_${mkl_args_NAME}_LINK_LIBRARY: ${MKL_${mkl_args_NAME}_LINK_LIBRARY}") endif() mark_as_advanced(MKL_${mkl_args_NAME}_LINK_LIBRARY) endif() endif() #message(STATUS "NAME: ${mkl_args_NAME} LIBNAME: ${mkl_args_LIBRARY_NAME} MKL_${mkl_args_NAME}_LINK_LIBRARY ${MKL_${mkl_args_NAME}_LINK_LIBRARY}") if(mkl_args_SEARCH_STATIC) find_library(MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY NAMES ${CMAKE_STATIC_LIBRARY_PREFIX}${mkl_args_LIBRARY_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX} PATHS /opt/intel/mkl/lib /opt/intel/tbb/lib /opt/intel/lib /opt/intel/oneapi/mkl/latest/lib /opt/intel/oneapi/compiler/latest/linux/compiler/lib /opt/intel/oneapi/lib $ENV{MKLROOT}/lib ${ENV_LIBRARY_PATHS} /opt/intel/compilers_and_libraries/linux/mkl/lib PATH_SUFFIXES "" intel64 intel64/gcc4.7 IntelSWTools/compilers_and_libraries/windows/mkl/lib/intel64 IntelSWTools/compilers_and_libraries/windows/compiler/lib/intel64 IntelSWTools/compilers_and_libraries/windows/tbb/lib/intel64/${msvc_dir} ) if(MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY) if (CMAKE_VERSION VERSION_GREATER 3.14) message(VERBOSE "MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY: ${MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY}") endif() mark_as_advanced(MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY) endif() endif() set_target_properties(MKL::${mkl_args_NAME} PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR}" IMPORTED_LOCATION "${MKL_${mkl_args_NAME}_LINK_LIBRARY}" IMPORTED_NO_SONAME TRUE) set_target_properties(MKL::${mkl_args_NAME}_STATIC PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR}" IMPORTED_LOCATION "${MKL_${mkl_args_NAME}_STATIC_LINK_LIBRARY}" IMPORTED_NO_SONAME TRUE) if(WIN32) find_file(MKL_${mkl_args_NAME}_DLL_LIBRARY NAMES ${CMAKE_SHARED_LIBRARY_PREFIX}${mkl_args_LIBRARY_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX} ${CMAKE_SHARED_LIBRARY_PREFIX}${mkl_args_LIBRARY_NAME}${md_suffix}${CMAKE_SHARED_LIBRARY_SUFFIX} lib${mkl_args_LIBRARY_NAME}${md_suffix}${CMAKE_SHARED_LIBRARY_SUFFIX} $ENV{LIB} $ENV{LIBRARY_PATH} PATH_SUFFIXES IntelSWTools/compilers_and_libraries/windows/redist/intel64/mkl IntelSWTools/compilers_and_libraries/windows/redist/intel64/compiler IntelSWTools/compilers_and_libraries/windows/redist/intel64/tbb/${msvc_dir} NO_SYSTEM_ENVIRONMENT_PATH) set_target_properties(MKL::${mkl_args_NAME} PROPERTIES IMPORTED_LOCATION "${MKL_${mkl_args_NAME}_DLL_LIBRARY}" IMPORTED_IMPLIB "${MKL_${mkl_args_NAME}_LINK_LIBRARY}") mark_as_advanced(MKL_${mkl_args_NAME}_DLL_LIBRARY) endif() endfunction() find_mkl_library(NAME Core LIBRARY_NAME mkl_core SEARCH_STATIC) find_mkl_library(NAME RT LIBRARY_NAME mkl_rt) # MKL can link against Intel OpenMP, GNU OpenMP, TBB, and Sequential if(MKL_THREAD_LAYER STREQUAL "Intel OpenMP") find_mkl_library(NAME ThreadLayer LIBRARY_NAME mkl_intel_thread SEARCH_STATIC) find_mkl_library(NAME ThreadingLibrary LIBRARY_NAME iomp5) elseif(MKL_THREAD_LAYER STREQUAL "GNU OpenMP") find_package(OpenMP REQUIRED) find_mkl_library(NAME ThreadLayer LIBRARY_NAME mkl_gnu_thread SEARCH_STATIC) set(MKL_ThreadingLibrary_LINK_LIBRARY ${OpenMP_gomp_LIBRARY}) if(MKL_ThreadingLibrary_LINK_LIBRARY) mark_as_advanced(MKL_${mkl_args_NAME}_LINK_LIBRARY) endif() if(NOT TARGET MKL::ThreadingLibrary) add_library(MKL::ThreadingLibrary SHARED IMPORTED) set_target_properties(MKL::ThreadingLibrary PROPERTIES IMPORTED_LOCATION "${MKL_ThreadingLibrary_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES OpenMP::OpenMP_CXX) endif() elseif(MKL_THREAD_LAYER STREQUAL "TBB") find_mkl_library(NAME ThreadLayer LIBRARY_NAME mkl_tbb_thread SEARCH_STATIC) find_mkl_library(NAME ThreadingLibrary LIBRARY_NAME tbb) elseif(MKL_THREAD_LAYER STREQUAL "Sequential") find_mkl_library(NAME ThreadLayer LIBRARY_NAME mkl_sequential SEARCH_STATIC) endif() if("${INT_SIZE}" EQUAL 4) find_mkl_library(NAME Interface LIBRARY_NAME mkl_intel_lp64 SEARCH_STATIC) else() find_mkl_library(NAME Interface LIBRARY_NAME mkl_intel_ilp64 SEARCH_STATIC) endif() set(MKL_KernelLibraries "mkl_def;mkl_mc;mkl_mc3;mkl_avx;mkl_avx2;mkl_avx512") foreach(lib ${MKL_KernelLibraries}) find_mkl_library(NAME ${lib} LIBRARY_NAME ${lib} DLL_ONLY) if(MKL_${lib}_LINK_LIBRARY) list(APPEND MKL_RUNTIME_KERNEL_LIBRARIES_TMP ${MKL_${lib}_LINK_LIBRARY}) endif() if(MKL_${lib}_DLL_LIBRARY) list(APPEND MKL_RUNTIME_KERNEL_LIBRARIES_TMP ${MKL_${lib}_DLL_LIBRARY}) endif() endforeach() set(MKL_RUNTIME_KERNEL_LIBRARIES "${MKL_RUNTIME_KERNEL_LIBRARIES_TMP}" CACHE STRING "MKL kernel libraries targeting different CPU architectures") mark_as_advanced(MKL_RUNTIME_KERNEL_LIBRARIES) # Bypass developer warning that the first argument to find_package_handle_standard_args (MKL_...) does not match # the name of the calling package (MKL) # https://cmake.org/cmake/help/v3.17/module/FindPackageHandleStandardArgs.html set(FPHSA_NAME_MISMATCHED TRUE) find_package_handle_standard_args(MKL FAIL_MESSAGE "Could NOT find MKL: Source the compilervars.sh or mklvars.sh scripts included with your installation of MKL. This script searches for the libraries in MKLROOT, LIBRARY_PATHS(Linux), and LIB(Windows) environment variables" VERSION_VAR MKL_VERSION_STRING REQUIRED_VARS MKL_INCLUDE_DIR MKL_Core_LINK_LIBRARY MKL_Interface_LINK_LIBRARY MKL_ThreadingLibrary_LINK_LIBRARY MKL_ThreadLayer_LINK_LIBRARY) find_package_handle_standard_args(MKL_Static FAIL_MESSAGE "Could NOT find MKL: Source the compilervars.sh or mklvars.sh scripts included with your installation of MKL. This script searches for the libraries in MKLROOT, LIBRARY_PATHS(Linux), and LIB(Windows) environment variables" VERSION_VAR MKL_VERSION_STRING REQUIRED_VARS MKL_INCLUDE_DIR MKL_Core_STATIC_LINK_LIBRARY MKL_Interface_STATIC_LINK_LIBRARY MKL_ThreadLayer_STATIC_LINK_LIBRARY) if(NOT WIN32) find_library(M_LIB m) mark_as_advanced(M_LIB) endif() if(MKL_FOUND AND NOT TARGET MKL::Shared) add_library(MKL::Shared SHARED IMPORTED) if(MKL_THREAD_LAYER STREQUAL "Sequential") set_target_properties(MKL::Shared PROPERTIES IMPORTED_LOCATION "${MKL_Core_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "MKL::Interface;MKL::ThreadLayer;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) else() set_target_properties(MKL::Shared PROPERTIES IMPORTED_LOCATION "${MKL_Core_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "MKL::Interface;MKL::ThreadLayer;MKL::ThreadingLibrary;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) endif() if(WIN32) set_target_properties(MKL::Shared PROPERTIES IMPORTED_LOCATION "${MKL_Core_DLL_LIBRARY}" IMPORTED_IMPLIB "${MKL_Core_LINK_LIBRARY}") endif() endif() if(MKL_Static_FOUND AND NOT TARGET MKL::Static) add_library(MKL::Static STATIC IMPORTED) if(UNIX AND NOT APPLE) if(MKL_THREAD_LAYER STREQUAL "Sequential") set_target_properties(MKL::Static PROPERTIES IMPORTED_LOCATION "${MKL_Core_STATIC_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "-Wl,--start-group;MKL::Core_STATIC;MKL::Interface_STATIC;MKL::ThreadLayer_STATIC;-Wl,--end-group;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) else() set_target_properties(MKL::Static PROPERTIES IMPORTED_LOCATION "${MKL_Core_STATIC_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "-Wl,--start-group;MKL::Core_STATIC;MKL::Interface_STATIC;MKL::ThreadLayer_STATIC;-Wl,--end-group;MKL::ThreadingLibrary;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) endif() else() if(MKL_THREAD_LAYER STREQUAL "Sequential") set_target_properties(MKL::Static PROPERTIES IMPORTED_LOCATION "${MKL_Core_STATIC_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "MKL::Core_STATIC;MKL::Interface_STATIC;MKL::ThreadLayer_STATIC;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) else() set_target_properties(MKL::Static PROPERTIES IMPORTED_LOCATION "${MKL_Core_STATIC_LINK_LIBRARY}" INTERFACE_LINK_LIBRARIES "MKL::Core_STATIC;MKL::Interface_STATIC;MKL::ThreadLayer_STATIC;MKL::ThreadingLibrary;${CMAKE_DL_LIBS};${M_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${MKL_INCLUDE_DIR};${MKL_FFTW_INCLUDE_DIR}" IMPORTED_NO_SONAME TRUE) endif() endif() endif() tools-2021.2/CMakeModules/cmake_uninstall.cmake.in000066400000000000000000000016551412152065700220430ustar00rootroot00000000000000IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) STRING(REGEX REPLACE "\n" ";" files "${files}") FOREACH(file ${files}) MESSAGE(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") IF(EXISTS "$ENV{DESTDIR}${file}") EXEC_PROGRAM( "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval ) IF(NOT "${rm_retval}" STREQUAL 0) MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") ENDIF(NOT "${rm_retval}" STREQUAL 0) ELSE(EXISTS "$ENV{DESTDIR}${file}") MESSAGE(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") ENDIF(EXISTS "$ENV{DESTDIR}${file}") ENDFOREACH(file) tools-2021.2/CMakeModules/gitscript.cmake000066400000000000000000000026601412152065700202720ustar00rootroot00000000000000if (GIT_EXECUTABLE) # refresh git index execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh WORKING_DIRECTORY ${TOP_SOURCE_DIR} TIMEOUT 5 OUTPUT_QUIET ERROR_VARIABLE EXEC_ERR OUTPUT_STRIP_TRAILING_WHITESPACE ) #later use git describe here execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD WORKING_DIRECTORY ${TOP_SOURCE_DIR} OUTPUT_VARIABLE THIS_GIT_ID OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD WORKING_DIRECTORY ${TOP_SOURCE_DIR} OUTPUT_VARIABLE _HAS_CHANGES OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) if (NOT "${_HAS_CHANGES}" STREQUAL "") set(THIS_GIT_ID "${THIS_GIT_ID} (dirty)") endif() message("Current git revision is ${THIS_GIT_ID}") set(THIS_GIT_ID "gitid: ${THIS_GIT_ID}") else() set (THIS_GIT_ID) endif() file(READ ${INPUT} CONTENT) string(REGEX REPLACE "#TOOLS_GIT_ID#" "${THIS_GIT_ID}" NEW_CONTENT "${CONTENT}") file(WRITE "${OUTPUT}.tmp" "${NEW_CONTENT}") file(COPY "${OUTPUT}.tmp" DESTINATION "${OUTPUT}.tmp.x" FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different ${OUTPUT}.tmp.x/${OUTPUT}.tmp ${OUTPUT}) execute_process(COMMAND ${CMAKE_COMMAND} -E remove ${OUTPUT}.tmp ${OUTPUT}.tmp.x/${OUTPUT}.tmp) execute_process(COMMAND ${CMAKE_COMMAND} -E remove_directory ${OUTPUT}.tmp.x) tools-2021.2/CMakeModules/gitversion.cmake000066400000000000000000000022621412152065700204510ustar00rootroot00000000000000if (GIT_EXECUTABLE) # refresh git index execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh WORKING_DIRECTORY ${TOP_SOURCE_DIR} TIMEOUT 5 OUTPUT_QUIET ERROR_VARIABLE EXEC_ERR OUTPUT_STRIP_TRAILING_WHITESPACE ) #later use git describe here execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD WORKING_DIRECTORY ${TOP_SOURCE_DIR} OUTPUT_VARIABLE TOOLS_GIT_ID OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process( COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD WORKING_DIRECTORY ${TOP_SOURCE_DIR} OUTPUT_VARIABLE _HAS_CHANGES OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) if (NOT "${_HAS_CHANGES}" STREQUAL "") set(TOOLS_GIT_ID "${TOOLS_GIT_ID} (dirty)") endif() message("Current git revision is ${TOOLS_GIT_ID}") set(TOOLS_GIT_ID "gitid: ${TOOLS_GIT_ID}") else() set (TOOLS_GIT_ID) endif() set (GIT_HEADER "gitversion.h") set (NEW_GIT_HEADER "new_gitversion.h") file(WRITE ${NEW_GIT_HEADER} "static const std::string gitversion = \"${TOOLS_GIT_ID}\";\n") execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different ${NEW_GIT_HEADER} ${GIT_HEADER}) execute_process(COMMAND ${CMAKE_COMMAND} -E remove ${NEW_GIT_HEADER}) tools-2021.2/LICENSE000066400000000000000000000261361412152065700137600ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. tools-2021.2/NOTICE000066400000000000000000000006531412152065700136530ustar00rootroot00000000000000Versatile Object-oriented Toolkit for Coarse-graining Applications Copyright 2009-2011 The VOTCA Development Team This product includes software developed at The VOTCA Development Team (http://www.votca.org). This software contains code, in particular the vec, matrix, objectfactory and property class, which was derived from a project by V. Ruehle. The code in src/libboost is taken from the Boost package (www.boost.org). tools-2021.2/README.rst000066400000000000000000000015471412152065700144410ustar00rootroot00000000000000|Codacy Badge| |codecov| |CI| |DOI| This is the tools module of the VOTCA package. Further information on VOTCA can be found at http://www.votca.org You can contact the VOTCA Development Team at devs@votca.org. .. |Codacy Badge| image:: https://app.codacy.com/project/badge/Grade/ace4de06384644b5855fcee4c3c20966 :target: https://www.codacy.com/gh/votca/tools?utm_source=github.com&utm_medium=referral&utm_content=votca/tools&utm_campaign=Badge_Grade .. |codecov| image:: https://codecov.io/gh/votca/tools/branch/master/graph/badge.svg :target: https://codecov.io/gh/votca/tools .. |CI| image:: https://github.com/votca/votca/workflows/CI/badge.svg?branch=master :target: https://github.com/votca/votca/actions?query=workflow%3ACI+branch%3Amaster .. |DOI| image:: https://zenodo.org/badge/23848711.svg :target: https://zenodo.org/badge/latestdoi/23848711 tools-2021.2/include/000077500000000000000000000000001412152065700143665ustar00rootroot00000000000000tools-2021.2/include/votca/000077500000000000000000000000001412152065700155025ustar00rootroot00000000000000tools-2021.2/include/votca/tools/000077500000000000000000000000001412152065700166425ustar00rootroot00000000000000tools-2021.2/include/votca/tools/CMakeLists.txt000066400000000000000000000004101412152065700213750ustar00rootroot00000000000000configure_file(votca_tools_config.h.in ${CMAKE_CURRENT_BINARY_DIR}/votca_tools_config.h) file(GLOB_RECURSE VOTCA_HEADERS *.h ${CMAKE_CURRENT_BINARY_DIR}/votca_tools_config.h ) install(FILES ${VOTCA_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/votca/tools) tools-2021.2/include/votca/tools/akimaspline.h000066400000000000000000000066351412152065700213220ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_AKIMASPLINE_H #define VOTCA_TOOLS_AKIMASPLINE_H // Standard includes #include // Local VOTCA includes #include "eigen.h" #include "floatingpointcomparison.h" #include "spline.h" namespace votca { namespace tools { /** * * \brief An Akima Spline Class * * does Akima interpolation based on the paper * "A new method of interpolation and smooth curve fitting based on local * procedures" * * Fitting is not supported. In order to fit data, do linear fitting and * interpolate the linear fitted values by Akima interpolation. */ class AkimaSpline : public Spline { public: // default constructor AkimaSpline() = default; // destructor ~AkimaSpline() override = default; /** * \brief Calculate the slope according to the original Akima paper ("A New * Method of Interpolation and Smooth Curve Fitting Based on Local * Procedures") \param slopes m1 to m4 of line segments connecting the five * data points \return slope handles all special cases to determine the slope * t based on slopes m1,m2,m3,m4 */ double getSlope(double m1, double m2, double m3, double m4); // construct an interpolation spline // x, y are the the points to construct interpolation, both vectors must be of // same size void Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // fit spline through noisy data // x,y are arrays with noisy data, both vectors must be of same size void Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // Calculate the function value double Calculate(double r) override; // Calculate the function derivative double CalculateDerivative(double r) override; using Spline::Calculate; using Spline::CalculateDerivative; protected: // p1,p2,p3,p4 and t1,t2 (same identifiers as in Akima paper, page 591) Eigen::VectorXd p0; Eigen::VectorXd p1; Eigen::VectorXd p2; Eigen::VectorXd p3; Eigen::VectorXd t; }; inline double AkimaSpline::Calculate(double r) { Index interval = getInterval(r); double z = r - _r[interval]; return p0(interval) + p1(interval) * z + p2(interval) * z * z + p3(interval) * z * z * z; } inline double AkimaSpline::CalculateDerivative(double r) { Index interval = getInterval(r); double z = r - _r[interval]; return +p1(interval) + 2.0 * p2(interval) * z + 3.0 * p3(interval) * z * z; } inline double AkimaSpline::getSlope(double m1, double m2, double m3, double m4) { if (isApproximatelyEqual(m1, m2, 1E-15) && isApproximatelyEqual(m3, m4, 1E-15)) { return (m2 + m3) / 2.0; } else { return (std::fabs(m4 - m3) * m2 + std::fabs(m2 - m1) * m3) / (std::fabs(m4 - m3) + std::fabs(m2 - m1)); } } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_AKIMASPLINE_H tools-2021.2/include/votca/tools/application.h000066400000000000000000000123231412152065700213170ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_APPLICATION_H #define VOTCA_TOOLS_APPLICATION_H // Third party includes #include // Local VOTCA includes #include "property.h" namespace votca { namespace tools { class Application { public: Application(); virtual ~Application(); /** * \brief executes the program * \param argc argc from main * \param argv argv from main * \return return code */ int Exec(int argc, char **argv); /** * \brief program name * \return string with program name * * overload this function to set the program name */ virtual std::string ProgramName() = 0; /** * \brief version string of application * \return version string */ virtual std::string VersionString() { return ""; } /** * \brief help text of application without version information * \param out ostream for output */ virtual void HelpText(std::ostream &out) = 0; /** * \brief Initialize application data * * Initialize is called by run before parsing the command line. * All necessary command line arguments can be added here */ virtual void Initialize() = 0; /** * \brief Process command line options * \return true to continue, false to stop * * EvaluateOptions is called by Run after parsing the command line. * return true if everything is ok, false to stop and show help text. */ virtual bool EvaluateOptions() = 0; /** * \brief Check weather required option is set * \param option_name name of the option * \param error_msg error message if option is missing * * CheckRequired is called from EvaluateOptions if a required options is set. * If not, the list of possible options is shown and an exception with * the error message given in error_msg is thrown */ void CheckRequired(const std::string &option_name, const std::string &error_msg = ""); /** * \brief Main body of application * * Run is called after command line was parsed + evaluated. All * the work should be done in here. */ virtual void Run() = 0; /** * \brief add option for command line * \param group group string * \return easy_init of boost, see documentation * * Adds an option to the available command line options. If no group is * specified, it is added to the standard group (Allowed Options). If group * is given, a sub group for this set of options will be created. */ boost::program_options::options_description_easy_init AddProgramOptions( const std::string &group = ""); /** * \brief get available program options & descriptions * \return variables_map (see boost documentation) */ boost::program_options::variables_map &OptionsMap() { return _op_vm; } boost::program_options::options_description &OptionsDesc() { return _op_desc; } /** * \brief filters out the Hidden group from the options descriptions * \return Option descriptions without the "Hidden" group */ boost::program_options::options_description &VisibleOptions() { return _visible_options; } /** * \brief call StopExecution after EvaluateOptions * * This is useful if the program executes an operation in EvaluateOptions * and then wants to stop execution successfully. Call StopExecution and * return true in EvaluateOptions. */ void StopExecution() { _continue_execution = false; } /// length of the output help enum HelpType { HelpShort, HelpLong }; /** * \brief Print long/short descriptions of calculators * * @param calculator_name name of a calculator * @param help_path path in VOTCASHARE were xml file with help is stored * @param helptype Index or short (with options) help */ void PrintDescription(std::ostream &out, const std::string &calculator_name, const std::string help_path, HelpType help_type); protected: /// Variable map containing all program options boost::program_options::variables_map _op_vm; /// program options required by all applications boost::program_options::options_description _op_desc; std::map _op_groups; virtual void ShowHelpText(std::ostream &out); void ShowManPage(std::ostream &out); void ShowTEXPage(std::ostream &out); bool _continue_execution; private: /// get input parameters from file, location may be specified in command line void ParseCommandLine(int argc, char **argv); /// program options without the Hidden group boost::program_options::options_description _visible_options; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_APPLICATION_H tools-2021.2/include/votca/tools/average.h000066400000000000000000000043541412152065700204330ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_AVERAGE_H #define VOTCA_TOOLS_AVERAGE_H namespace votca { namespace tools { template class Average { public: void Process(const T &value); void Clear(); template void ProcessRange(const iterator_type &begin, const iterator_type &end); T CalcDev() const; T CalcSig2() const; const T &getAvg() const; const T getM2() const; size_t getN() const; private: size_t _n = 0; T _av = 0; // average T _m2 = 0; // second moment }; template inline void Average::Process(const T &value) { _av = _av * (double)_n / (double)(_n + 1) + value / (double)(_n + 1); _n++; _m2 += value * value; } template inline void Average::Clear() { _av = 0; _n = 0; _m2 = 0; } template template void Average::ProcessRange(const iterator_type &begin, const iterator_type &end) { for (iterator_type iter = begin; iter != end; ++iter) { Process(*iter); } } template T Average::CalcDev() const { double dev = 0.0; dev = std::sqrt((_m2 - _n * _av * _av) / (_n - 1)); return dev; } template T Average::CalcSig2() const { double dev = 0.0; dev = _m2 / _n - _av * _av; return dev; } template const T &Average::getAvg() const { return _av; } template const T Average::getM2() const { double m2 = 0.0; m2 = _m2 / _n; return m2; } template size_t Average::getN() const { return _n; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_AVERAGE_H tools-2021.2/include/votca/tools/calculator.h000066400000000000000000000102541412152065700211460ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_CALCULATOR_H #define VOTCA_TOOLS_CALCULATOR_H // Local VOTCA includes #include "globals.h" #include "property.h" #include "propertyiomanipulator.h" namespace votca { namespace tools { /** * \brief Base class for all calculators * * Calculators are grouped in CalculatorFactories and are run by Threads * or Applications. Every calculator has a description (an XML file) installed * in VOTCASHARE which is used to compile HELP. * This XML file also contains default values. * */ class Calculator { public: Calculator() = default; virtual ~Calculator() = default; /** * \brief Calculator name * * This name is used to register a calculator in a Factory * It the name of the XML file with the default calculator options * stored in VOTCASHARE * * @return calculator name */ virtual std::string Identify() = 0; /** * \brief Initializes a calculator from an XML file with options * * Options are passed to a calculator by the Application * These option overwrite defaults * * @param options Property object passed by the application to a calculator */ virtual void Initialize(const Property &user_options) = 0; /** * \brief Sets number of threads to use * * If only one thread is used, this calculator behaves as a master * * @param nThreads number of threads running this calculator * */ void setnThreads(Index nThreads) { _nThreads = nThreads; _maverick = (_nThreads == 1) ? true : false; } /** * \brief Outputs all options of a calculator * * @param output stream */ void DisplayOptions(std::ostream &out); /** * \brief Loads default options stored in VOTCASHARE */ Property LoadDefaults(const std::string package = "tools"); /** * \brief Updates user options with default options stored in VOTCASHARE * * If a value is not given or tag is not present and at the same time * a default value exists in the corresponding XML file in VOTCASHARE * a tag is created and/or a default value is assigned to it */ void UpdateWithUserOptions(Property &default_options, const Property &user_options); /** * \brief Load the default options and merge them with the user input * * Defaults are overwritten with user input */ Property LoadDefaultsAndUpdateWithUserOptions(const std::string package, const Property &user_options) { Property defaults = LoadDefaults(package); InjectDefaultsAsValues(defaults); Property user_options_with_defaults = user_options; InjectDefaultsAsValues(user_options_with_defaults); UpdateWithUserOptions(defaults, user_options_with_defaults); RecursivelyCheckOptions(defaults); return defaults; } protected: Index _nThreads; bool _maverick; void OverwriteDefaultsWithUserInput(const Property &p, Property &defaults); // Copy the defaults into the value static void InjectDefaultsAsValues(Property &defaults); static void RecursivelyCheckOptions(const Property &p); static bool IsValidOption(const Property &prop, const std::vector &choices); static std::vector GetPropertyChoices(const Property &p); template static bool IsValidCast(const tools::Property &prop) { try { prop.as(); return true; } catch (const std::runtime_error &e) { return false; } } }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_CALCULATOR_H tools-2021.2/include/votca/tools/colors.h000066400000000000000000000122641412152065700203210ustar00rootroot00000000000000/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef __VOTCA_TOOLS_COLORS_H #define __VOTCA_TOOLS_COLORS_H namespace votca { namespace tools { /** \brief stores color codes for colorful help output * * "\x1b[%dm" * * 0: reset colors/style * 1: bold * 4: underline * 30 - 37: black, red, green, yellow, blue, magenta, cyan, and white text * 40 - 47: black, red, green, yellow, blue, magenta, cyan, and white background * A, B, C, D - moves cursor one line above, under, right, left * * example: "\x1b[1;35;42m" */ namespace Colors { static const char Empty[] = {0}; static const char Reset[] = {0x1b, '[', '0', ';', '3', '9', 'm', 0}; static const char Black[] = {0x1b, '[', '0', ';', '3', '0', 'm', 0}; static const char Red[] = {0x1b, '[', '0', ';', '3', '1', 'm', 0}; static const char Green[] = {0x1b, '[', '0', ';', '3', '2', 'm', 0}; static const char Yellow[] = {0x1b, '[', '0', ';', '3', '3', 'm', 0}; static const char Blue[] = {0x1b, '[', '0', ';', '3', '4', 'm', 0}; static const char Magenta[] = {0x1b, '[', '0', ';', '3', '5', 'm', 0}; static const char Cyan[] = {0x1b, '[', '0', ';', '3', '6', 'm', 0}; static const char White[] = {0x1b, '[', '0', ';', '3', '7', 'm', 0}; static const char BoldBlack[] = {0x1b, '[', '1', ';', '3', '0', 'm', 0}; static const char BoldRed[] = {0x1b, '[', '1', ';', '3', '1', 'm', 0}; static const char BoldGreen[] = {0x1b, '[', '1', ';', '3', '2', 'm', 0}; static const char BoldYellow[] = {0x1b, '[', '1', ';', '3', '3', 'm', 0}; static const char BoldBlue[] = {0x1b, '[', '1', ';', '3', '4', 'm', 0}; static const char BoldMagenta[] = {0x1b, '[', '1', ';', '3', '5', 'm', 0}; static const char BoldCyan[] = {0x1b, '[', '1', ';', '3', '6', 'm', 0}; static const char BoldWhite[] = {0x1b, '[', '1', ';', '3', '7', 'm', 0}; } // namespace Colors class ColorScheme { public: virtual const char *_reset() const = 0; virtual const char *_black() const = 0; virtual const char *_red() const = 0; virtual const char *_green() const = 0; virtual const char *_yellow() const = 0; virtual const char *_blue() const = 0; virtual const char *_magenta() const = 0; virtual const char *_cyan() const = 0; virtual const char *_white() const = 0; }; class ColorSchemeBase { public: virtual const char *Reset() const = 0; virtual const char *Black() const = 0; virtual const char *Red() const = 0; virtual const char *Green() const = 0; virtual const char *Yellow() const = 0; virtual const char *Blue() const = 0; virtual const char *Magenta() const = 0; virtual const char *Cyan() const = 0; virtual const char *White() const = 0; virtual ~ColorSchemeBase() = default; }; template class Color : public ColorSchemeBase { TColorScheme _cs; public: const char *Reset() const override { return _cs._reset(); } const char *Black() const override { return _cs._black(); } const char *Red() const override { return _cs._red(); } const char *Green() const override { return _cs._green(); } const char *Yellow() const override { return _cs._yellow(); } const char *Blue() const override { return _cs._blue(); } const char *Magenta() const override { return _cs._magenta(); } const char *Cyan() const override { return _cs._cyan(); } const char *White() const override { return _cs._white(); } }; class csDefault : public ColorScheme { public: const char *_reset() const override { return Colors::Empty; } const char *_black() const override { return Colors::Empty; } const char *_red() const override { return Colors::Empty; } const char *_green() const override { return Colors::Empty; } const char *_yellow() const override { return Colors::Empty; } const char *_blue() const override { return Colors::Empty; } const char *_magenta() const override { return Colors::Empty; } const char *_cyan() const override { return Colors::Empty; } const char *_white() const override { return Colors::Empty; } }; class csRGB : public ColorScheme { public: const char *_reset() const override { return Colors::Reset; } const char *_black() const override { return Colors::Black; } const char *_red() const override { return Colors::Red; } const char *_green() const override { return Colors::Green; } const char *_yellow() const override { return Colors::Yellow; } const char *_blue() const override { return Colors::Blue; } const char *_magenta() const override { return Colors::Magenta; } const char *_cyan() const override { return Colors::Cyan; } const char *_white() const override { return Colors::White; } }; extern Color DEFAULT_COLORS; } // namespace tools } // namespace votca #endif /* __VOTCA_TOOLS_COLORS_H */ tools-2021.2/include/votca/tools/constants.h000066400000000000000000000050151412152065700210300ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_CONSTANTS_H #define VOTCA_TOOLS_CONSTANTS_H // Standard includes #include // Third party includes #include // Local VOTCA includes #include "types.h" namespace votca { namespace tools { namespace conv { // mathematical constants const double Pi = boost::math::constants::pi(); // natural constants // Boltzmann Factor eV/K const double kB = 8.617332478E-5; // Planck's Constant eV*s const double hbar = 6.5821192815E-16; // length conversions // votca xtp-uses for any conversions the following scheme unitA2unitB const double bohr2nm = 0.052917721092; const double nm2bohr = 18.897259886; const double ang2bohr = 1.8897259886; const double bohr2ang = 1.0 / 1.8897259886; const double nm2ang = 10.0; const double ang2nm = 0.1; const double hrt2ev = 27.21138602; const double ev2hrt = 1.0 / 27.21138602; // 1 eV = 96.485 Kj/mol const double ev2kj_per_mol = 96.485; const double kcal2kj = 4.18679994; const double kj2kcal = 1 / kcal2kj; } // namespace conv namespace topology_constants { /// Used to indicate that a valid element variable has not been assigned const std::string unassigned_element = "unassigned"; /// Used to indicate that a valid bead type variable has not been assigned const std::string unassigned_bead_type = "unassigned"; /// Used to indicate that a valid residue type variable has not been assigned const std::string unassigned_residue_type = "unassigned"; /// Used to indicate that a valid molecule type variable has not been assigned const std::string unassigned_molecule_type = "unassigned"; /// Used to indicate a valid residue id has not been assigned const Index unassigned_residue_id = -1; /// Used to indicate a valid molecule id has not been assigned const Index unassigned_molecule_id = -1; } // namespace topology_constants } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_CONSTANTS_H tools-2021.2/include/votca/tools/correlate.h000066400000000000000000000030161412152065700207730ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_CORRELATE_H #define VOTCA_TOOLS_CORRELATE_H // Standard includes #include #include // Local VOTCA includes #include "datacollection.h" namespace votca { namespace tools { /** \brief class to calculate correlations of values */ class Correlate { public: Correlate() = default; ~Correlate() = default; /** calculate the correlation of the first row in selection with all the other */ void CalcCorrelations(DataCollection::selection &data); std::vector &getData() { return _corr; } const std::vector &getData() const { return _corr; } private: std::vector _corr; }; inline std::ostream &operator<<(std::ostream &out, const Correlate &c) { for (double i : c.getData()) { out << i << std::endl; } return out; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_CORRELATE_H tools-2021.2/include/votca/tools/crosscorrelate.h000066400000000000000000000031041412152065700220430ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_CROSSCORRELATE_H #define VOTCA_TOOLS_CROSSCORRELATE_H // Standard includes #include #include // Local VOTCA includes #include "datacollection.h" #include "eigen.h" #include "types.h" namespace votca { namespace tools { /** \brief class to calculate cross correlations and autocorrelations */ class CrossCorrelate { public: CrossCorrelate() = default; ~CrossCorrelate() = default; void AutoCorrelate(DataCollection::selection& data); std::vector& getData() { return _corrfunc; } const std::vector& getData() const { return _corrfunc; } private: std::vector _corrfunc; }; inline std::ostream& operator<<(std::ostream& out, const CrossCorrelate& c) { for (Index i = 0; i < Index(c.getData().size()); i++) { out << i << " " << c.getData()[i] << std::endl; } return out; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_CROSSCORRELATE_H tools-2021.2/include/votca/tools/cubicspline.h000066400000000000000000000217171412152065700213230ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_CUBICSPLINE_H #define VOTCA_TOOLS_CUBICSPLINE_H // Standard includes #include // Local VOTCA includes #include "eigen.h" #include "spline.h" namespace votca { namespace tools { /** \brief A cubic spline class This class does cubic piecewise spline interpolation and spline fitting. As representation of a single spline, the general form \f[ S_i(x) = A(x,h_i) f_i + B(x,h_i) f_{i+1} + C(x,h_i) f''_i + d(x,h_i) f''_{i+1} \f] with \f[ x_i \le x < x_{i+1}\,,\\ h_i = x_{i+1} - x_{i} \f] The \f$f_i\,,\,,f''_i\f$ are the function values and second derivates at point \f$x_i\f$. The parameters \f$f''_i\f$ are no free parameters, they are determined by the smoothing condition that the first derivatives are continuous. So the only free paramers are the grid points x_i as well as the functon values f_i at these points. A spline can be generated in several ways: - Interpolation spline - Fitting spline (fit to noisy data) - calculate the parameters elsewere and fill the spline class */ class CubicSpline : public Spline { public: // default constructor CubicSpline() = default; // destructor ~CubicSpline() override = default; // construct an interpolation spline // x, y are the the points to construct interpolation, both vectors must be of // same size void Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // fit spline through noisy data // x,y are arrays with noisy data, both vectors must be of same size void Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // Calculate the function value double Calculate(double r) override; // Calculate the function derivative double CalculateDerivative(double r) override; using Spline::Calculate; using Spline::CalculateDerivative; // set spline parameters to values that were externally computed void setSplineData(const Eigen::VectorXd &f, const Eigen::VectorXd &f2) { _f = f; _f2 = f2; } /** * \brief Add a point (one entry) to fitting matrix * \param pointer to matrix * \param value x * \param offsets relative to getInterval(x) * \param scale parameters for terms "A,B,C,D" * When creating a matrix to fit data with a spline, this function creates * one entry in that fitting matrix. */ template void AddToFitMatrix(matrix_type &M, double x, Index offset1, Index offset2 = 0, double scale = 1); /** * \brief Add a point (one entry) to fitting matrix * \param pointer to matrix [in] [out] * \param value x [in] * \param offsets relative to getInterval(x) [in] * \param scale1 parameters for terms "A,B,C,D" [in] * \param scale2 parameters for terms "AA,BB,CC,DD" [in] * When creating a matrix to fit data with a spline, this function creates * one entry in that fitting matrix. */ template void AddToFitMatrix(matrix_type &M, double x, Index offset1, Index offset2, double scale1, double scale2); /** * \brief Add a vector of points to fitting matrix * \param pointer to matrix * \param vector of x values * \param offsets relative to getInterval(x) * Same as previous function, but vector-valued and with scale=1.0 */ template void AddToFitMatrix(matrix_type &M, vector_type &x, Index offset1, Index offset2 = 0); /** * \brief Add boundary condition of sum_i f_i =0 to fitting matrix * \param pointer to matrix * \param offsets */ template void AddBCSumZeroToFitMatrix(matrix_type &M, Index offset1, Index offset2 = 0); /** * \brief Add boundary conditions to fitting matrix * \param pointer to matrix * \param offsets */ template void AddBCToFitMatrix(matrix_type &M, Index offset1, Index offset2 = 0); private: // y values of grid points Eigen::VectorXd _f; // second derivatives of grid points Eigen::VectorXd _f2; // A spline can be written in the form // S_i(x) = A(x,x_i,x_i+1)*f_i + B(x,x_i,x_i+1)*f''_i // + C(x,x_i,x_i+1)*f_{i+1} + D(x,x_i,x_i+1)*f''_{i+1} double A(double r); double B(double r); double C(double r); double D(double r); double Aprime(double r); double Bprime(double r); double Cprime(double r); double Dprime(double r); // tabulated derivatives at grid points. Second argument: 0 - left, 1 - right double A_prime_l(Index i); double A_prime_r(Index i); double B_prime_l(Index i); double B_prime_r(Index i); double C_prime_l(Index i); double C_prime_r(Index i); double D_prime_l(Index i); double D_prime_r(Index i); }; template inline void CubicSpline::AddToFitMatrix(matrix_type &M, double x, Index offset1, Index offset2, double scale) { Index spi = getInterval(x); M(offset1, offset2 + spi) += A(x) * scale; M(offset1, offset2 + spi + 1) += B(x) * scale; M(offset1, offset2 + spi + _r.size()) += C(x) * scale; M(offset1, offset2 + spi + _r.size() + 1) += D(x) * scale; } // for adding f'(x)*scale1 + f(x)*scale2 as needed for threebody interactions template inline void CubicSpline::AddToFitMatrix(matrix_type &M, double x, Index offset1, Index offset2, double scale1, double scale2) { Index spi = getInterval(x); M(offset1, offset2 + spi) += Aprime(x) * scale1; M(offset1, offset2 + spi + 1) += Bprime(x) * scale1; M(offset1, offset2 + spi + _r.size()) += Cprime(x) * scale1; M(offset1, offset2 + spi + _r.size() + 1) += Dprime(x) * scale1; AddToFitMatrix(M, x, offset1, offset2, scale2); } template inline void CubicSpline::AddToFitMatrix(matrix_type &M, vector_type &x, Index offset1, Index offset2) { for (Index i = 0; i < x.size(); ++i) { Index spi = getInterval(x(i)); M(offset1 + i, offset2 + spi) = A(x(i)); M(offset1 + i, offset2 + spi + 1) = B(x(i)); M(offset1 + i, offset2 + spi + _r.size()) = C(x(i)); M(offset1 + i, offset2 + spi + _r.size() + 1) = D(x(i)); } } template inline void CubicSpline::AddBCSumZeroToFitMatrix(matrix_type &M, Index offset1, Index offset2) { for (Index i = 0; i < _r.size(); ++i) { M(offset1, offset2 + i) = 1; M(offset1, offset2 + _r.size() + i) = 0; } } template inline void CubicSpline::AddBCToFitMatrix(matrix_type &M, Index offset1, Index offset2) { for (Index i = 0; i < _r.size() - 2; ++i) { M(offset1 + i + 1, offset2 + i) = A_prime_l(i); M(offset1 + i + 1, offset2 + i + 1) = B_prime_l(i) - A_prime_r(i); M(offset1 + i + 1, offset2 + i + 2) = -B_prime_r(i); M(offset1 + i + 1, offset2 + _r.size() + i) = C_prime_l(i); M(offset1 + i + 1, offset2 + _r.size() + i + 1) = D_prime_l(i) - C_prime_r(i); M(offset1 + i + 1, offset2 + _r.size() + i + 2) = -D_prime_r(i); } switch (_boundaries) { case splineNormal: M(offset1, offset2 + _r.size()) = 1; M(offset1 + _r.size() - 1, offset2 + 2 * _r.size() - 1) = 1; break; case splineDerivativeZero: // y M(offset1 + 0, offset2 + 0) = -1 * A_prime_l(0); M(offset1 + 0, offset2 + 1) = -1 * B_prime_l(0); M(offset1 + _r.size() - 1, offset2 + _r.size() - 2) = A_prime_l(_r.size() - 2); M(offset1 + _r.size() - 1, offset2 + _r.size() - 1) = B_prime_l(_r.size() - 2); // y'' M(offset1 + 0, offset2 + _r.size() + 0) = D_prime_l(0); M(offset1 + 0, offset2 + _r.size() + 1) = C_prime_l(0); M(offset1 + _r.size() - 1, offset2 + 2 * _r.size() - 2) = C_prime_l(_r.size() - 2); M(offset1 + _r.size() - 1, offset2 + 2 * _r.size() - 1) = D_prime_l(_r.size() - 2); break; case splinePeriodic: M(offset1, offset2) = 1; M(offset1, offset2 + _r.size() - 1) = -1; M(offset1 + _r.size() - 1, offset2 + _r.size()) = 1; M(offset1 + _r.size() - 1, offset2 + 2 * _r.size() - 1) = -1; break; } } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_CUBICSPLINE_H tools-2021.2/include/votca/tools/datacollection.h000066400000000000000000000120571412152065700220050ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_DATACOLLECTION_H #define VOTCA_TOOLS_DATACOLLECTION_H // Standard includes #include #include #include #include // Local VOTCA includes #include "tokenizer.h" #include "types.h" namespace votca { namespace tools { /** * \brief This class handles a set of arrays which can be identified by name * tags * * This class is a Container of arrays. The arrays can be accessed by * specifying a name or wildcard. * **/ template class DataCollection { public: /** * \brief The array class, extends vector by a name tag */ class array : public std::vector { public: array(std::string name) { _name = name; } const std::string &getName() const { return _name; } private: std::string _name; }; using iterator = typename std::vector::iterator; using const_iterator = typename std::vector::const_iterator; /** * \brief class for array selection */ class selection { public: selection() = default; ~selection() = default; Index size() const { return Index(_arrays.size()); } bool empty() const { return _arrays.empty(); } array &operator[](Index i) { assert(i < Index(_arrays.size())); return *(_arrays[i]); } const array &operator[](Index i) const { assert(i < Index(_arrays.size())); return *(_arrays[i]); } void push_back(array *a) { _arrays.push_back(a); } void push_back(selection *s) { _arrays.insert(_arrays.end(), s->begin(), s->end()); } iterator begin() { return _arrays.begin(); } iterator end() { return _arrays.end(); } const_iterator begin() const { return _arrays.begin(); } const_iterator end() const { return _arrays.end(); } private: std::vector _arrays; }; /// constructor DataCollection() = default; /// destructor ~DataCollection() { clear(); } /** * \brief clears the data collection */ void clear(); /** * \ brief returns the number of arrays */ Index size() const { return Index(_data.size()); } bool empty() const { return _data.empty(); } array &operator[](Index i) { assert(i < Index(_data.size())); return *(_data[i]); } iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } /** * \brief create a new array */ array *CreateArray(std::string name); /** * \brief access the data container */ std::vector &Data() { return _data; } const std::vector &Data() const { return _data; } /** * \brief access an array by name */ array *ArrayByName(std::string name); /** * \brief select a set of arrays * * WARNING If attempting to append to an existing selection you must be * careful if there exist more than one array with the same name the * first array name that matches 'strselection' will be appended. */ selection *select(std::string strselection, selection *sel_append = nullptr); private: std::vector _data; std::map _array_by_name; }; template void DataCollection::clear() { for (auto &d : _data) { delete d; } _data.clear(); } template typename DataCollection::array *DataCollection::CreateArray( std::string name) { assert(ArrayByName(name) == nullptr); array *a = new array(name); _data.push_back(a); _array_by_name[name] = a; return a; } template typename DataCollection::array *DataCollection::ArrayByName( std::string name) { typename std::map::iterator i = _array_by_name.find(name); if (i == _array_by_name.end()) { return nullptr; } return (*i).second; } template typename DataCollection::selection *DataCollection::select( std::string strselection, selection *sel_append) { typename DataCollection::selection *sel = sel_append; if (!sel_append) { sel = new typename DataCollection::selection; } for (auto &pair : _array_by_name) { if (wildcmp(strselection.c_str(), pair.second->getName().c_str())) { sel->push_back(pair.second); } } return sel; } std::ostream &operator<<(std::ostream &out, const DataCollection::selection &sel); } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_DATACOLLECTION_H tools-2021.2/include/votca/tools/edge.h000066400000000000000000000065111412152065700177220ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_EDGE_H #define VOTCA_TOOLS_EDGE_H // Standard includes #include #include #include #include // Local VOTCA includes #include "types.h" namespace votca { namespace tools { /** * \brief Connects to vertices * * The edge class stores the ids of two seperate vertices indictating that they * are connected (id1,id2). Unlike a pair the vertex with the lower value is * always placed in id1, this allows us to reduce ambiguity when dealing with * a link. */ class Edge { protected: std::vector vertices_; public: Edge() = default; virtual ~Edge() = default; /// Creates an edge the smallest integer value will be placed in the id1 /// spot and the larger in the id2 spot Edge(Index ID1, Index ID2); /// Given one of the integers in the edge the other will be output Index getOtherEndPoint(Index ver) const; /// grab the smaller integer Index getEndPoint1() const { return vertices_.front(); } /// grab the larger integer Index getEndPoint2() const { return vertices_.back(); } /** * \brief Checks to see if an edge loops back on itself. * * If both ends of the edge point to the same vertex than it is considered a * loop. **/ bool loop() const { return vertices_.front() == vertices_.back(); } /// Determine if the edge contains the Index ID bool contains(Index ID) const; /// Checks if Edges are equivalent virtual bool operator==(const Edge& ed) const; /// Checks if Edges are not equivalent virtual bool operator!=(const Edge& ed) const; /// If the vertices are smaller in value /// Edge ed1(2,3); /// Edge ed2(1,5); /// Edge ed3(4,1); /// priority is given to the smallest vertex /// assert(ed2(const Edge& ed) const; virtual bool operator<=(const Edge& ed) const; virtual bool operator>=(const Edge& ed) const; /// Print the contents of the edge friend std::ostream& operator<<(std::ostream& os, const Edge& ed); }; // Value used as a dummy object const Edge DUMMY_EDGE(std::numeric_limits::max(), std::numeric_limits::max()); } // namespace tools } // namespace votca /// Define a hasher so we can use it as a key in an unordered_map namespace std { template <> class hash { public: size_t operator()(const votca::tools::Edge& ed) const { return hash()(ed.getEndPoint1()) ^ hash()(ed.getEndPoint2()); } }; } // namespace std #endif // VOTCA_TOOLS_EDGE_H tools-2021.2/include/votca/tools/edgecontainer.h000066400000000000000000000053601412152065700216260ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_EDGECONTAINER_H #define VOTCA_TOOLS_EDGECONTAINER_H // Standard includes #include #include #include #include // Local VOTCA includes #include "edge.h" namespace votca { namespace tools { /** * \brief EdgeContainer is responsible for operations on groups of edges * * Such operations have to deal with finding edges attached to a vertex * finding neighboring vertices etc. */ class EdgeContainer { protected: /// The vertex, the neighboring vertices and the number of edges std::unordered_map> adj_list_; public: /// Constructors can take no arguments a single Edge or a vector of edges EdgeContainer() = default; EdgeContainer(Edge edge); EdgeContainer(std::vector edges); /// Get the value of the max degree Index getMaxDegree() const; /// Contains vector of all vertices with degree std::vector getVerticesDegree(Index degree) const; /// Determine the degree of the vertex/number of edges attached Index getDegree(const Index vertex) const; /// Determine if a vertex with the specified degree exists bool vertexExistWithDegree(Index degree) const; /// Check if the edge exists returns true or false bool edgeExist(const Edge& edge) const; /// Check if the vertex exists returns true or false bool vertexExist(Index vertex) const; /// Add an edge to the container void addEdge(Edge edge); /// Add a lone vertex void addVertex(Index vertex); /// Get all the edges in vector form std::vector getEdges() const; /// Get all the vertices in vector form std::vector getVertices() const; /// Get the vertices neighboring vert std::vector getNeighVertices(Index vertex) const; /// Get the edges neighboring vert std::vector getNeighEdges(Index vertex) const; /// Print output of object friend std::ostream& operator<<(std::ostream& os, const EdgeContainer edgecontainer); }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_EDGECONTAINER_H tools-2021.2/include/votca/tools/eigen.h000066400000000000000000000035011412152065700201010ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_EIGEN_H #define VOTCA_TOOLS_EIGEN_H // Local VOTCA includes #include "votca_tools_config.h" #ifdef MKL_FOUND #include #define EIGEN_USE_MKL_ALL #endif #if defined(FFTW3_FOUND) || defined(MKL_FOUND) #define EIGEN_FFTW_DEFAULT #endif //! Macro to detect strictly gcc. //! \details __GNUC__ and __GNUG__ were intended to indicate the GNU compilers. //! However, they're also defined by Clang/LLVM and Intel compilers to indicate //! compatibility. This macro can be used to detect strictly gcc and not clang //! or icc. #if (defined(__GNUC__) || defined(__GNUG__)) && \ !(defined(__clang__) || defined(__INTEL_COMPILER)) #define STRICT_GNUC #define GCC_VERSION \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #if (defined STRICT_GNUC) && GCC_VERSION > 70000 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wint-in-bool-context" #endif #include #include #include #include #if (defined STRICT_GNUC) && GCC_VERSION > 70000 #pragma GCC diagnostic pop #endif #endif // VOTCA_TOOLS_EIGEN_H tools-2021.2/include/votca/tools/eigenio_matrixmarket.h000066400000000000000000000023361412152065700232260ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_EIGENIO_MATRIXMARKET_H #define VOTCA_TOOLS_EIGENIO_MATRIXMARKET_H // Local VOTCA includes #include "eigen.h" namespace votca { namespace tools { namespace EigenIO_MatrixMarket { Eigen::VectorXd ReadVector(const std::string& filename); void WriteVector(const std::string& filename, const Eigen::VectorXd& output); void WriteMatrix(const std::string& filename, const Eigen::MatrixXd& output); Eigen::MatrixXd ReadMatrix(const std::string& filename); } // namespace EigenIO_MatrixMarket } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_EIGENIO_MATRIXMARKET_H tools-2021.2/include/votca/tools/eigensystem.h000066400000000000000000000034601412152065700213520ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_EIGENSYSTEM_H #define VOTCA_TOOLS_EIGENSYSTEM_H // Local VOTCA includes #include "eigen.h" namespace votca { namespace tools { class EigenSystem { public: // returns eigenvalues const Eigen::VectorXd& eigenvalues() const { return _eigenvalues; } Eigen::VectorXd& eigenvalues() { return _eigenvalues; } // returns eigenvectors const Eigen::MatrixXd& eigenvectors() const { return _eigenvectors; } Eigen::MatrixXd& eigenvectors() { return _eigenvectors; } // returns left eigenvectors or other in case of nonhermititan problem const Eigen::MatrixXd& eigenvectors2() const { return _eigenvectors_2; } Eigen::MatrixXd& eigenvectors2() { return _eigenvectors_2; } Eigen::ComputationInfo info() const { return _info; } Eigen::ComputationInfo& info() { return _info; } void clear() { _info = Eigen::Success; _eigenvalues.resize(0); _eigenvectors.resize(0, 0); _eigenvectors_2.resize(0, 0); } private: Eigen::ComputationInfo _info = Eigen::Success; Eigen::VectorXd _eigenvalues; Eigen::MatrixXd _eigenvectors; Eigen::MatrixXd _eigenvectors_2; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_EIGENSYSTEM_H tools-2021.2/include/votca/tools/elements.h000066400000000000000000000130531412152065700206310ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_ELEMENTS_H #define VOTCA_TOOLS_ELEMENTS_H // Standard includes #include #include // Local VOTCA includes #include "constants.h" namespace votca { namespace tools { /** \brief information about an element The Elements class stores properties of several elements in the periodic table includeing: mass, element name, element symbol, van der Waals radius, effective nuclear potential, element number as it appears in the periodic table. */ class Elements { public: Elements() : _filled_VdWChelpG(false), _filled_VdWMK(false), _filled_NucCrg(false), _filled_CovRad(false), _filled_Mass(false), _filled_EleNum(false), _filled_EleName(false), _filled_ElPolarizability(false), _filled_EleShort(false), _filled_EleFull(false){}; /// Determine if the name is a recognized element symbol or name bool isElement(std::string name); /// ChelpG is a method for calculating the electrostatic potential outside /// of a molecule. The VdWChelpG radius in this case is specific to each /// element and defines the radius outside of which the electrostatic /// potential is calculated. The electrostatic potential within the radius /// is not calculated. For more information see the reference paper CHELPG /// paper [Journal of Computational Chemistry 11, 361, 1990] double getVdWChelpG(std::string name); /// Merz-Singh-Kollman MK method is a similar method for calculating the /// electrostatic potential outside of a molecule. Details of the method can /// be found here [Singh, U. Chandra (04/01/1984). "An approach to computing /// electrostatic charges for molecules". Journal of computational chemistry /// 5 (2), 129, 1984]. The VdWMK method will return the radii used to define /// where the electrostatic grid starts. double getVdWMK(std::string name); /// Return the Nuclear charges of each atom. H - 1, He - 2, Na - 3 etc... Index getNucCrg(std::string name); /// Similar to the Nuclear charges but returns in integer form represents /// the id of the atom in the periodic table, the id starts at 1 Index getEleNum(std::string name); /// Returns the mass of each atom in a.u. double getMass(std::string name); /// Returns the atomic polarisability of atom // All polarizabilities in nm**3 // Isotropic polarizability volume is evaluated from the tensor // as (a_xx * a_yy * a_zz )^(1/3) for eigenvalues of the polarizability tensor double getPolarizability(std::string name); /// Returns the covalent Radii of the atom double getCovRad(std::string name, std::string unit); /// Provided the element number returns the symbol for the element name /// (1) = "H", (2) = "He", ... std::string getEleName(Index elenum); /// Provided the full element name returns the element symbol /// "Hydrogen" = "H", "HELIUM" = "He",... std::string getEleShort(std::string elefull); /// Is `eleshort` recognized an element symbol i.e. H, C, He, Ne etc bool isEleShort(std::string shortname); /// Is `elefull` recognized as an element name i.e. Carbon, HYDROGEN, suphur bool isEleFull(std::string fullname); bool isMassAssociatedWithElement(double mass, double tolerance); /// Get the shortened element name given a mass similar in size to one of /// the elements. Provided the mass is within the specified tolerance of /// the match. std::string getEleShortClosestInMass(double mass, double tolerance); /// Provided the element symbol returns the element name /// "Pb" = "LEAD", "Na" = "SODIUM", .... std::string getEleFull(std::string eleshort); private: // cache variables bool _filled_VdWChelpG = false; bool _filled_VdWMK = false; bool _filled_NucCrg = false; bool _filled_CovRad = false; bool _filled_Mass = false; bool _filled_EleNum = false; bool _filled_EleName = false; bool _filled_ElPolarizability = false; bool _filled_EleShort = false; bool _filled_EleFull = false; std::map _VdWChelpG; std::map _VdWMK; std::map _NucCrg; std::map _CovRad; std::map _Mass; std::map _EleNum; std::map _EleName; std::map _ElPolarizability; std::map _EleShort; std::map _EleFull; /// Finds the element closest in mass and returns the difference as well as /// the string of elements short name std::pair findShortNameOfElementClosestInMass_( double mass); void FillMass(); void FillVdWChelpG(); void FillNucCrg(); void FillCovRad(); void FillEleNum(); void FillEleName(); void FillEleShort(); void FillEleFull(); void FillVdWMK(); void FillPolarizability(); }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_ELEMENTS_H tools-2021.2/include/votca/tools/filesystem.h000066400000000000000000000023561412152065700212050ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_FILESYSTEM_H #define VOTCA_TOOLS_FILESYSTEM_H // Standard includes #include namespace votca { namespace tools { namespace filesystem { // return the file ending like .jpg .gro etc.., returns an empty string // otherwise std::string GetFileExtension(const std::string& filename); // return the filename without the file extension std::string GetFileBase(const std::string& filename); // returns true if file exists otherwise false bool FileExists(const std::string& filename); } // namespace filesystem } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_FILESYSTEM_H tools-2021.2/include/votca/tools/floatingpointcomparison.h000066400000000000000000000031651412152065700237700ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_FLOATINGPOINTCOMPARISON_H #define VOTCA_TOOLS_FLOATINGPOINTCOMPARISON_H // Standard includes #include #include /** * \brief Provides a means for comparing floating point numbers * * Implements relative method - do not use for comparing with zero * use this most of the time, tolerance needs to be meaningful in your context * * Function taken from * https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison * user ShitalShal */ // Standard includes #include namespace votca { namespace tools { template static bool isApproximatelyEqual(T a, T b, T tolerance) { T diff = std::abs(a - b); if (diff <= tolerance) { return true; } if (diff < std::max(std::abs(a), std::abs(b)) * tolerance) { return true; } return false; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_FLOATINGPOINTCOMPARISON_H tools-2021.2/include/votca/tools/getline.h000066400000000000000000000022471412152065700204470ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GETLINE_H #define VOTCA_TOOLS_GETLINE_H // Standard includes #include #include #include namespace votca { namespace tools { /** \brief Wrapper for a getline function Removes Windows end-of-line character */ inline std::istream& getline(std::istream& is, std::string& str) { std::istream& ist = std::getline(is, str, '\n'); str.erase(remove(str.begin(), str.end(), '\r'), str.end()); return ist; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GETLINE_H tools-2021.2/include/votca/tools/globals.h000066400000000000000000000037661412152065700204520ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GLOBALS_H #define VOTCA_TOOLS_GLOBALS_H // Standard includes #include namespace votca { struct Log { /// be loud and noisy enum Level { error = 0, warning = 1, info = 2, debug = 3 }; static Level current_level; static bool verbose() { return current_level > Level::error; } }; namespace tools { /** \brief Retrieves VOTCASHARE environment variable. Throws std::runtime_error if not set. */ std::string GetVotcaShare(); bool VotcaShareSet(); /** \brief class to store global variables This class is used to access global variables */ struct globals { /// web of the package static std::string url; /// email address of the developers static std::string email; /// If Eigen is overloaded with MKL static bool VOTCA_MKL; /// man pages format strings struct man { static std::string option; static std::string header; static std::string name; static std::string authors; static std::string copyright; static std::string synopsis; static std::string description; static std::string options; }; /// TEX pages format strings struct tex { static std::string section; static std::string label; static std::string description; static std::string options; static std::string option; }; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GLOBALS_H tools-2021.2/include/votca/tools/graph.h000066400000000000000000000131761412152065700201240ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPH_H #define VOTCA_TOOLS_GRAPH_H // Standard includes #include #include #include #include // Local VOTCA includes #include "edgecontainer.h" #include "graphnode.h" namespace votca { namespace tools { /** * \brief A graph object that contains the graph nodes and the edges describing * the bonds between nodes. * */ class GraphNode; class Graph { protected: EdgeContainer edge_container_; /// Parameter description /// @param Index - is the index of the graph nodes / vertex ids /// @param GraphNode - this is the node object at each vertex and contains /// all the informatino that is relevant to that object std::unordered_map nodes_; /// This is the id of the graph to graphs that contain the same content /// are considered equal std::string id_; protected: /// Calculate the id of the graph void calcId_(); public: Graph() : id_(""){}; virtual ~Graph() = default; /// Constructor /// @param edgs - vector of edges where each edge is composed of two /// s (vertex ids) describing a link between the vertices /// @param nodes - unordered_map where the key is the vertex id and the /// target is the graph node Graph(std::vector edges, std::unordered_map nodes); /// Equivalence and non equivalence operators work by determine if the /// contents of each graph node in each of the graphs are the same. bool operator!=(const Graph& graph) const; bool operator==(const Graph& graph) const; /// Find all the vertices that are isolated (not connected to any other /// vertex) and return them in a vector with their corresponding graph node. std::vector> getIsolatedNodes(void) const; /// Returns a vector of the vertices and their graph nodes that are directly /// connected to the vertex 'vert' std::vector> getNeighNodes(Index vertex) const; /// set the Node associated with vertex 'vert' void setNode(Index vertex, GraphNode& graph_node); void setNode(std::pair& id_and_node); /// Gets all vertices with degree of 3 or greater std::vector getJunctions() const; /// Return a copy of the graph node at vertex 'vert' GraphNode getNode(const Index vertex) const; /// Return all the vertices and their graph nodes that are within the graph virtual std::vector> getNodes() const; /// Returns all the vertices of the graph connected to vertex `vert` through /// an edge. std::vector getNeighVertices(Index vertex) const { return edge_container_.getNeighVertices(vertex); } /// Returns the id of graph std::string getId() const { return id_; } /// Returns all the edges in the graph virtual std::vector getEdges() { return edge_container_.getEdges(); } /// Returns all the edges in the graph connected to vertex `vertex` std::vector getNeighEdges(Index vertex) const { return edge_container_.getNeighEdges(vertex); } /// Returns all the vertices in the graph std::vector getVertices() const; /** * \brief Finds the max degree of a vertex in the graph. * * Will look at each of the vertices and find the vertex with the most edges * connected to it. It will count the number of edges this corresponds to the * maximum degree of the graph. **/ Index getMaxDegree() const { return edge_container_.getMaxDegree(); } /// Calcualtes the degree, or number of edges connected to vertex `vertex` Index getDegree(Index vertex) const; /// Returns all the vertices with degree specified by `degree` virtual std::vector getVerticesDegree(Index degree) const; /// Determines if a vertex exists within the graph bool vertexExist(Index vertex) const; /// Determines if an edge is stored in the graph virtual bool edgeExist(const Edge& edge) const { return edge_container_.edgeExist(edge); } /// Remove contents of all nodes void clearNodes(); /// Copies nodes from one graph to another. This should only be used in cases /// where the graph does not contain nodes before the copy. void copyNodes(Graph& graph); friend std::ostream& operator<<(std::ostream& os, const Graph graph); }; /** * \brief Compare function pair object * * This function is meant to be used with the stl sort algorithm. It will sort * a vector of pairs containing the vertex ids and the graphnodes. Only the * contetns of the graph node object are used to determine precidence e.g. * * pair pr_grn1{ 1, gn }; * pair pr_grn2{ 2, gn2 }; * * vector > vec_pr_gn = { pr_grn1, pr_grn2 , ... etc }; * * sort(vec_pr_gn.begin(),vec_pr_gn.end(),cmpVertNodePair); */ bool cmpVertNodePair(const std::pair& id_and_node1, const std::pair& id_and_node2); } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPH_H tools-2021.2/include/votca/tools/graph_bf_visitor.h000066400000000000000000000030171412152065700223430ustar00rootroot00000000000000/* * Copyright 2009-2019 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef __VOTCA_TOOLS_GRAPH_BF_VISITOR_H #define __VOTCA_TOOLS_GRAPH_BF_VISITOR_H #include "graphvisitor.h" #include #include /** * \brief A breadth first (BF) graph visitor * * This graph visitor will explore the vertices closest to the starting node * first and proceed outwards. * */ namespace votca { namespace tools { class Graph; class Edge; class GraphNode; class Graph_BF_Visitor : public GraphVisitor { private: std::deque> edge_que_; /// The core of the breadth first visitor is in how the edges are added /// to the queue in this function void addEdges_(const Graph& graph, Index vertex) override; Edge getEdge_() override; public: Graph_BF_Visitor() = default; bool queEmpty() const override; }; } // namespace tools } // namespace votca #endif // __VOTCA_TOOLS_GRAPH_BF_VISITOR_H tools-2021.2/include/votca/tools/graph_df_visitor.h000066400000000000000000000030251412152065700223440ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPH_DF_VISITOR_H #define VOTCA_TOOLS_GRAPH_DF_VISITOR_H // Standard includes #include // Local VOTCA includes #include "graphvisitor.h" /** * \brief A breadth first (DF) graph visitor * * This graph visitor will explore the vertices closest to the starting node * first and proceed outwards. * */ namespace votca { namespace tools { class Graph; class Edge; class GraphNode; class Graph_DF_Visitor : public GraphVisitor { private: std::list edge_list_; /// The core of the breadth first visitor is in how the edges are added /// to the queue in this function void addEdges_(const Graph& g, Index vertex) override; Edge getEdge_() override; public: Graph_DF_Visitor() = default; bool queEmpty() const override; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPH_DF_VISITOR_H tools-2021.2/include/votca/tools/graphalgorithm.h000066400000000000000000000162031412152065700220250ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPHALGORITHM_H #define VOTCA_TOOLS_GRAPHALGORITHM_H // Standard includes #include #include // Local VOTCA includes #include "graphnode.h" #include "reducedgraph.h" /** * \brief This file is a compilation of graph related algorithms. * * These algorithms require the interplay of the graph and graph visitor * classes and thus cannot be made methods of either. In most cases a graph * visitor is specified explores the graph to determine some metric */ namespace votca { namespace tools { class Graph; class GraphVisitor; /** * \brief Determine if every vertex is connected to every other one through some * combination of edges. * * The purpose of this algorithm is to simply determine if the graph is one * large network or not. If it is it means every vertex is connected to every * other one by 1 or more series of edges. * * @param[in] - Graph instance * @param[in,out] - Graph visitor reference instance used to explore the graph * @return - Boolean value (true - if single network) */ bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor); /** * \brief Explore one of the branches if exploration is initiated at vertex * `starting_vertex`. * * The `edge` is used to determine which branch is to be explored. The edge must * be an edge connected to the starting_vertex. * * Take the following * * 1 - 2 - 3 - 4 - 5 * | | * 6 - 7 - 8 * * If our graph is reprsented by the above depiction and vertex 3 is chosen as * our starting vertex, we are left with 3 edges to choose from Edges: * * 2 - 3 * 3 - 4 * 3 - 6 * * If we pick edge 3 - 4 or 3 - 6 the returned set of edges will consist of the * loop * * 3 - 4 - 5 * | | * 6 - 7 - 8 * * If instead Edge 2 - 3 is picked, the following set of edges would be returned * * 1 - 2 - 3 * * @param[in] - Graph instance * @param[in] - Index starting vertex, where the exploration begins * @param[in] - the edge indicating which branch is to be explored * @return - set of edges in the branch that were explored **/ std::set exploreBranch(Graph g, Index starting_vertex, const Edge& edge); /** * \brief Will take a graph and reduce it, by removing all vertices with degree * of 2. * * The purpose of this algorithm is to introduce new functionality that reduces * the complexity of a graph by removing any vertex that has a degree of 2. By * exploring a reduced graph instead of a full graph insight can still be gained * into the topology of the graph but with better performance. The edges of the * reduced graph can be expanded if needed to determine how they correspond to * the full graph. Take: * * 1 - 2 - 3 - 4 - 5 - 6 * | | * 7 - 8 - 9 * * This would be reduced to * * 1 - 2 - 4 - 6 * | _ | * * A total of 4 vertices with 4 edges as opposed to 9 vertices and 9 edges. * * @param[in] - graph instance * @return - a reduced graph **/ ReducedGraph reduceGraph(Graph graph); /** * \brief Break graph into smaller graph instances if the network is made up of * isolated sub networks. * * This algorithm will determine if there are groups of vertices that are * connected, but where there are no connections shared between the groups. * These groups will be brocken up into their own Graph instances. E.g. Take * a graph with the following vertices and connections * * Graph 1: * * 1 - 2 - 3 * | | 8 - 9 - 10 11 * 4 - 5 - 6 -7 * * decoupling the graph into sub graphs will break the islands up into * individual graphs: * * Sub Graph 1 Sub Graph 2 Sub Graph 3 * * 1 - 2 - 3 * | | 8 - 9 - 10 11 * 4 - 5 - 6 -7 * * * @param[in] - Graph instance * @return - vector containing shared pointers to all the sub graphs if there * are no subgraphs than the input graph is returned. */ std::vector decoupleIsolatedSubGraphs(Graph graph); /** * \brief Explore a graph with a graph visitor. * * This function will simply explore a graph, any information gained from the * exploration will depend on the graph visitor used. Note that the Graph * visitor is the base class which will not work on its own. The purpose of * doing this is to make use of polymorphism. * * @param[in,out] - Graph reference instance * @param[in,out] - graph visitor */ void exploreGraph(Graph& graph, GraphVisitor& graph_visitor); /** * \brief Find a unique identifier that describes graph structure. * * This algorithm is designed to explore the topology of the graph and return an * identifier in the form of the string that is unique to the topology. It does * this by taking into account the contents of the graphnodes. How it does this * is specific to the graph visitor specified. * * @param[in,out] - Graph reference instance * @return - string identifier */ template std::string findStructureId(Graph& graph) { // Determine the highest degree in the graph Index maxD = graph.getMaxDegree(); // Get the vertices with this degree std::vector vertices = graph.getVerticesDegree(maxD); // Get the nodes and determine which node has the greatest stringID // When compared using compare function std::string str_id = ""; std::vector graph_node_ids; for (const Index& vertex : vertices) { GraphNode graph_node = graph.getNode(vertex); Index comp_int = str_id.compare(graph_node.getStringId()); if (comp_int > 0) { str_id = graph_node.getStringId(); graph_node_ids.clear(); graph_node_ids.push_back(vertex); } else if (comp_int == 0) { graph_node_ids.push_back(vertex); } } // If the str_id is empty it means the nodes are empty and we will // simply have to rely on the degree to choose the vertices to explore from if (str_id.compare("") == 0) { graph_node_ids = vertices; } // If two or more graph nodes are found to be equal then // they must all be explored std::string chosenId = ""; Graph graph_chosen = graph; for (const Index& vertex : graph_node_ids) { GV graph_visitor; graph_visitor.setStartingVertex(vertex); Graph graph_temp = graph; exploreGraph(graph_temp, graph_visitor); std::string temp_struct_id = graph_temp.getId(); if (chosenId.compare(temp_struct_id) < 0) { chosenId = temp_struct_id; graph_chosen = graph_temp; } } graph = graph_chosen; return chosenId; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPHALGORITHM_H tools-2021.2/include/votca/tools/graphdistvisitor.h000066400000000000000000000037251412152065700224270ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPHDISTVISITOR_H #define VOTCA_TOOLS_GRAPHDISTVISITOR_H // Standard includes #include #include // Local VOTCA includes #include "graph_bf_visitor.h" /** * \brief A graph visitor determines the graph topology * * This visitor will calculate the distance of each node from the starting node * it is built on top of the graph breadth first visitor. As the visitor moves * through the graph it adds a 'Dist' attribute to each graph node with an * integer value corresponding to how far it is removed from the starting node. * * E.g. * * 0 - 1 - 2 - 3 * * If vertex 1 is the starting vertex than the graph node associated with * vertex 1 will have a distance of 0. Vertices 0 and 2 a distance of 1 and * vertex 3 a distnace of 2. */ namespace votca { namespace tools { class Graph; class Edge; class GraphNode; class Graph_BF_Visitor; class GraphDistVisitor : public Graph_BF_Visitor { public: GraphDistVisitor() = default; /// Note the only manipulation to the BF visitor is the need to add a /// distance attribute to each of the graph nodes. void exploreNode(std::pair& p_gn, Graph& g, Edge ed = DUMMY_EDGE) override; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPHDISTVISITOR_H tools-2021.2/include/votca/tools/graphnode.h000066400000000000000000000063331412152065700207670ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPHNODE_H #define VOTCA_TOOLS_GRAPHNODE_H // Standard includes #include #include #include // Local VOTCA includes #include "types.h" namespace votca { namespace tools { class GraphDistVisitor; /** * \brief A graph node that will take a variety of different values * * The purpose of this object is to allow a level of flexibility when using * graph type algorithms. The object uses its contents to create a string * that is unique to the contents. If two nodes with the same contents are * created they will be considered to be equivalent. * * NOTE: It may be of interest to take a look at the the Boost property map * class, which was designed for a similar purpose. */ class GraphNode { private: std::string str_id_{""}; std::unordered_map int_vals_; std::unordered_map double_vals_; std::unordered_map str_vals_; void initStringId_(); public: GraphNode() = default; /// Constructor /// Each map corresponds to a different content the graph node can contain. GraphNode(const std::unordered_map int_vals, const std::unordered_map double_vals, const std::unordered_map str_vals); /// Basic setters void setInt(const std::unordered_map int_vals); void setDouble(const std::unordered_map double_vals); void setStr(const std::unordered_map str_vals); /// Basic getters Index getInt(const std::string str); double getDouble(const std::string str); std::string getStr(const std::string str); /// Get the string id unique to the contents of the graph node std::string getStringId() const { return str_id_; } bool operator==(const GraphNode gn) const; bool operator!=(const GraphNode gn) const; // Allow visitor to directly access members of the node friend GraphDistVisitor; friend std::ostream& operator<<(std::ostream& os, const GraphNode gn); }; /** * \brief Comparison function to be used with stl sort algorithm * * Given a vector of graph node objects this function can be used to sort them * they are sorted based on the contents of the graphnode which are summarized * in the graph nodes string id. E.g. * * vector vec_gn = { gn1, gn2,...etc }; * * sort(vec_gn.begin(),vec_gn.end(),cmpNode); */ bool cmpNode(GraphNode gn1, GraphNode gn2); } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPHNODE_H tools-2021.2/include/votca/tools/graphvisitor.h000066400000000000000000000067351412152065700215470ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_GRAPHVISITOR_H #define VOTCA_TOOLS_GRAPHVISITOR_H // Standard includes #include #include // Local VOTCA includes #include "edge.h" #include "graphnode.h" /** * \brief A graph visitor class for creating graph visitor objects * * This class serves as the base class for creating graph visitor objects * it contains the framework by which all derived graph visitors should follow. * The function of the graph visitor is to explore a graph, this can be done in * different ways such as a breadth first or depth first algorithm or others. * * The general flow of the class is as follows: * * 1. Set the node the graph visitor will start on and create an edge queue * 2. Get an edge from the edge queue * 3. Explore the edge and operate on the unexplored node(optional) add more * edges to the edge queue. * 4. Repeat until no more edges exist in the queue. */ namespace votca { namespace tools { class Graph; class GraphVisitor { protected: /// set containing all the vertix ids that have been explored std::set explored_; /// The vertex the visitor started on Index startingVertex_ = 0; /// What is done to an individual graph node as it is explored virtual void addEdges_(const Graph& graph, Index vertex) = 0; virtual Edge getEdge_() = 0; /// Edge(0,0) is a dummy value public: virtual void exploreNode(std::pair& vertex_and_node, Graph& graph, Edge edge = DUMMY_EDGE); GraphVisitor() = default; /// Determine which vertices in the edge, if any, have not been explored std::vector getUnexploredVertex(const Edge edge) const; /// Determine if the exploration is complete, this is determined by whether /// the edge queue is empty or not, it does not necessarily mean all /// vertices in a graph have been explored. virtual bool queEmpty() const; void setStartingVertex(Index vertex) { startingVertex_ = vertex; } Index getStartingVertex() const { return startingVertex_; } /// Initialize the graphvisitor the default starting point is 0 void initialize(Graph& graph); /// What the visitor does to each node as it is visited, it will /// simply add the vertex that was explored to the list of explored /// vertices in its current form. virtual void exec(Graph& graph, Edge edge); /// The next edge to be explored, note that when this function /// is called it removes the edge from the visitors queue and will /// no longer be accessible with a second call to nextEdge Edge nextEdge(Graph graph); /// Get the set of all the vertices that have been explored std::set getExploredVertices() const; /// Has the vertex been explored bool vertexExplored(const Index vertex) const; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_GRAPHVISITOR_H tools-2021.2/include/votca/tools/histogram.h000066400000000000000000000045011412152065700210100ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_HISTOGRAM_H #define VOTCA_TOOLS_HISTOGRAM_H // Standard includes #include #include #include // Local VOTCA includes #include "datacollection.h" namespace votca { namespace tools { /** \brief class to generate histograms This class produces a histogram out of a vector of values. This class is obsolate and only used in csg_boltzman. Use HistogramNew instead! */ class Histogram { public: struct options_t; /// constructor Histogram(const options_t &op); Histogram(); /// destructor ~Histogram(); /** process data and generate histogram */ void ProcessData(DataCollection::selection *data); /// returns the minimum value double getMin() const { return _min; } /// return the maximum value double getMax() const { return _max; } /// return the number of grid points Index getN() const { return _options._n; } std::vector &getPdf() { return _pdf; } double getInterval() const { return _interval; } void Normalize(void); struct options_t { Index _n = 101; bool _auto_interval = true; bool _extend_interval = false; double _min = 0; double _max = 1.; bool _periodic = false; bool _normalize = true; std::string _scale = "no"; }; private: std::vector _pdf; double _min = 0; double _max = 0; double _interval; options_t _options; }; inline std::ostream &operator<<(std::ostream &out, Histogram &h) { for (Index i = 0; i < h.getN(); i++) { out << h.getMin() + h.getInterval() * ((double)i + 0.0) << " " << h.getPdf()[i] << std::endl; } return out; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_HISTOGRAM_H tools-2021.2/include/votca/tools/histogramnew.h000066400000000000000000000123251412152065700215250ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_HISTOGRAMNEW_H #define VOTCA_TOOLS_HISTOGRAMNEW_H // Standard includes #include #include // Local VOTCA includes #include "table.h" namespace votca { namespace tools { /** * \brief class to generate histograms * * This class produces a bin centered histogram out of a vector of values. * The min and max values that are provided with the initialization function * will place bins at those positions. For example if I want to create a * histogram for 0 to 5 with bins centered at 0 and 5, I could do: * * HistogramNew hn; * double min_value = 0.0; * double max_value = 5.0; * Index number_bins = 6; * hn.Initialize(min_value, max_value, number_bins); * * This would produce a histogram with bins centered at the positions shown. * below. The upper and lower bounds for each bin are also shown: * * Bin: 1 2 3 4 5 6 * Pos: 0.0 1.0 2.0 3.0 4.0 5.0 * Upper Bound: 0.5 1.5 2.5 3.5 4.5 5.5 * Lower Bound:-0.5 0.5 1.5 2.5 3.5 4.5 * * Step Size: 1.0 * * You also have the option to change the histogram to a periodic bin centered * histogram by setting the periodic value to true; * * hn.setPeriodic(true); * * This has the effect of rearranging the step size. The new histogram would * look like this: * * Bin: 1 2 3 4 5 6 1 * Pos: 0.000 0.833 1.667 2.500 3.333 4.167 5.000 * Upper Bound: 0.416 1.249 2.082 2.910 3.750 4.580 0.416 * Upper Bound: 4.580 0.416 1.249 2.082 2.910 3.750 4.580 * * Step Size: 0.833 * * Note that the bin in position 1 cycles back after bin 6 and that the step * size is smaller this is a result of maintaining the same number of bins to * be clear bin 1 is responsible for any values that fall between * * 0.00 - 0.416 and 4.580 - 5.00 * */ class HistogramNew { public: /** * \brief Initialize the HistogramNew * @param min lower bound of interval * @param max upper bound of interval * @param nbins number of bins */ void Initialize(double min, double max, Index nbins); /** * \brief process a data point * \param v value of this point * \scale scale weighting of this point, bin of v is increased by scale * instead of 1 */ void Process(const double &v, double scale = 1.0); /** \brief process a range of data using iterator interface */ template void ProcessRange(const iterator_type &begin, const iterator_type &end); /** * \brief get the lower bound of the histogram intervaö * \return lower limit of interval */ double getMin() const { return _min; } /** * \brief get the upper bound of the histogram intervaö * \return upper limit of interval */ double getMax() const { return _max; } /** * \brief Get number of grid points * \return number of grid poitns */ Index getNBins() const { return _nbins; } /** * \brief Get the count of the bin with the fewest counts * \return minimum counts */ double getMinBinVal() const; /** * \brief Get the count of the bin with the maximum counts * \return maximum counts */ double getMaxBinVal() const; /** * \brief Given the bin number get the Inverval bounds * @param[in] bin - pass in the index of the bin * \return pair with upper and lower bounds of the interval of the bin */ std::pair getInterval(Index bin) const; /** * \brief get the grid of histogram * \return step per bin */ double getStep() const { return _step; } /** * \brief normalize the histogram that the integral is 1 */ void Normalize(); /** * \brief clear all data */ void Clear(); /** * \brief get access to content of histogram * \return table object with bins in x and values in y */ Table &data() { return _data; } const Table &data() const { return _data; } /** * \brief set whether interval is periodic * \param periodic is periodic */ void setPeriodic(bool periodic) { _periodic = periodic; } private: void Initialize_(); double _min = 0; double _max = 0; double _step = 0; bool _periodic = false; Index _nbins = 100; Table _data; }; inline std::ostream &operator<<(std::ostream &out, HistogramNew &h) { out << h.data(); return out; } template inline void HistogramNew::ProcessRange(const iterator_type &begin, const iterator_type &end) { for (iterator_type iter = begin; iter != end; ++iter) { Process(*iter); } } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_HISTOGRAMNEW_H tools-2021.2/include/votca/tools/identity.h000066400000000000000000000031451412152065700206470ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_IDENTITY_H #define VOTCA_TOOLS_IDENTITY_H // Standard includes #include namespace votca { namespace tools { /** \brief Information about Identity The identity object is meant to provide functionality for storing the id of an object it primariy meant to be used in child classes and provides a more safety than other implementations. */ template class Identity { private: T id_; bool id_set_; public: /// Constructor Identity() : id_set_(false) {} /// Constructor that takes initial id Identity(const T &id) : id_(id), id_set_(true){}; /// Gets the id returns error of the id has not been set const T &getId() const { assert(id_set_ && "No id has been set, cannot get id"); return id_; } /// Set the id void setId(const T &id) { id_set_ = true; id_ = id; } }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_IDENTITY_H tools-2021.2/include/votca/tools/lexical_cast.h000066400000000000000000000025641412152065700214550ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_LEXICAL_CAST_H #define VOTCA_TOOLS_LEXICAL_CAST_H // Standard includes #include #include // Third party includes #include namespace votca { namespace tools { /** * Wrapper for boost::lexical_cast with improved error messages * @param arg variable to convert * @param error additional error text * @return converted value */ template inline Target lexical_cast(const Source &arg, const std::string &error) { try { return boost::lexical_cast(arg); } catch (std::exception &) { throw std::runtime_error("invaid type: " + error); } } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_LEXICAL_CAST_H tools-2021.2/include/votca/tools/linalg.h000066400000000000000000000032251412152065700202630ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_LINALG_H #define VOTCA_TOOLS_LINALG_H // Local VOTCA includes #include "eigen.h" #include "eigensystem.h" #include "types.h" namespace votca { namespace tools { /** * \brief solves A*x=b under the constraint B*x = 0 * @return x * @param A matrix for linear equation system * @param b inhomogenity * @param constr constrained condition * * This function implements the qrsolver under constraints */ Eigen::VectorXd linalg_constrained_qrsolve(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const Eigen::MatrixXd& constr); /** * \brief solves A*V=E*V for the first n eigenvalues * @param A symmetric matrix to diagonalize, is destroyed during iteration * @param nmax number of eigenvalues to return * * This function is only useful if MKL is used, wraps * LAPACKE_dsyevx */ EigenSystem linalg_eigenvalues(Eigen::MatrixXd& A, Index nmax); } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_LINALG_H tools-2021.2/include/votca/tools/linspline.h000066400000000000000000000041561412152065700210160ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_LINSPLINE_H #define VOTCA_TOOLS_LINSPLINE_H // Local VOTCA includes #include "eigen.h" #include "spline.h" namespace votca { namespace tools { /** * \brief A Linear Spline Class * * class supports linear interpolation and linear fit of data */ class LinSpline : public Spline { public: // default constructor LinSpline() = default; // LinSpline() : // _boundaries(splineNormal) {} // destructor ~LinSpline() override = default; // construct an interpolation spline // x, y are the the points to construct interpolation, both vectors must be of // same size void Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // fit spline through noisy data // x,y are arrays with noisy data, both vectors must be of same size void Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) override; // Calculate the function value double Calculate(double r) override; // Calculate the function derivative double CalculateDerivative(double r) override; using Spline::Calculate; using Spline::CalculateDerivative; protected: // a,b for piecewise splines: ax+b Eigen::VectorXd a; Eigen::VectorXd b; }; inline double LinSpline::Calculate(double r) { Index interval = getInterval(r); return a(interval) * r + b(interval); } inline double LinSpline::CalculateDerivative(double r) { Index interval = getInterval(r); return a(interval); } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_LINSPLINE_H tools-2021.2/include/votca/tools/mutex.h000066400000000000000000000022041412152065700201530ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_MUTEX_H #define VOTCA_TOOLS_MUTEX_H // Standard includes #include namespace votca { namespace tools { /** \brief Convenient class for Mutexes * Class allows to create, lock and unlock mutexes. Destroying is handled * by the destructor. */ class Mutex { public: Mutex(); ~Mutex(); void Lock(); void Unlock(); private: pthread_mutex_t _mutexVar; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_MUTEX_H tools-2021.2/include/votca/tools/name.h000066400000000000000000000027531412152065700177420ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_NAME_H #define VOTCA_TOOLS_NAME_H // Standard includes #include #include namespace votca { namespace tools { /** * \brief Name object * * This object is meant to be used a derived type for larger objects. In this * way the same methods for setting and getting the name of an object will be * uniformly defined. * */ class Name { private: std::string name_; bool name_set_{false}; public: Name() = default; Name(const std::string name) : name_(name), name_set_(true){}; void setName(const std::string &name) { name_ = name; name_set_ = true; } const std::string &getName() const { assert(name_set_ && "No name has been set, cannot get name."); return name_; } }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_NAME_H tools-2021.2/include/votca/tools/objectfactory.h000066400000000000000000000071271412152065700216600ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_OBJECTFACTORY_H #define VOTCA_TOOLS_OBJECTFACTORY_H // Standard includes #include #include #include #include // Third party includes #include namespace votca { namespace tools { /** \brief template class for object factory This class is a template for an object factory. The factory creates an instance of an derived class, be giving a key (e.g. a string) for the object which identifies it uniquely. This allows the implementation of new features (e.g. new file formats, new mapping algorithms) without touching or recompiling existing bits of code. If you don't understand this, read the book by Alexandresku (Modern C++ design) everything explained there in detail! */ template class ObjectFactory { private: using creator_t = std::unique_ptr (*)(); public: ObjectFactory() = default; virtual ~ObjectFactory() = default; /** * \brief register an object * \param key identifier * \param creator create policy * * This function is called to register an object in the factory. After an * object is registered, an instance of it can be created by calling Create * specifying the corresponding key. */ void Register(const key_t &key, creator_t creator); template void Register(const key_t &key); /** Create an instance of the object identified by key. */ virtual std::unique_ptr Create(const key_t &key); bool IsRegistered(const key_t &_id) const; std::vector getKeys() const { std::vector key; key.reserve(_objects.size()); for (const auto &pair : _objects) { key.push_back(pair.first); } return key; } private: std::map _objects; }; template std::unique_ptr create_policy_new() { return std::make_unique(); } template inline void ObjectFactory::Register(const key_t &key, creator_t creator) { (void)_objects .insert(typename std::map::value_type(key, creator)) .second; } template template inline void ObjectFactory::Register(const key_t &key) { Register(key, create_policy_new); } template inline std::unique_ptr ObjectFactory::Create(const key_t &key) { typename std::map::const_iterator it = _objects.find(key); if (it != _objects.end()) { return (it->second)(); } else { throw std::runtime_error( "factory key " + boost::lexical_cast(key) + " not found."); } } template inline bool ObjectFactory::IsRegistered(const key_t &_id) const { return (_objects.find(_id) != _objects.end()); } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_OBJECTFACTORY_H tools-2021.2/include/votca/tools/property.h000066400000000000000000000274771412152065700207200ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_PROPERTY_H #define VOTCA_TOOLS_PROPERTY_H // Standard includes #include #include #include #include #include #include // Third party includes #include #include // Local VOTCA includes #include "eigen.h" #include "lexical_cast.h" #include "tokenizer.h" #include "types.h" namespace votca { namespace tools { /** * \brief class to manage program options with xml serialization functionality * * This class stores tags and content in a hierarchical (tree) structure similar * to the one used in the XML format. The structure can be either filled * manually or read in from an XML file using load_property_from_xml. The * supported XML constructs are TAGS, ATTRIBUTES, and CONTENT: content * * The property object can be output to an ostream using format modifiers: * cout << XML << property; * Supported formats are XML, TXT, TEX, HLP */ class Property { /// \brief outputs the property to the ostream friend std::ostream &operator<<(std::ostream &out, const Property &p); public: Property() = default; Property(const std::string &name, const std::string &value, const std::string &path) : _name(name), _value(value), _path(path) {} /** * \brief add a new property to structure * @param key identifier * @param value value * @return reference to the created Property object */ Property &add(const std::string &key, const std::string &value); /** * \brief add a copy of an existing property to a property * @param other other property */ void add(const Property &other); /** * \brief set value of existing property * @param key identifier * @param value value * @return reference to the created Property object */ Property &set(const std::string &key, const std::string &value); /** * \brief get existing property * @param key identifier * @return Reference to property object * * This function tries to find a property specified by key separated * by "." to step down hierarchy. If the property is not * found a runtime_exception is thrown. */ Property &get(const std::string &key); const Property &get(const std::string &key) const; /** * \brief adds new or gets existing property * @param key identifier * @return Reference to property object * * This function tries to find a property specified by key separated * by "." to step down hierarchy. If the property is not * found a property with that name is added and returned. */ Property &getOradd(const std::string &key); /** * \brief check whether property exists * @param key identifier * @return true or false */ bool exists(const std::string &key) const; /** * \brief select property based on a filter * @param filter * @return list of pointers to property objects * * returns a list of properties that match the key criteria including * wildcard "*". Example: "base.item*.value" */ std::vector Select(const std::string &filter); std::vector Select(const std::string &filter) const; /** * \brief reference to value of property * @return std::string content */ std::string &value() { return _value; } const std::string &value() const { return _value; } /** * \brief name of property * @return name */ std::string &name() { return _name; } const std::string &name() const { return _name; } /** * \brief full path of property (including parents) * @return path * * e.g. cg.inverse.value */ std::string &path() { return _path; } const std::string &path() const { return _path; } /** * \brief return value as type * * returns the value after type conversion, e.g. * p.as() returns an integer */ template T as() const; template T ifExistsReturnElseReturnDefault(const std::string &key, T defaultvalue) const; template T ifExistsReturnElseThrowRuntimeError(const std::string &key) const; template T ifExistsAndinListReturnElseThrowRuntimeError( const std::string &key, std::vector possibleReturns) const; /** * \brief does the property has childs? * \return true or false */ bool HasChildren() const { return !_map.empty(); } /// iterator to iterate over properties using iterator = std::vector::iterator; using const_iterator = std::vector::const_iterator; /// \brief iterator to first child property iterator begin() { return _properties.begin(); } const_iterator begin() const { return _properties.begin(); } /// \brief end iterator for child properties iterator end() { return _properties.end(); } const_iterator end() const { return _properties.end(); } /// \brief number of child properties Index size() const { return Index(_properties.size()); } /** * \brief return attribute as type * * returns an attribute after type conversion, e.g. * p.getAttribute() returns an integer */ template T getAttribute(const std::string &attribute) const; /** * \brief set an attribute */ template void setAttribute(const std::string &attribute, const T &value); /** * \brief return true if a node has attributes */ bool hasAttributes() const { return _attributes.size() > 0; } /** * \brief return true if an attribute exists */ bool hasAttribute(const std::string &attribute) const; /** for iterator-based access of Attributes */ typedef std::map::iterator AttributeIterator; typedef std::map::const_iterator const_AttributeIterator; /** * \brief returns an iterator to an attribute */ AttributeIterator findAttribute(const std::string &attribute) { return _attributes.find(attribute); } const_AttributeIterator findAttribute(const std::string &attribute) const { return _attributes.find(attribute); } /** * \brief returns an iterator to the first attribute */ AttributeIterator firstAttribute() { return _attributes.begin(); } const_AttributeIterator firstAttribute() const { return _attributes.begin(); } /** * \brief returns an iterator to the last attribute */ AttributeIterator lastAttribute() { return _attributes.end(); } const_AttributeIterator lastAttribute() const { return _attributes.end(); } /** * \brief return attribute as type * * returns an attribute after type conversion, e.g. * p.getAttribute() returns an integer */ template T getAttribute(AttributeIterator it); template T getAttribute(const_AttributeIterator it) const; void LoadFromXML(std::string filename); static Index getIOindex() { return IOindex; }; private: std::map _map; std::map _attributes; std::vector _properties; std::string _name = ""; std::string _value = ""; std::string _path = ""; static const Index IOindex; }; // TO DO: write a better function for this!!!! template <> inline bool Property::as() const { if (_value == "true" || _value == "TRUE" || _value == "1") { return true; } else { return false; } } template inline T Property::as() const { return lexical_cast(_value, "wrong type in " + _path + "." + _name + "\n"); } template inline T Property::ifExistsReturnElseReturnDefault(const std::string &key, T defaultvalue) const { T result; if (this->exists(key)) { result = this->get(key).as(); } else { result = defaultvalue; } return result; } template inline T Property::ifExistsReturnElseThrowRuntimeError( const std::string &key) const { T result; if (this->exists(key)) { result = this->get(key).as(); } else { throw std::runtime_error( (boost::format("Error: %s is not found") % key).str()); } return result; } template inline T Property::ifExistsAndinListReturnElseThrowRuntimeError( const std::string &key, std::vector possibleReturns) const { T result; result = ifExistsReturnElseThrowRuntimeError(key); if (std::find(possibleReturns.begin(), possibleReturns.end(), result) == possibleReturns.end()) { std::stringstream s; s << "Allowed options are: "; for (Index i = 0; i < Index(possibleReturns.size()); ++i) { s << possibleReturns[i] << " "; } s << std::endl; throw std::runtime_error( s.str() + (boost::format("Error: %s is not allowed") % key).str()); } return result; } template <> inline std::string Property::as() const { std::string tmp(_value); boost::trim(tmp); return tmp; } template <> inline Eigen::VectorXd Property::as() const { std::vector tmp; Tokenizer tok(as(), " ,"); tok.ConvertToVector(tmp); return Eigen::Map(tmp.data(), tmp.size()); } template <> inline Eigen::Vector3d Property::as() const { std::vector tmp; Tokenizer tok(as(), " ,"); tok.ConvertToVector(tmp); Eigen::Vector3d result; if (Index(tmp.size()) != result.size()) { throw std::runtime_error("Vector has " + boost::lexical_cast(tmp.size()) + " instead of three entries"); } result << tmp[0], tmp[1], tmp[2]; return result; } template <> inline std::vector Property::as >() const { std::vector tmp; Tokenizer tok(as(), " ,"); tok.ConvertToVector(tmp); return tmp; } template <> inline std::vector Property::as >() const { std::vector tmp; Tokenizer tok(as(), " ,\n\t"); tok.ConvertToVector(tmp); return tmp; } template inline T Property::getAttribute( std::map::const_iterator it) const { if (it != _attributes.end()) { return lexical_cast((*it).second); } else { std::stringstream s; s << *this << std::endl; throw std::runtime_error(s.str() + "attribute " + (*it).first + " not found\n"); } } template inline T Property::getAttribute(const std::string &attribute) const { std::map::const_iterator it; it = _attributes.find(attribute); if (it != _attributes.end()) { return lexical_cast(_attributes.at(attribute), "wrong type in attribute " + attribute + " of element " + _path + "." + _name + "\n"); } else { std::stringstream s; s << *this << std::endl; throw std::runtime_error(s.str() + "attribute " + attribute + " not found\n"); } } template inline void Property::setAttribute(const std::string &attribute, const T &value) { _attributes[attribute] = lexical_cast(value, "wrong type to set attribute"); } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_PROPERTY_H tools-2021.2/include/votca/tools/propertyiomanipulator.h000066400000000000000000000052021412152065700235020ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_PROPERTYIOMANIPULATOR_H #define VOTCA_TOOLS_PROPERTYIOMANIPULATOR_H // Local VOTCA includes #include "colors.h" #include "property.h" namespace votca { namespace tools { /** * \brief Manipulates the format state of the output stream * * Changes the state of the output stream. Property class reads this state * and formats its output according to this state (XML, TXT, T2T, etc) */ class PropertyIOManipulator { public: enum Type { XML, HLP, TEX, TXT }; explicit PropertyIOManipulator(Type type = XML, Index level = 0, std::string indentation = "", ColorSchemeBase *color_scheme = nullptr) : _type(type), _level(level), _indentation(indentation), _color_scheme(color_scheme) { ; } ~PropertyIOManipulator() { delete _color_scheme; } friend std::ostream &operator<<(std::ostream &os, PropertyIOManipulator &piom) { os.pword(int(Property::getIOindex())) = &piom; return os; } const Type &getType() { return _type; } void setType(Type type) { _type = type; } const Index &getLevel() { return _level; } void setLevel(Index level) { _level = level; } const std::string &getIndentation() { return _indentation; } void setIndentation(std::string indentation) { _indentation = indentation; } const ColorSchemeBase *getColorScheme() { if (!_color_scheme) { return &DEFAULT_COLORS; } return _color_scheme; } template const ColorSchemeBase *setColorScheme() { if (_color_scheme) { delete _color_scheme; } _color_scheme = new Color(); return _color_scheme; } private: Type _type; Index _level; std::string _indentation; ColorSchemeBase *_color_scheme; }; extern PropertyIOManipulator XML; extern PropertyIOManipulator TXT; extern PropertyIOManipulator TEX; extern PropertyIOManipulator HLP; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_PROPERTYIOMANIPULATOR_H tools-2021.2/include/votca/tools/random.h000066400000000000000000000031361412152065700202760ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_RANDOM_H #define VOTCA_TOOLS_RANDOM_H // Standard includes #include // Local VOTCA includes #include "types.h" namespace votca { namespace tools { class Random { public: void init(Index seed) { if (seed < 0) { throw std::runtime_error("seed integer must be positive."); } _mt = std::mt19937(unsigned(seed)); } // draws a random double from [0,1) double rand_uniform() { return _distribution(_mt); } // sets maxint for a uniform integer distribution [0,maxint] void setMaxInt(Index maxint) { _int_distribution = std::uniform_int_distribution{0, maxint}; } // draws from a uniform integer distribution [0,maxint] Index rand_uniform_int() { return _int_distribution(_mt); } private: std::mt19937 _mt; std::uniform_real_distribution _distribution{0.0, 1.0}; std::uniform_int_distribution _int_distribution; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_RANDOM_H tools-2021.2/include/votca/tools/rangeparser.h000066400000000000000000000066761412152065700213430ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_RANGEPARSER_H #define VOTCA_TOOLS_RANGEPARSER_H // Standard includes #include #include #include // Local VOTCA includes #include "types.h" namespace votca { namespace tools { /** * \brief RangeParser * * parse strings like min:step:max, not flexible enough yet to be really useful */ class RangeParser { public: RangeParser(); void Parse(std::string str); void Add(Index begin, Index end, Index stride = 1); private: struct block_t { block_t() = default; block_t(const Index &begin, const Index &end, const Index &stride) : _begin(begin), _end(end), _stride(stride) {} Index _begin, _end, _stride; }; public: struct iterator { iterator() = default; Index operator*() const { return _current; } RangeParser::iterator &operator++(); bool operator==(const RangeParser::iterator &); bool operator!=(const RangeParser::iterator &); private: RangeParser *_parent; iterator(RangeParser *, std::list::iterator); std::list::iterator _block; Index _current; friend class RangeParser; }; RangeParser::iterator begin(); RangeParser::iterator end(); private: void ParseBlock(std::string str); std::list _blocks; friend std::ostream &operator<<(std::ostream &out, const RangeParser &rp); }; inline void RangeParser::Add(Index begin, Index end, Index stride) { _blocks.push_back(block_t(begin, end, stride)); } inline RangeParser::iterator RangeParser::begin() { return RangeParser::iterator(this, _blocks.begin()); } inline RangeParser::iterator RangeParser::end() { return RangeParser::iterator(this, _blocks.end()); } inline RangeParser::iterator::iterator(RangeParser *parent, std::list::iterator block) : _parent(parent), _block(block) { if (block != parent->_blocks.end()) { _current = (*block)._begin; } else { _current = -1; } } inline bool RangeParser::iterator::operator==(const RangeParser::iterator &i) { return (_block == i._block) && (_current == i._current); } inline bool RangeParser::iterator::operator!=(const RangeParser::iterator &i) { return !((_block == i._block) && (_current == i._current)); } inline std::ostream &operator<<(std::ostream &out, const RangeParser &rp) { std::list::const_iterator iter(rp._blocks.begin()); for (; iter != rp._blocks.end(); ++iter) { if (iter != rp._blocks.begin()) { out << ","; } if (iter->_begin == iter->_end) { out << iter->_begin; } else if (iter->_stride == 1) { out << iter->_begin << ":" << iter->_end; } else { out << iter->_begin << ":" << iter->_stride << ":" << iter->_end; } } return out; } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_RANGEPARSER_H tools-2021.2/include/votca/tools/reducededge.h000066400000000000000000000116641412152065700212630ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_REDUCEDEDGE_H #define VOTCA_TOOLS_REDUCEDEDGE_H // Local VOTCA includes #include "edge.h" namespace votca { namespace tools { /** * \brief Connects two vertices, also stores the vertices between the endpoints. * * The edge class stores the ids of two seperate vertices indictating that they * are connected (id1,id2). The vertex with the lower id is always at EndPoint1 * and the vertex with the large id is always placed at end point 2. * * Unlike, the more basic edge class the reduced edge class allows the user to * store a chain of vertices that exist between the two endpoints. For instance * an edge of the form: * * 1 - 2 - 3 - 4 * * Can be stored, in this case EndPoint1 will be vertex 1 and EndPoint2 will be * vertex 4. The class name is called a reduced edge because the edge is treated * as if it were an edge of only two vertices described as * * 1 - 4 * **/ class ReducedEdge : public Edge { public: ReducedEdge() = default; /// Creates an edge the smallest integer value will be placed in the id1 /// spot and the larger in the id2 spot ReducedEdge(std::vector vertices); ReducedEdge(Index vertex1, Index vertex2) : ReducedEdge(std::vector{vertex1, vertex2}){}; /// Returns a vector of vertices that constitute the edge std::vector getChain() const { return vertices_; } /** * \brief Provided a vertex this method will determine if it exists within the * reduced edge. * * Given a reduced edge * * 1 - 2 - 3 - 4 * * Calling the method with vertex 3 will return true as the vertex exists * within the chain stored by the reduced edge. * * \param[in] Index potential vertex stored in the reduced edge * \return bool true if it is in the chain false otherwise **/ bool vertexExistInChain(const int& vertex) const; /** * \brief Method expands the edge into its parts * * This method will take an expanded edge e.g. * * 1 - 2 - 3 - 4 - 5 * * And break it up into its more primitive edges: * * 1 - 2, * 2 - 3, * 3 - 4, * 4 - 5 * * These edges will then be placed in a vector and returned. * * \return vector of edges **/ std::vector expand() const; /// Checks if Edges are equivalent bool operator==(const ReducedEdge& edge) const; /// Checks if Edges are not equivalent bool operator!=(const ReducedEdge& edge) const; /** * The Reduced Edge follows the same rules as the more basic edge when * the EndPoints are differet between the two edges * * If the vertices are smaller in value * Edge ed1(2,3); * Edge ed2(1,5); * Edge ed3(4,1); * priority is given to the smallest vertex * assert(ed2{ 1, 5, 4}); * Edge ed5(vector{ 1, 2, 3, 4}); * * The shorter of the two edges is considered smaller * assert(ed4{ 1, 2, 5, 4}); * assert(ed5(const ReducedEdge& edge) const; bool operator<=(const ReducedEdge& edge) const; bool operator>=(const ReducedEdge& edge) const; using Edge::operator!=; using Edge::operator==; using Edge::operator<; using Edge::operator>; using Edge::operator<=; using Edge::operator>=; /// Print the contents of the edge friend std::ostream& operator<<(std::ostream& os, const ReducedEdge& edge); }; } // namespace tools } // namespace votca /// Define a hasher so we can use it as a key in an unordered_map namespace std { template <> class hash { public: size_t operator()(const votca::tools::ReducedEdge& ed) const { size_t value = 1; auto vertices = ed.getChain(); for (auto vertex : vertices) { value += hash()(static_cast(vertex)) ^ value; } return value; } }; } // namespace std #endif // VOTCA_TOOLS_REDUCEDEDGE_H tools-2021.2/include/votca/tools/reducedgraph.h000066400000000000000000000076201412152065700214550ustar00rootroot00000000000000/* * E * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_REDUCEDGRAPH_H #define VOTCA_TOOLS_REDUCEDGRAPH_H // Local VOTCA includes #include "graph.h" #include "reducededge.h" namespace votca { namespace tools { /** * \brief Contains a graph that consits of vertices with degree of 1 or greater *than 3 * * The point of this class is to reduce the computational complexity of a * regular graph. This is achieved by removing any vertices with degree 2. For * example a graph: * * 1 - 2 - 3 - 4 - 5 - 9 * | | | * 6 - 7 8 * * Would be reduced to * * 1 - 2 - 3 - 4 - 9 * | _ | | * 8 * * Notice that the vertices 5, 6 and 7 have been removed, there also exist two * edges connecting 2 to 3. The reduced graph still contains all the information * associated with the full graph but when used with graph algorithms only the * vertices and nodes associated with the reduced graph are used. * **/ class ReducedGraph : public Graph { private: /** * The inherited graph stores all the edges describing the graph after it * has been reduced. However, in order to expand the edges back to the * vertices that make them up a second variable is needed. * * E.g. * * 1 - 2 - 4 - 9 - 5 * * The edge * * 1 - 5 * * Would be stored in the parent graph datastructure, the rest of the * vertices are stored as a vector in the expanded_edges_ object **/ std::unordered_map>> expanded_edges_; void init_(std::vector reduced_edges, std::unordered_map nodes); // Junctions must be stored internally std::set junctions_; public: ReducedGraph() = default; ReducedGraph(std::vector reduced_edges); ReducedGraph(std::vector reduced_edges, std::unordered_map nodes); /** * \brief Allows one to return all edges connecting two vertices of the *reduced graph. * * In this case if edge (2,3) were passed in: * * 1 - 2 - 3 - 4 - 5 - 9 * | | | * 6 - 7 8 * * Reduced Graph * * 1 - 2 - 3 - 4 - 9 * | _ | | * 8 * * The following vectors would be returned * * vec_edges = expandEdge(Edge(2,3)); * vec_edges.at(0); // 2-3 * vec_edges.at(1); // 2-6, 6-7, 7-3 **/ std::vector> expandEdge(const Edge& edge) const; /// This method will return a copy of the full graph Graph expandGraph() const; /** * \brief Gets the junctions in the graph. * * This method is different from the regular graph method as it must account * for edges that loop around and refer to the same vertex. * * E.g. * * - - * | | * - -1 - 2 - 3 * * This is composed of the edges: * 1, 1 * 1, 2 * 2, 3 * * Thus 1 is the only junction that exists in the reduced graph **/ // std::vector getJunctions() const; std::vector> getNodes(void) const override; std::vector getVerticesDegree(Index degree) const override; friend std::ostream& operator<<(std::ostream& os, const ReducedGraph graph); }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_REDUCEDGRAPH_H tools-2021.2/include/votca/tools/spline.h000066400000000000000000000121461412152065700203110ustar00rootroot00000000000000/* * Copyright 2010-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_SPLINE_H #define VOTCA_TOOLS_SPLINE_H // Local VOTCA includes #include "eigen.h" #include "types.h" namespace votca { namespace tools { /** * \brief Spline Class * * class supports spline interpolation and fit of data * the cubic spline class, akima spline class and linear spline class are * inherited from this one */ class Spline { public: Spline() = default; virtual ~Spline() = default; /** * \brief Calculate interpolating spline for given (x,y) values. Points on * resulting spline can be obtained via Calculate(). \param x values of data * to be interpolated \param y values of data to be interpolated both vectors * must be of same size */ virtual void Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) = 0; /** * \brief Fit spline through noisy (x,y) values. Points on resulting fitted * spline can be obtained via Calculate(). \param x values of data to be * fitted \param y values of data to be fitted both vectors must be of same * size */ virtual void Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) = 0; /** * \brief Calculate spline function value for a given x value on the spline * created by Interpolate() or Fit() \param x data value \return y value */ virtual double Calculate(double x) = 0; /** * \brief Calculate y value for a given x value on the derivative of the * spline created by function Interpolate or Fit \param x data value \return y * value of derivative */ virtual double CalculateDerivative(double x) = 0; /// enum for type of boundary condition enum eBoundary { splineNormal = 0, ///< normal boundary conditions: \f$f_0=f_N=0\f$ splinePeriodic = 1, ///< periodic boundary conditions: \f$f_0=f_N\f$ splineDerivativeZero = 2 ///< derivatives and end-points are zero. }; /** * \brief Set the boundary type of the spline * \param boundary of type eBoundary */ void setBC(eBoundary bc) { _boundaries = bc; } /** * \brief Set the boundary type of the spline * \param boundary of type int */ void setBCInt(Index bc) { switch (bc) { case 0: _boundaries = splineNormal; break; case 1: _boundaries = splinePeriodic; break; case 2: _boundaries = splineDerivativeZero; break; } } /** * \brief Get the grid point of certain index * \param index of grid point * \return grid value */ double getGridPoint(int i); /** * \brief Calculate spline function values for given x values on the spline * created by Interpolate() or Fit() \param vector of x data values \return * vector of y value */ Eigen::VectorXd Calculate(const Eigen::VectorXd &x); /** * \brief Calculate y values for given x values on the derivative of the * spline created by function Interpolate or Fit \param vector of x data * values \return vector of y value */ Eigen::VectorXd CalculateDerivative(const Eigen::VectorXd &x); /** * \brief Print spline values (using Calculate()) on output "out" on the * entire grid in steps of "interval" \param reference "out" to output \param * steps of size "interval" */ void Print(std::ostream &out, double interval); /** * \brief Determine the index of the interval containing value r * \param value r * \return interval index */ Index getInterval(double r); /** * \brief Generate the grid for fitting from "min" to "max" in steps of "h" * \param left interval border "min" * \param right interval border "max" * \param step "h" * \return number of grid values in the interval */ Index GenerateGrid(double min, double max, double h); /** * \brief Get the grid array x * \return pointer to the corresponding array */ Eigen::VectorXd &getX() { return _r; } const Eigen::VectorXd &getX() const { return _r; } /** * \brief Get the spline data _f * \return reference to the corresponding array */ // Eigen::VectorXd &getSplineF() { return _f; } // const Eigen::VectorXd &getSplineF() const { return _f; } /** * \brief Get second derivatives (cubic splines) * \return reference to the corresponding array */ // Eigen::VectorXd &getSplineF2() { return _f2; } // const Eigen::VectorXd &getSplineF2() const { return _f; } protected: eBoundary _boundaries = eBoundary::splineNormal; // the grid points Eigen::VectorXd _r; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_SPLINE_H tools-2021.2/include/votca/tools/structureparameters.h000066400000000000000000000070131412152065700231400ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_STRUCTUREPARAMETERS_H #define VOTCA_TOOLS_STRUCTUREPARAMETERS_H // Standard includes #include #include // Third party includes #include namespace votca { namespace tools { /** * \brief Supported and Standardized parameter types **/ enum StructureParameter { Mass, Position, MoleculeId, ResidueId, Charge, Element, Symmetry, ResidueType, BeadId, BeadType, MoleculeType }; /** * \brief Provides a means to standardise the constructors of different classes * * The purpose of this class is for use primarily in io readers, it provides * a means to standardize the use of templated classes in the readers. * * E.g. Say I have two atom classes * * class Atom1 { * public: * Atom1(StructureParameters parameters) : * id_(parameters.get(StructureParameter::BeadId)), * mass_(parameters.get(StructureParameter::Mass)){}; * * private: * Index id_; * double mass_; * }; * * class Atom2 { * public: * Atom2(StructureParameters parameters) : * id_(parameters.get(StructureParameter::BeadId)), * element_(parameters.get(StructureParameter::Element)){}; * * private: * Index id_; * string element_; * }; * * Pseudo code below, our file reader has a method that creates the atoms * (shown below), now because we have a standardized constructor the templated * file method can be used with either class without specialization. * * class FileReader { * * template * T CreateAtomOrBead { * * string element = "C"; * Index id = 1; * double mass = 12.01; * * StructureParameters parameters; * parameters.set(StructureParameter::Element,element); * parameters.set(StructureParameter::Mass,mass); * parameters.set(StructureParameter::BeadId,id); * * T atom_or_bead(parameters); * return atom_or_bead; * } * * }; **/ class StructureParameters { public: void set(const StructureParameter parameter, boost::any value) noexcept; template T get(const StructureParameter parameter) const; private: std::unordered_map> parameters; }; void StructureParameters::set(const StructureParameter parameter, boost::any value) noexcept { parameters[parameter] = value; } template T StructureParameters::get(const StructureParameter parameter) const { assert(parameters.count(parameter) && "StructureParameter is not stored in StructureParameters class"); assert(typeid(T) == parameters.at(parameter).type() && "Cannot return boost any value from parameters class because it is " "not being cast to the correct type"); return boost::any_cast(parameters.at(parameter)); } } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_STRUCTUREPARAMETERS_H tools-2021.2/include/votca/tools/table.h000066400000000000000000000067001412152065700201050ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_TABLE_H #define VOTCA_TOOLS_TABLE_H // Standard includes #include #include // Local VOTCA includes #include "eigen.h" #include "types.h" namespace votca { namespace tools { /** \brief class to store tables like rdfs, tabulated potentials, etc \think about weather to make this a template, can be used in histogram as well, of for counting with integers... */ class Table { public: void clear(); void GenerateGridSpacing(double min, double max, double spacing); void resize(Index N); Index size() const { return _x.size(); } double &x(Index i) { return _x[i]; } double &y(Index i) { return _y[i]; } const double &x(Index i) const { return _x[i]; } const double &y(Index i) const { return _y[i]; } char &flags(Index i) { return _flags[i]; } double &yerr(Index i) { return _yerr[i]; } void set(const Index &i, const double &x, const double &y) { _x[i] = x; _y[i] = y; } void set(const Index &i, const double &x, const double &y, const char &flags) { _x[i] = x; _y[i] = y; _flags[i] = flags; } void set(const Index &i, const double &x, const double &y, const char &flags, const double &yerr) { _x[i] = x; _y[i] = y; _flags[i] = flags; _yerr[i] = yerr; } void set_comment(const std::string comment) { _has_comment = true; _comment_line = comment; } void Load(std::string filename); void Save(std::string filename) const; void Smooth(Index Nsmooth); bool GetHasYErr() { return _has_yerr; } void SetHasYErr(bool has_yerr) { _has_yerr = has_yerr; } /** * \brief Gets the maximum value in the y column * \return - max value */ double getMaxY() const; /** * \brief Gets the minimum value in the y column * \return - min value */ double getMinY() const; /** * \brief Gets the maximum value in the x column * \return - max value */ double getMaxX() const; /** * \brief Gets the minimum value in the x column * \return - min value */ double getMinX() const; Eigen::VectorXd &x() { return _x; } Eigen::VectorXd &y() { return _y; } std::vector &flags() { return _flags; } Eigen::VectorXd &yerr() { return _yerr; } void push_back(double x, double y, char flags = ' '); const std::string &getErrorDetails() { return _error_details; } void setErrorDetails(std::string str) { _error_details = str; } private: Eigen::VectorXd _x; Eigen::VectorXd _y; std::vector _flags; Eigen::VectorXd _yerr; std::string _error_details = ""; bool _has_yerr = false; bool _has_comment = false; friend std::ostream &operator<<(std::ostream &out, const Table &t); friend std::istream &operator>>(std::istream &in, Table &t); std::string _comment_line; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_TABLE_H tools-2021.2/include/votca/tools/thread.h000066400000000000000000000037121412152065700202650ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_THREAD_H #define VOTCA_TOOLS_THREAD_H // Standard includes #include namespace votca { namespace tools { /** * \brief Framework for threaded execution * * The Thread class handles the threaded execution of VOTCA code. * In its current state, it is based on POSIX threads. * It mainly contains a wrapper, a start and a wait function. * This class should not be touched by the user. **/ class Thread { public: Thread(); virtual ~Thread(); /** * \brief Starts and runs a thread * * This method is responsible for creating and running the thread. **/ void Start(); /** * \brief WaitDone() will not exit until thread ends computation. */ void WaitDone(); /** * \brief Checks to see if the thread is done * * \return True if thread is done, False otherwise **/ bool IsFinished() const; protected: /** * \brief Run() executes the actual code. * * It is left blank here and must be overloaded, for the thread to do * any work. This method should never be called by the user, it is * called internally by the Start method. */ virtual void Run(void) = 0; friend void *runwrapper(void *arg); private: pthread_attr_t _attr; pthread_t _thread; bool _finished; }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_THREAD_H tools-2021.2/include/votca/tools/tokenizer.h000066400000000000000000000070551412152065700210340ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_TOKENIZER_H #define VOTCA_TOOLS_TOKENIZER_H // Standard includes #include #include // Third party includes #include #include namespace votca { namespace tools { /** * \brief break string into words * * This class wraps boost::tokenizer to break a string into words. A list of * delimeters can be freely choosen. */ class Tokenizer { public: using iterator = boost::tokenizer>::iterator; /** * \brief startup tokenization * @param str string to break up * @param separators list of separators * * After initialization,the words can be accessed using the iterator * interface or directly transferred to a vector ToVector of ConvertToVector. */ Tokenizer(const std::string &str, const char *separators) : _str(str) { boost::char_separator sep(separators); tok = std::make_unique>>(_str, sep); } Tokenizer(const std::string &str, const std::string &separators) : Tokenizer(str, separators.c_str()){}; /** * \brief iterator to first element * @return begin iterator */ iterator begin() { return tok->begin(); } /** * \brief end iterator * @return end iterator */ iterator end() { return tok->end(); } /** * \brief store all words in a vector of strings. * @param v storage vector * * This class appends all words to a vector of strings. */ void ToVector(std::vector &v) { for (iterator iter = begin(); iter != end(); ++iter) { v.push_back(*iter); } } std::vector ToVector() { std::vector result; for (iterator iter = begin(); iter != end(); ++iter) { result.push_back(*iter); } return result; } /** * \brief store all words in a vector with type conversion. * @param v storage vector * * This class appends all words to a vector of arbitrary type (e.g. double) * and also does type conversion. */ template void ConvertToVector(std::vector &v) { std::vector tmp; ToVector(tmp); v.resize(tmp.size()); typename std::vector::iterator viter = v.begin(); typename std::vector::iterator iter; for (iter = tmp.begin(); iter != tmp.end(); ++iter, ++viter) { *viter = boost::lexical_cast(*iter); } } private: std::unique_ptr>> tok; std::string _str; }; // Matches a string against a wildcard string such as "*.*" or // "bl?h.*" etc. This is good for file globbing or to match hostmasks. int wildcmp(const char *wild, const char *string); int wildcmp(const std::string &wild, const std::string &string); } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_TOKENIZER_H tools-2021.2/include/votca/tools/types.h000066400000000000000000000015151412152065700201610ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_TYPES_H #define VOTCA_TOOLS_TYPES_H // Local VOTCA includes #include "eigen.h" namespace votca { using Index = Eigen::Index; } // namespace votca #endif // VOTCA_TOOLS_TYPES_H tools-2021.2/include/votca/tools/unitconverter.h000066400000000000000000000221771412152065700217330ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #pragma once #ifndef VOTCA_TOOLS_UNITCONVERTER_H #define VOTCA_TOOLS_UNITCONVERTER_H // Standard includes #include namespace votca { namespace tools { enum DistanceUnit { meters, centimeters, nanometers, angstroms, bohr }; enum MassUnit { attograms, picograms, femtograms, atomic_mass_units, grams_per_mole, // the same as atomic mass units kilograms, grams }; enum TimeUnit { seconds, microseconds, nanoseconds, femtoseconds, picoseconds }; // Extrinsic Energy Units enum EnergyUnit { electron_volts, kilocalories, hartrees, joules, kilojoules, }; // Intrinsic Energy Units enum MolarEnergyUnit { kilojoules_per_mole, joules_per_mole, kilocalories_per_mole, electron_volts_per_mole, hartrees_per_mole }; enum ChargeUnit { e, coulombs }; enum VelocityUnit { angstroms_per_femtosecond, angstroms_per_picosecond, nanometers_per_picosecond }; // Extrinsic Force Units enum ForceUnit { kilocalories_per_angstrom, newtons, kilojoules_per_nanometer, kilojoules_per_angstrom, hatree_per_bohr }; // Intrinsic Force Units enum MolarForceUnit { kilocalories_per_mole_angstrom, newtons_per_mole, kilojoules_per_mole_nanometer, kilojoules_per_mole_angstrom, hatree_per_mole_bohr }; /** * @brief Class converts between different unit types */ class UnitConverter { private: /// All distances with respect to Ang constexpr double getDistanceValue_( const DistanceUnit& enum_type) const noexcept { switch (enum_type) { case DistanceUnit::meters: return 1E-10; case DistanceUnit::centimeters: return 1E-8; case DistanceUnit::nanometers: return 0.1; case DistanceUnit::angstroms: return 1.0; case DistanceUnit::bohr: return 1.8897161646321; } return 0.0; } /// All times with respect to pico seconds constexpr double getTimeValue_(const TimeUnit& enum_type) const noexcept { switch (enum_type) { case TimeUnit::seconds: return 1E-12; case TimeUnit::microseconds: return 1E-6; case TimeUnit::nanoseconds: return 1E-3; case TimeUnit::picoseconds: return 1.0; case TimeUnit::femtoseconds: return 1000; } return 0.0; } /// All masses with respect to atomic mass units constexpr double getMassValue_(const MassUnit& enum_type) const noexcept { switch (enum_type) { case MassUnit::kilograms: return 1.6605402E-27; case MassUnit::grams: return 1.6605402E-24; case MassUnit::picograms: return 1.6605402E-12; case MassUnit::femtograms: return 1.6605402E-9; case MassUnit::attograms: return 1.66054019E-6; case MassUnit::atomic_mass_units: return 1.0; case MassUnit::grams_per_mole: return 1.0; } return 0.0; } /// All energies in terms of electron volts constexpr double getEnergyValue_(const EnergyUnit& enum_type) const noexcept { switch (enum_type) { case EnergyUnit::kilocalories: return 3.82929389E-23; case EnergyUnit::kilojoules: return 1.602176634E-22; case EnergyUnit::joules: return 1.602176634E-19; case EnergyUnit::hartrees: return 0.0367493; case EnergyUnit::electron_volts: return 1.0; } return 0.0; } // All molar energies in terms of eV_per_mole constexpr double getMolarEnergyValue_( const MolarEnergyUnit& enum_type) const noexcept { switch (enum_type) { case MolarEnergyUnit::kilojoules_per_mole: return 1.602176634E-22; case MolarEnergyUnit::joules_per_mole: return 1.602176634E-19; case MolarEnergyUnit::kilocalories_per_mole: return 3.82929389E-23; case MolarEnergyUnit::hartrees_per_mole: return 0.0367493; case MolarEnergyUnit::electron_volts_per_mole: return 1.0; } return 0.0; } /// All charge in terms of elementary charge e constexpr double getChargeValue_(const ChargeUnit& enum_type) const noexcept { switch (enum_type) { case ChargeUnit::e: return 1; case ChargeUnit::coulombs: return 1.602176565E-19; } return 0.0; } /// All velocities in terms of nanometers per picosecond constexpr double getVelocityValue_( const VelocityUnit& enum_type) const noexcept { switch (enum_type) { case VelocityUnit::nanometers_per_picosecond: return 1.0; case VelocityUnit::angstroms_per_picosecond: return convert(DistanceUnit::nanometers, DistanceUnit::angstroms); case VelocityUnit::angstroms_per_femtosecond: return convert(DistanceUnit::nanometers, DistanceUnit::angstroms) / convert(TimeUnit::picoseconds, TimeUnit::femtoseconds); } return 0.0; } /// Default force unit is the kilojoules per nanometer constexpr double getForceValue_(const ForceUnit& enum_type) const noexcept { switch (enum_type) { case ForceUnit::kilocalories_per_angstrom: return convert(EnergyUnit::kilojoules, EnergyUnit::kilocalories) / convert(DistanceUnit::nanometers, DistanceUnit::angstroms); case ForceUnit::newtons: return convert(EnergyUnit::kilojoules, EnergyUnit::joules) / convert(DistanceUnit::nanometers, DistanceUnit::meters); case ForceUnit::kilojoules_per_nanometer: return 1.0; case ForceUnit::kilojoules_per_angstrom: return (1.0) / convert(DistanceUnit::nanometers, DistanceUnit::angstroms); case ForceUnit::hatree_per_bohr: return convert(EnergyUnit::kilojoules, EnergyUnit::hartrees) / (convert(DistanceUnit::nanometers, DistanceUnit::bohr)); } return 0.0; } /// Default force unit is the kilojoules per mole nanometer constexpr double getMolarForceValue_( const MolarForceUnit& enum_type) const noexcept { switch (enum_type) { case MolarForceUnit::kilocalories_per_mole_angstrom: return convert(MolarEnergyUnit::kilojoules_per_mole, MolarEnergyUnit::kilocalories_per_mole) / convert(DistanceUnit::nanometers, DistanceUnit::angstroms); case MolarForceUnit::newtons_per_mole: return convert(MolarEnergyUnit::kilojoules_per_mole, MolarEnergyUnit::joules_per_mole) / convert(DistanceUnit::nanometers, DistanceUnit::meters); case MolarForceUnit::kilojoules_per_mole_nanometer: return 1.0; case MolarForceUnit::kilojoules_per_mole_angstrom: return (1.0) / convert(DistanceUnit::nanometers, DistanceUnit::angstroms); case MolarForceUnit::hatree_per_mole_bohr: return convert(MolarEnergyUnit::kilojoules_per_mole, MolarEnergyUnit::hartrees_per_mole) / (convert(DistanceUnit::nanometers, DistanceUnit::bohr)); } return 0.0; } public: constexpr double convert(const DistanceUnit& from, const DistanceUnit& to) const noexcept { return getDistanceValue_(to) / getDistanceValue_(from); } constexpr double convert(const TimeUnit& from, const TimeUnit& to) const noexcept { return getTimeValue_(to) / getTimeValue_(from); } constexpr double convert(const MassUnit& from, const MassUnit& to) const noexcept { return getMassValue_(to) / getMassValue_(from); } constexpr double convert(const EnergyUnit& from, const EnergyUnit& to) const noexcept { return getEnergyValue_(to) / getEnergyValue_(from); } constexpr double convert(const MolarEnergyUnit& from, const MolarEnergyUnit& to) const noexcept { return getMolarEnergyValue_(to) / getMolarEnergyValue_(from); } constexpr double convert(const ChargeUnit& from, const ChargeUnit& to) const noexcept { return getChargeValue_(to) / getChargeValue_(from); } constexpr double convert(const VelocityUnit& from, const VelocityUnit& to) const noexcept { return getVelocityValue_(to) / getVelocityValue_(from); } constexpr double convert(const ForceUnit& from, const ForceUnit& to) const noexcept { return (getForceValue_(to)) / (getForceValue_(from)); } constexpr double convert(const MolarForceUnit& from, const MolarForceUnit& to) const noexcept { return (getMolarForceValue_(to)) / (getMolarForceValue_(from)); } }; } // namespace tools } // namespace votca #endif // VOTCA_TOOLS_UNITCONVERTER_H tools-2021.2/include/votca/tools/version.h000066400000000000000000000015531412152065700205040ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef VOTCA_TOOLS_VERSION_H #define VOTCA_TOOLS_VERSION_H // Standard includes #include namespace votca { namespace tools { const std::string& ToolsVersionStr(); } } // namespace votca #endif // VOTCA_TOOLS_VERSION_H tools-2021.2/include/votca/tools/votca_tools_config.h.in000066400000000000000000000017601412152065700233050ustar00rootroot00000000000000/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #ifndef __VOTCA_TOOLS_VOTCA_CONFIG_H #define __VOTCA_TOOLS_VOTCA_CONFIG_H /* Linear algebra packages */ #cmakedefine MKL_FOUND /* FFT library */ #cmakedefine FFTW3_FOUND /* Version number of package */ #define TOOLS_VERSION "@PROJECT_VERSION@" /* Contact address of package */ #define TOOLS_BUGREPORT "@PROJECT_CONTACT@" #endif // __VOTCA_TOOLS_VOTCA_CONFIG_H tools-2021.2/scripts/000077500000000000000000000000001412152065700144325ustar00rootroot00000000000000tools-2021.2/scripts/CMakeLists.txt000066400000000000000000000030621412152065700171730ustar00rootroot00000000000000option(INSTALL_RC_FILES "Install votca rc files, no need when installing under /usr" ON) add_feature_info(INSTALL_RC_FILES INSTALL_RC_FILES "Install votca rc files (VOTCARC.bash etc.)") if(INSTALL_RC_FILES) if(APPLE) set(LD_LIBRARY_PATH "DYLD_LIBRARY_PATH") else(APPLE) set(LD_LIBRARY_PATH "LD_LIBRARY_PATH") endif(APPLE) configure_file(VOTCARC.csh.in ${CMAKE_CURRENT_BINARY_DIR}/VOTCARC.csh @ONLY) configure_file(VOTCARC.bash.in ${CMAKE_CURRENT_BINARY_DIR}/VOTCARC.bash @ONLY) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/VOTCARC.csh ${CMAKE_CURRENT_BINARY_DIR}/VOTCARC.bash DESTINATION ${CMAKE_INSTALL_BINDIR}) endif(INSTALL_RC_FILES) foreach(SCRIPT votca_compare) configure_file(${SCRIPT}.in ${CMAKE_CURRENT_BINARY_DIR}/${SCRIPT}.tmp.out @ONLY) add_custom_target(${SCRIPT}_build ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${SCRIPT}) add_custom_command(OUTPUT ${SCRIPT} COMMAND ${CMAKE_COMMAND} -DINPUT="${SCRIPT}.tmp.out" -DOUTPUT="${SCRIPT}" -DGIT_EXECUTABLE="${GIT_EXECUTABLE}" -DTOP_SOURCE_DIR="${CMAKE_SOURCE_DIR}" -P ${PROJECT_SOURCE_DIR}/CMakeModules/gitscript.cmake DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${SCRIPT}.tmp.out ${PROJECT_SOURCE_DIR}/CMakeModules/gitscript.cmake) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${SCRIPT}) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${SCRIPT} DESTINATION ${CMAKE_INSTALL_BINDIR}) endforeach(SCRIPT) add_executable(VOTCA::votca_compare IMPORTED GLOBAL) set_property(TARGET VOTCA::votca_compare PROPERTY IMPORTED_LOCATION "${CMAKE_CURRENT_BINARY_DIR}/votca_compare") tools-2021.2/scripts/VOTCARC.bash.in000066400000000000000000000021721412152065700170010ustar00rootroot00000000000000#!/usr/bin/env bash # # Copyright 2009-2017 The VOTCA Development Team (http://www.votca.org) # # 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. # #path is never empty PATH="@CMAKE_INSTALL_FULL_BINDIR@:${PATH}" #debian wants to have : at the end MANPATH="@CMAKE_INSTALL_FULL_MANDIR@:${MANPATH}" @LD_LIBRARY_PATH@="@CMAKE_INSTALL_FULL_LIBDIR@${@LD_LIBRARY_PATH@:+:}${@LD_LIBRARY_PATH@}" VOTCASHARE="@CMAKE_INSTALL_FULL_DATADIR@/votca" export PATH MANPATH @LD_LIBRARY_PATH@ VOTCASHARE #bash completion if [ -n "$BASH_VERSION" ]; then for comp in "${VOTCASHARE}"/rc/*completion.bash; do [ -r "$comp" ] && source "$comp" done unset comp fi tools-2021.2/scripts/VOTCARC.csh.in000066400000000000000000000021261412152065700166400ustar00rootroot00000000000000#!/usr/bin/env csh # # Copyright 2009-2017 The VOTCA Development Team (http://www.votca.org) # # 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. # #path is never empty setenv PATH "@CMAKE_INSTALL_FULL_BINDIR@:${PATH}" #debian wants to have : at the end if (! $?MANPATH) setenv MANPATH "" setenv MANPATH "@CMAKE_INSTALL_FULL_MANDIR@:${MANPATH}" if (! $?@LD_LIBRARY_PATH@) setenv @LD_LIBRARY_PATH@ "" if ( "$@LD_LIBRARY_PATH@" != "" ) setenv @LD_LIBRARY_PATH@ ":${@LD_LIBRARY_PATH@}" setenv @LD_LIBRARY_PATH@ "@CMAKE_INSTALL_FULL_LIBDIR@${@LD_LIBRARY_PATH@}" setenv VOTCASHARE "@CMAKE_INSTALL_FULL_DATADIR@/votca" tools-2021.2/scripts/votca_compare.in000066400000000000000000000075401412152065700176120ustar00rootroot00000000000000#! /usr/bin/env python3 # # Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) # # 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. # import sys import os import argparse VERSION = '@PROJECT_VERSION@ #TOOLS_GIT_ID#' PROGTITLE = 'THE VOTCA::TOOLS FILE COMPARISON' PROGDESCR = 'COMPARES TWO FILES TO EACH OTHER' VOTCAHEADER = ''' ================================================== ======== VOTCA (http://www.votca.org) ======== ================================================== {progtitle} please submit bugs to bugs@votca.org votca_compare, version {version} '''.format(version=VERSION, progtitle=PROGTITLE) def xxquit(what=''): if what != '': print("ERROR: {what}".format(what=what)) sys.exit(1) def RepresentsFloat(s): try: float(s) return True except ValueError: return False def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) # ============================================================================= # PROGRAM OPTIONS # ============================================================================= class ToolsHelpFormatter(argparse.HelpFormatter): def _format_usage(self, usage, action, group, prefix): return VOTCAHEADER progargs = argparse.ArgumentParser(prog='votca_compare', formatter_class=lambda prog: ToolsHelpFormatter(prog, max_help_position=70), description=PROGDESCR) progargs.add_argument('-f1', '--file1', dest='file1', action='store', required=True, type=argparse.FileType('r'), help='File1 to compare.') progargs.add_argument('-f2', '--file2', dest='file2', action='store', required=True, type=argparse.FileType('r'), help='File2 to compare') progargs.add_argument('--etol', dest='etol', action='store', type=float, default=1e-5, help='Tolerance for floats to be regarded equal,default=1e-5') OPTIONS = progargs.parse_args() # ============================================================================= # Compare Execution # ============================================================================= print("Comparing {} and {} to a tolerance of {}".format(OPTIONS.file1.name, OPTIONS.file2.name, OPTIONS.etol)) logs = [] for i, (line1, line2) in enumerate(zip(OPTIONS.file1, OPTIONS.file2)): if line1.startswith('#') or line2.startswith('#'): continue for j, (entry1, entry2) in enumerate(zip(line1.split(), line2.split())): if RepresentsFloat(entry1) and RepresentsFloat(entry2): if not isclose(float(entry1),float(entry2),OPTIONS.etol,OPTIONS.etol): logs.append([i, j, entry1, entry2]) elif entry1 != entry2: logs.append([i, j, entry1, entry2]) if not logs: sys.exit(0) else: print("Diff:") for diff in logs: print("row {} col {}:\t{} vs {}".format(diff[0], diff[1], diff[2], diff[3])) sys.exit(1) tools-2021.2/share/000077500000000000000000000000001412152065700140455ustar00rootroot00000000000000tools-2021.2/share/man/000077500000000000000000000000001412152065700146205ustar00rootroot00000000000000tools-2021.2/share/man/CMakeLists.txt000066400000000000000000000006651412152065700173670ustar00rootroot00000000000000if (BUILD_MANPAGES) string(TIMESTAMP VOTCA_DATE "%Y/%m/%d" UTC) configure_file(votca-tools.man.in ${CMAKE_CURRENT_BINARY_DIR}/votca-tools.man) add_custom_target(votca_tools_manpages DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/votca-tools.man) add_dependencies(manpages votca_tools_manpages) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/votca-tools.man DESTINATION ${CMAKE_INSTALL_MANDIR}/man7 RENAME votca-tools.7) endif (BUILD_MANPAGES) tools-2021.2/share/man/votca-tools.man.in000066400000000000000000000030151412152065700201730ustar00rootroot00000000000000.TH "votca-tools" 7 "@VOTCA_DATE@" "VOTCA Development Team " .SH NAME .P votca\-tools \- The basic tools library of the VOTCA package .SH DESCRIPTION .P votca\-tools provides the basic functions used by all parts of the VOTCA package. .P Please visit the program site at __http://www.votca.org__. .SH SYNOPSIS .P If VOTCA was installed in a non\-default location one can use the VOTCARC file to set the important environment variables (PATH, MANPATH, CSGSHARE). .P In bash shell: \fBsource VOTCARC.bash\fR .P In tcsh shell: \fBsource VOTCARC.csh\fR .P In sh shell: \fB. VOTCARC.bash\fR .SH AUTHORS .P Written and maintained by the VOTCA Development Team .P This Manual Page converted from t2t format to the this format by txt2tags (http://txt2tags.org) ! .SH COPYRIGHT .P Copyright 2009\-2019 The VOTCA Development Team (http://www.votca.org) .P 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 .P http://www.apache.org/licenses/LICENSE\-2.0 .P 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. .\" man code generated by txt2tags 2.6 (http://txt2tags.org) .\" cmdline: txt2tags -q -t man -i votca-tools.t2t.in -o votca-tools.man.in tools-2021.2/share/man/votca-tools.t2t.in000066400000000000000000000030021412152065700201250ustar00rootroot00000000000000votca-tools VOTCA Development Team @VOTCA_DATE@ %to build votca-tools.man run: %txt2tags -q -t man -i votca-tools.t2t.in -o votca-tools.man.in %make the manpage type 7, txt2tags does 1 by default %!postproc(man): "^(\.TH.*) 1 " "\1 7 " = NAME = votca-tools - The basic tools library of the VOTCA package = DESCRIPTION = votca-tools provides the basic functions used by all parts of the VOTCA package. Please visit the program site at __http://www.votca.org__. = SYNOPSIS = If VOTCA was installed in a non-default location one can use the VOTCARC file to set the important environment variables (PATH, MANPATH, CSGSHARE). In bash shell: **source VOTCARC.bash** In tcsh shell: **source VOTCARC.csh** In sh shell: **. VOTCARC.bash** = AUTHORS = Written and maintained by the VOTCA Development Team This Manual Page converted from t2t format to the this format by [txt2tags http://txt2tags.org] ! = COPYRIGHT = Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) 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. tools-2021.2/src/000077500000000000000000000000001412152065700135325ustar00rootroot00000000000000tools-2021.2/src/CMakeLists.txt000066400000000000000000000001501412152065700162660ustar00rootroot00000000000000add_subdirectory(libtools) add_subdirectory(tools) if(ENABLE_TESTING) add_subdirectory(tests) endif() tools-2021.2/src/libtools/000077500000000000000000000000001412152065700153615ustar00rootroot00000000000000tools-2021.2/src/libtools/CMakeLists.txt000066400000000000000000000047371412152065700201340ustar00rootroot00000000000000find_package(EXPAT REQUIRED) set_package_properties(EXPAT PROPERTIES TYPE REQUIRED PURPOSE "Used for XML parsing") file(GLOB VOTCA_SOURCES *.cc) add_library(votca_tools ${VOTCA_SOURCES} ${VOTCA_LINALG_SOURCES}) #CMAKE_CURRENT_BINARY_DIR for gitversion.h #PROJECT_BINARY_DIR/include for votca_tools_config.h target_include_directories(votca_tools PRIVATE ${CMAKE_CURRENT_BINARY_DIR} PUBLIC $ $ $ $) add_custom_target(gitversion COMMAND ${CMAKE_COMMAND} -DTOP_SOURCE_DIR="${CMAKE_SOURCE_DIR}" -DGIT_EXECUTABLE="${GIT_EXECUTABLE}" -P ${PROJECT_SOURCE_DIR}/CMakeModules/gitversion.cmake) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES gitversion.h) add_dependencies(votca_tools gitversion) set_target_properties(votca_tools PROPERTIES SOVERSION ${SOVERSION}) target_link_libraries(votca_tools PUBLIC Boost::boost Boost::program_options Eigen3::Eigen PRIVATE Boost::filesystem Boost::system EXPAT::EXPAT Threads::Threads ${MATH_LIBRARIES}) if(TARGET MKL::Shared) target_link_libraries(votca_tools PUBLIC MKL::Shared) install(FILES "${PROJECT_SOURCE_DIR}/CMakeModules/FindMKL.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VOTCA_TOOLS) endif() if(FFTW3_FOUND) # fftw3.h gets included in our public eigen.h through Eigen/FFT target_link_libraries(votca_tools PUBLIC FFTW3::fftw3) install(FILES "${PROJECT_SOURCE_DIR}/CMakeModules/FindFFTW3.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VOTCA_TOOLS) endif() install(TARGETS votca_tools EXPORT VOTCA_TOOLS_Targets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT VOTCA_TOOLS_Targets FILE VOTCA_TOOLS_Targets.cmake NAMESPACE VOTCA:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VOTCA_TOOLS) include(CMakePackageConfigHelpers) write_basic_package_version_file("VOTCA_TOOLSConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY ExactVersion) configure_file(VOTCA_TOOLSConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/VOTCA_TOOLSConfig.cmake @ONLY) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/VOTCA_TOOLSConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/VOTCA_TOOLSConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VOTCA_TOOLS) add_library(VOTCA::votca_tools ALIAS votca_tools) tools-2021.2/src/libtools/VOTCA_TOOLSConfig.cmake.in000066400000000000000000000013001412152065700217440ustar00rootroot00000000000000include(CMakeFindDependencyMacro) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) find_dependency(Eigen3 REQUIRED NO_MODULE) find_dependency(Boost 1.53.0 REQUIRED COMPONENTS program_options) if(@FFTW3_FOUND@) find_dependency(FFTW3 REQUIRED) endif() if(@MKL_FOUND@) enable_language(CXX) set(MKL_THREAD_LAYER "@MKL_THREAD_LAYER@" CACHE STRING "The thread layer to choose for MKL") find_dependency(MKL REQUIRED) endif() include("${CMAKE_CURRENT_LIST_DIR}/VOTCA_TOOLS_Targets.cmake") if(NOT TARGET VOTCA::votca_compare) add_executable(VOTCA::votca_compare IMPORTED) set_property(TARGET VOTCA::votca_compare PROPERTY IMPORTED_LOCATION "@CMAKE_INSTALL_FULL_BINDIR@/votca_compare") endif() tools-2021.2/src/libtools/akimaspline.cc000066400000000000000000000133111412152065700201640ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/akimaspline.h" #include "votca/tools/linalg.h" namespace votca { namespace tools { using namespace std; void AkimaSpline::Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) { if (x.size() != y.size()) { throw std::invalid_argument( "error in AkimaSpline::Interpolate : sizes of vectors x and y do not " "match"); } // Akima splines require at least 4 points if (x.size() < 4) { throw std::invalid_argument( "error in AkimaSpline::Interpolate : vectors x and y have to contain " "at least 4 points"); } const Index N = x.size(); // copy the grid points into f _r = x; // initialize vectors p1,p2,p3,p4 and t p0 = Eigen::VectorXd::Zero(N); p1 = Eigen::VectorXd::Zero(N); p2 = Eigen::VectorXd::Zero(N); p3 = Eigen::VectorXd::Zero(N); t = Eigen::VectorXd::Zero(N); double m1, m2, m3, m4; double temp, g0, g1, g2, x1, x2, y1, y2, x4, x5, y4, y5, m5; // boundary conditions // >> determine t(0), t(1) and t(N-2), t(N-1) switch (_boundaries) { case splineNormal: // Akima method: estimation of two more points on each side using a // degree two polyomial // resulting slopes t(0), t(1), t(N-2), t(N-1) are directly calculated // left side: t(0), t(1) temp = (x(1) - x(0)) / (x(2) - x(0)); temp = temp * temp; g0 = y(0); g1 = ((y(1) - y(0)) - temp * (y(2) - y(0))) / ((x(1) - x(0)) - temp * (x(2) - x(0))); g2 = ((y(2) - y(0)) - g1 * (x(2) - x(0))) / ((x(2) - x(0)) * (x(2) - x(0))); x1 = x(0) - (x(2) - x(0)); x2 = x(1) - (x(2) - x(0)); y1 = g0 + g1 * (x1 - x(0)) + g2 * (x1 - x(0)) * (x1 - x(0)); y2 = g0 + g1 * (x2 - x(0)) + g2 * (x2 - x(0)) * (x2 - x(0)); m1 = (y2 - y1) / (x2 - x1); m2 = (y(0) - y2) / (x(0) - x2); m3 = (y(1) - y(0)) / (x(1) - x(0)); m4 = (y(2) - y(1)) / (x(2) - x(1)); t(0) = getSlope(m1, m2, m3, m4); m5 = (y(3) - y(2)) / (x(3) - x(2)); t(1) = getSlope(m2, m3, m4, m5); // right side: t(N-2), t(N-1) temp = (x(N - 2) - x(N - 1)) / (x(N - 3) - x(N - 1)); temp = temp * temp; g0 = y(N - 1); g1 = ((y(N - 2) - y(N - 1)) - temp * (y(N - 3) - y(N - 1))) / ((x(N - 2) - x(N - 1)) - temp * (x(N - 3) - x(N - 1))); g2 = ((y(N - 3) - y(N - 1)) - g1 * (x(N - 3) - x(N - 1))) / ((x(N - 3) - x(N - 1)) * (x(N - 3) - x(N - 1))); x4 = x(N - 2) + (x(N - 1) - x(N - 3)); x5 = x(N - 1) + (x(N - 1) - x(N - 3)); y4 = g0 + g1 * (x4 - x(N - 1)) + g2 * (x4 - x(N - 1)) * (x4 - x(N - 1)); y5 = g0 + g1 * (x5 - x(N - 1)) + g2 * (x5 - x(N - 1)) * (x5 - x(N - 1)); m1 = (y(N - 3) - y(N - 4)) / (x(N - 3) - x(N - 4)); m2 = (y(N - 2) - y(N - 3)) / (x(N - 2) - x(N - 3)); m3 = (y(N - 1) - y(N - 2)) / (x(N - 1) - x(N - 2)); m4 = (y4 - y(N - 1)) / (x4 - x(N - 1)); m5 = (y5 - y4) / (x5 - x4); t(N - 2) = getSlope(m1, m2, m3, m4); t(N - 1) = getSlope(m2, m3, m4, m5); break; case splinePeriodic: // left: last two points determine the slopes t(0), t(1) m1 = (y(N - 1) - y(N - 2)) / (x(N - 1) - x(N - 2)); m2 = (y(0) - y(N - 1)) / (x(0) - x(N - 1)); m3 = (y(1) - y(0)) / (x(1) - x(0)); m4 = (y(2) - y(1)) / (x(2) - x(1)); m5 = (y(3) - y(2)) / (x(3) - x(2)); t(0) = getSlope(m1, m2, m3, m4); t(1) = getSlope(m2, m3, m4, m5); // right: first two points determine the slopes t(N-2), t(N-1) m1 = (y(N - 3) - y(N - 4)) / (x(N - 3) - x(N - 4)); m2 = (y(N - 2) - y(N - 3)) / (x(N - 2) - x(N - 3)); m3 = (y(N - 1) - y(N - 2)) / (x(N - 1) - x(N - 2)); m4 = (y(0) - y(N - 1)) / (x(0) - x(N - 1)); m5 = (y(1) - y(0)) / (x(1) - x(0)); t(N - 2) = getSlope(m1, m2, m3, m4); t(N - 1) = getSlope(m2, m3, m4, m5); break; case splineDerivativeZero: throw std::runtime_error( "erro in AkimaSpline::Interpolate: case splineDerivativeZero not " "implemented yet"); break; } // calculate t's for all inner points [2,N-3] for (Index i = 2; i < N - 2; i++) { m1 = (y(i - 1) - y(i - 2)) / (x(i - 1) - x(i - 2)); m2 = (y(i) - y(i - 1)) / (x(i) - x(i - 1)); m3 = (y(i + 1) - y(i)) / (x(i + 1) - x(i)); m4 = (y(i + 2) - y(i + 1)) / (x(i + 2) - x(i + 1)); t(i) = getSlope(m1, m2, m3, m4); } // calculate p0,p1,p2,p3 for all intervals 0..(N-2), where interval // [x(i),x(i+1)] shall have number i (this means that the last interval // has number N-2) for (Index i = 0; i < N - 1; i++) { p0(i) = y(i); p1(i) = t(i); p2(i) = (3.0 * (y(i + 1) - y(i)) / (x(i + 1) - x(i)) - 2.0 * t(i) - t(i + 1)) / (x(i + 1) - x(i)); p3(i) = (t(i) + t(i + 1) - 2.0 * (y(i + 1) - y(i)) / (x(i + 1) - x(i))) / ((x(i + 1) - x(i)) * (x(i + 1) - x(i))); } } void AkimaSpline::Fit(const Eigen::VectorXd &, const Eigen::VectorXd &) { throw std::runtime_error("Akima fit not implemented."); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/application.cc000066400000000000000000000200131412152065700201670ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Third party includes #include #include #include // Local VOTCA includes #include "votca/tools/application.h" #include "votca/tools/globals.h" #include "votca/tools/propertyiomanipulator.h" #include "votca/tools/version.h" // Local private VOTCA includes #include "votca_tools_config.h" namespace votca { namespace tools { using namespace std; Application::Application() : _op_desc("Allowed options"), _continue_execution(true) {} Application::~Application() = default; void Application::ShowHelpText(std::ostream &out) { out << "==================================================\n"; out << "======== VOTCA (http://www.votca.org) ========\n"; out << "==================================================\n\n"; out << "please submit bugs to " TOOLS_BUGREPORT "\n\n"; out << ProgramName(); if (VersionString() != "") { out << ", version " << VersionString(); } out << endl << "votca_tools, version " << ToolsVersionStr() << "\n\n"; HelpText(out); // remove Hidden group from the option list and print out << "\n\n" << VisibleOptions() << endl; } void Application::ShowManPage(std::ostream &out) { out << boost::format(globals::man::header) % ProgramName() % VersionString(); out << boost::format(globals::man::name) % ProgramName() % globals::url; out << boost::format(globals::man::synopsis) % ProgramName(); std::stringstream ss; HelpText(ss); out << boost::format(globals::man::description) % ss.str(); out << boost::format(globals::man::options); for (const auto &option : _op_desc.options()) { string format_name = option->format_name() + " " + option->format_parameter(); boost::replace_all(format_name, "-", "\\-"); out << boost::format(globals::man::option) % format_name % option->description(); } out << boost::format(globals::man::authors) % globals::email; out << boost::format(globals::man::copyright) % globals::url; } void Application::ShowTEXPage(std::ostream &out) { string program_name = ProgramName(); boost::replace_all(program_name, "_", "\\_"); out << boost::format(globals::tex::section) % program_name; out << boost::format(globals::tex::label) % ProgramName(); std::stringstream ss, os; HelpText(ss); out << boost::format(globals::tex::description) % ss.str(); for (const auto &option : _op_desc.options()) { string format_name = option->format_name() + " " + option->format_parameter(); boost::replace_all(format_name, "-", "{-}"); os << boost::format(globals::tex::option) % format_name % option->description(); } out << boost::format(globals::tex::options) % os.str(); } int Application::Exec(int argc, char **argv) { try { //_continue_execution = true; AddProgramOptions()("help,h", " display this help and exit"); AddProgramOptions()("verbose", " be loud and noisy"); AddProgramOptions()("verbose1", " be very loud and noisy"); AddProgramOptions()("verbose2,v", " be extremly loud and noisy"); AddProgramOptions("Hidden")("man", " output man-formatted manual pages"); AddProgramOptions("Hidden")("tex", " output tex-formatted manual pages"); Initialize(); // initialize program-specific parameters ParseCommandLine(argc, argv); // initialize general parameters & read input file Log::current_level = Log::error; if (_op_vm.count("verbose")) { Log::current_level = Log::warning; } if (_op_vm.count("verbose1")) { Log::current_level = Log::info; } if (_op_vm.count("verbose2")) { Log::current_level = Log::debug; } if (_op_vm.count("man")) { ShowManPage(cout); return 0; } if (_op_vm.count("tex")) { ShowTEXPage(cout); return 0; } if (_op_vm.count("help")) { ShowHelpText(cout); return 0; } if (!EvaluateOptions()) { ShowHelpText(cout); return -1; } if (_continue_execution) { Run(); } else { cout << "nothing to be done - stopping here\n"; } } catch (std::exception &error) { cerr << "an error occurred:\n" << error.what() << endl; return -1; } return 0; } boost::program_options::options_description_easy_init Application::AddProgramOptions(const string &group) { // if no group is given, add it to standard options if (group == "") { return _op_desc.add_options(); } // does group already exist, if yes, add it there std::map::iterator iter; iter = _op_groups.find(group); if (iter != _op_groups.end()) { return iter->second.add_options(); } // no group with given name was found -> create group _op_groups.insert( make_pair(group, boost::program_options::options_description(group))); return _op_groups[group].add_options(); } void Application::ParseCommandLine(int argc, char **argv) { namespace po = boost::program_options; // default options should be added to visible (the rest is handled via a map)) _visible_options.add(_op_desc); // add all categories to list of available options for (const auto &pair : _op_groups) { _op_desc.add(pair.second); if (pair.first != "Hidden") { _visible_options.add(pair.second); } } // parse the command line try { po::store(po::parse_command_line(argc, argv, _op_desc), _op_vm); po::notify(_op_vm); } catch (boost::program_options::error &err) { throw runtime_error(string("error parsing command line: ") + err.what()); } } void Application::CheckRequired(const string &option_name, const string &error_msg) { if (!_op_vm.count(option_name)) { ShowHelpText(cout); throw std::runtime_error("missing argument " + option_name + "\n" + error_msg); } } void Application::PrintDescription(std::ostream &out, const string &calculator_name, const string help_path, HelpType help_type) { boost::format _format("%|3t|%1% %|20t|%2% \n"); string help_string; boost::filesystem::path arg_path; Property options; // loading the documentation xml file from VOTCASHARE string xmlFile = (arg_path / tools::GetVotcaShare() / help_path / (boost::format("%1%.%2%") % calculator_name % "xml").str()) .string() .c_str(); try { options.LoadFromXML(xmlFile); Property &calculator_options = options.get("options." + calculator_name); Property::AttributeIterator atr_it = calculator_options.findAttribute("help"); if (atr_it != calculator_options.lastAttribute()) { help_string = (*atr_it).second; } else { if (Log::current_level > 0) { out << _format % calculator_name % "Undocumented"; } return; } switch (help_type) { default: break; case HelpShort: // short description of the calculator out << _format % calculator_name % help_string; break; case HelpLong: votca::tools::PropertyIOManipulator iom( votca::tools::PropertyIOManipulator::HLP, 2, ""); out << iom << options; break; } } catch (std::exception &) { if (Log::current_level > 0) { out << _format % calculator_name % "Undocumented"; } } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/calculator.cc000066400000000000000000000133411412152065700200230ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/calculator.h" #include "votca/tools/globals.h" #include "votca/tools/tokenizer.h" namespace votca { namespace tools { Property Calculator::LoadDefaults(const std::string package) { std::string calculator_name = Identify(); // add default values if specified in VOTCASHARE std::string votca_share = GetVotcaShare(); // load the xml description of the calculator (with defaults and test values) std::string xmlFile = votca_share + std::string("/") + package + std::string("/xml/") + calculator_name + std::string(".xml"); Property defaults_all; defaults_all.LoadFromXML(xmlFile); return defaults_all.get("options." + calculator_name); } void Calculator::UpdateWithUserOptions(Property &default_options, const Property &user_options) { // copy options from the object supplied by the Application std::string calculator_name = Identify(); Property options_id = user_options.get("options." + calculator_name); // if a value is given override default values OverwriteDefaultsWithUserInput(options_id, default_options); } void Calculator::OverwriteDefaultsWithUserInput(const Property &p, Property &defaults) { // Go through everything that is defined in user option for (const Property &prop : p) { if (prop.HasChildren()) { if (defaults.exists(prop.name())) { OverwriteDefaultsWithUserInput(prop, defaults.get(prop.name())); } else { Property &new_prop = defaults.add(prop.name(), ""); new_prop = prop; } } else if (defaults.exists(prop.name()) && (prop.value() != "")) { defaults.set(prop.name(), prop.value()); } else if (prop.value() != "") { defaults.add(prop.name(), prop.value()); } } } std::vector Calculator::GetPropertyChoices(const Property &p) { if (p.hasAttribute("choices")) { std::string att = p.getAttribute("choices"); std::size_t start_bracket = att.find('['); if (start_bracket != std::string::npos) { std::size_t end_bracket = att.find(']'); att = att.substr(start_bracket + 1, end_bracket - start_bracket - 1); } Tokenizer tok{att, " ,"}; return tok.ToVector(); } else { return {""}; } } void Calculator::RecursivelyCheckOptions(const Property &p) { for (const Property &prop : p) { if (prop.HasChildren()) { RecursivelyCheckOptions(prop); } else { std::vector choices = Calculator::GetPropertyChoices(prop); const std::string &head = choices.front(); if (head != "") { if (!Calculator::IsValidOption(prop, choices)) { std::ostringstream oss; oss << "\nThe input value for \"" << prop.name() << "\""; if (choices.size() == 1) { oss << " should be a \"" << head << "\""; } else { oss << " should be one of the following values: "; for (const std::string &c : choices) { oss << "\"" << c << "\"" << " "; } } oss << " But \"" << prop.value() << "\" cannot be converted into one.\n"; std::cout << oss.str(); throw std::runtime_error(oss.str()); } } } } } bool Calculator::IsValidOption(const Property &prop, const std::vector &choices) { const std::string &head = choices.front(); std::ostringstream oss; bool is_valid = true; if (head == "bool") { is_valid = Calculator::IsValidCast(prop); } else if (head == "float") { is_valid = Calculator::IsValidCast(prop); } else if (head == "float+") { is_valid = Calculator::IsValidCast(prop) && (prop.as() >= 0.0); } else if (head == "int") { is_valid = Calculator::IsValidCast(prop); } else if (head == "int+") { is_valid = Calculator::IsValidCast(prop) && (prop.as() >= 0); } else { std::string value = prop.as(); std::string att = prop.getAttribute("choices"); std::size_t start_bracket = att.find('['); if (start_bracket == std::string::npos) { // There is a single choice out of multiple default valid choices auto it = std::find(std::cbegin(choices), std::cend(choices), value); is_valid = (it != std::cend(choices)); } else { // there are multiple valid choices Tokenizer tok{value, " ,"}; for (const std::string &word : tok) { auto it = std::find(std::cbegin(choices), std::cend(choices), word); if (it == std::cend(choices)) { is_valid = false; break; } } } } return is_valid; } void Calculator::InjectDefaultsAsValues(Property &defaults) { for (Property &prop : defaults) { if (prop.HasChildren()) { InjectDefaultsAsValues(prop); } else { if (prop.hasAttribute("default") && (prop.value() == "")) { prop.set(".", prop.getAttribute("default")); } } } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/colors.cc000066400000000000000000000014311412152065700171700ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/colors.h" namespace votca { namespace tools { Color DEFAULT_COLORS; } } // namespace votca tools-2021.2/src/libtools/correlate.cc000066400000000000000000000025101412152065700176460ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/correlate.h" #include "votca/tools/eigen.h" namespace votca { namespace tools { void Correlate::CalcCorrelations(DataCollection::selection &data) { Index N = Index(data[0].size()); double Nd = (double)N; Eigen::Map m0(data[0].data(), N); double xm = m0.sum(); xm /= Nd; double xsq = m0.abs2().sum(); for (Index v = 1; v < data.size(); v++) { Eigen::Map m_v(data[v].data(), N); double ym = m_v.sum(); double ysq = m_v.abs2().sum(); double p = (m_v * m0).sum(); ym /= Nd; double norm = std::sqrt((xsq - Nd * xm * xm) * (ysq - Nd * ym * ym)); p = (p - Nd * xm * ym) / norm; _corr.push_back(p); } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/crosscorrelate.cc000066400000000000000000000023411412152065700207220ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/crosscorrelate.h" namespace votca { namespace tools { void CrossCorrelate::AutoCorrelate(DataCollection::selection& data) { Index N = data[0].size(); Eigen::Map input(data[0].data(), N); Eigen::FFT fft; Eigen::VectorXcd frequency = fft.fwd(input); Eigen::VectorXcd magnitude = frequency.cwiseAbs2(); _corrfunc.resize(N); Eigen::Map corr_map(_corrfunc.data(), N); corr_map = fft.inv(magnitude); double d = corr_map(0); corr_map.array() /= d; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/cubicspline.cc000066400000000000000000000135751412152065700202030ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include // Local VOTCA includes #include "votca/tools/cubicspline.h" #include "votca/tools/linalg.h" namespace votca { namespace tools { using namespace std; void CubicSpline::Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) { if (x.size() != y.size()) { throw std::invalid_argument( "error in CubicSpline::Interpolate : sizes of vectors x and y do not " "match"); } if (x.size() < 3) { throw std::invalid_argument( "error in CubicSpline::Interpolate : vectors x and y have to contain " "at least 3 points"); } const Index N = x.size(); // copy the grid points into f _r = x; _f = y; Eigen::VectorXd temp = Eigen::VectorXd::Zero(N); Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, N); for (Index i = 0; i < N - 2; ++i) { temp(i + 1) = -(A_prime_l(i) * _f(i) + (B_prime_l(i) - A_prime_r(i)) * _f(i + 1) - B_prime_r(i) * _f(i + 2)); A(i + 1, i) = C_prime_l(i); A(i + 1, i + 1) = D_prime_l(i) - C_prime_r(i); A(i + 1, i + 2) = -D_prime_r(i); } switch (_boundaries) { case splineNormal: A(0, 0) = 1; A(N - 1, N - 1) = 1; break; case splinePeriodic: A(0, 0) = 1; A(0, N - 1) = -1; A(N - 1, 0) = 1; A(N - 1, N - 1) = -1; break; case splineDerivativeZero: throw std::runtime_error( "erro in CubicSpline::Interpolate: case splineDerivativeZero not " "implemented yet"); break; } Eigen::HouseholderQR QR(A); _f2 = QR.solve(temp); } void CubicSpline::Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) { if (x.size() != y.size()) { throw std::invalid_argument( "error in CubicSpline::Fit : sizes of vectors x and y do not match"); } const Index N = x.size(); const Index ngrid = _r.size(); // construct the equation // A*u = b // where u = { {f[i]}, {f''[i]} } // and b[i] = y[i] for 0<=i=N (for smoothing condition) // A[i,j] contains the data fitting + the spline smoothing conditions Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, 2 * ngrid); Eigen::MatrixXd B = Eigen::MatrixXd::Zero( ngrid, 2 * ngrid); // Matrix with smoothing conditions // Construct smoothing matrix AddBCToFitMatrix(B, 0); // construct the matrix to fit the points and the vector b AddToFitMatrix(A, x, 0); // now do a constrained qr solve Eigen::VectorXd sol = linalg_constrained_qrsolve(A, y, B); // check vector "sol" for nan's for (Index i = 0; i < 2 * ngrid; i++) { if ((std::isinf(sol(i))) || (std::isnan(sol(i)))) { throw std::runtime_error( "error in CubicSpline::Fit : value nan occurred due to wrong fitgrid " "boundaries"); } } _f = sol.segment(0, ngrid); _f2 = sol.segment(ngrid, ngrid); } double CubicSpline::Calculate(double r) { Index interval = getInterval(r); return A(r) * _f[interval] + B(r) * _f[interval + 1] + C(r) * _f2[interval] + D(r) * _f2[interval + 1]; } double CubicSpline::CalculateDerivative(double r) { Index interval = getInterval(r); return Aprime(r) * _f[interval] + Bprime(r) * _f[interval + 1] + Cprime(r) * _f2[interval] + Dprime(r) * _f2[interval + 1]; } double CubicSpline::A(double r) { return (1.0 - (r - _r[getInterval(r)]) / (_r[getInterval(r) + 1] - _r[getInterval(r)])); } double CubicSpline::Aprime(double r) { return -1.0 / (_r[getInterval(r) + 1] - _r[getInterval(r)]); } double CubicSpline::B(double r) { return (r - _r[getInterval(r)]) / (_r[getInterval(r) + 1] - _r[getInterval(r)]); } double CubicSpline::Bprime(double r) { return 1.0 / (_r[getInterval(r) + 1] - _r[getInterval(r)]); } double CubicSpline::C(double r) { double xxi = r - _r[getInterval(r)]; double h = _r[getInterval(r) + 1] - _r[getInterval(r)]; return (0.5 * xxi * xxi - (1.0 / 6.0) * xxi * xxi * xxi / h - (1.0 / 3.0) * xxi * h); } double CubicSpline::Cprime(double r) { double xxi = r - _r[getInterval(r)]; double h = _r[getInterval(r) + 1] - _r[getInterval(r)]; return (xxi - 0.5 * xxi * xxi / h - h / 3); } double CubicSpline::D(double r) { double xxi = r - _r[getInterval(r)]; double h = _r[getInterval(r) + 1] - _r[getInterval(r)]; return ((1.0 / 6.0) * xxi * xxi * xxi / h - (1.0 / 6.0) * xxi * h); } double CubicSpline::Dprime(double r) { double xxi = r - _r[getInterval(r)]; double h = _r[getInterval(r) + 1] - _r[getInterval(r)]; return (0.5 * xxi * xxi / h - (1.0 / 6.0) * h); } double CubicSpline::A_prime_l(Index i) { return -1.0 / (_r[i + 1] - _r[i]); } double CubicSpline::B_prime_l(Index i) { return 1.0 / (_r[i + 1] - _r[i]); } double CubicSpline::C_prime_l(Index i) { return (1.0 / 6.0) * (_r[i + 1] - _r[i]); } double CubicSpline::D_prime_l(Index i) { return (1.0 / 3.0) * (_r[i + 1] - _r[i]); } double CubicSpline::A_prime_r(Index i) { return -1.0 / (_r[i + 2] - _r[i + 1]); } double CubicSpline::B_prime_r(Index i) { return 1.0 / (_r[i + 2] - _r[i + 1]); } double CubicSpline::C_prime_r(Index i) { return -(1.0 / 3.0) * (_r[i + 2] - _r[i + 1]); } double CubicSpline::D_prime_r(Index i) { return -(1.0 / 6.0) * (_r[i + 2] - _r[i + 1]); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/datacollection.cc000066400000000000000000000026441412152065700206630ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/datacollection.h" namespace votca { namespace tools { std::ostream& operator<<(std::ostream& out, const DataCollection::selection& sel) { if (sel.empty()) { out << "-- empty selection --" << std::endl; return out; } std::stringstream s; for (size_t i = 0;; ++i) { s.clear(); s.str(""); s.setf(std::ios::scientific); Index written = 0; for (auto& array : sel) { if (i >= array->size()) { s << " -"; continue; } written++; s << " " << (*array)[i]; } if (written == 0) { return out; } out << i << s.str() << std::endl; } return out; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/edge.cc000066400000000000000000000045201412152065700165750ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Local VOTCA includes #include "votca/tools/edge.h" namespace votca { namespace tools { using namespace std; Edge::Edge(Index ID1, Index ID2) { vertices_ = vector{min({ID1, ID2}), max({ID1, ID2})}; } Index Edge::getOtherEndPoint(Index ver) const { if (ver == vertices_.front()) { return vertices_.back(); } else { return vertices_.front(); } } bool Edge::contains(Index ID) const { return (vertices_.front() == ID || vertices_.back() == ID); } bool Edge::operator==(const Edge& ed) const { if (this->vertices_.front() == ed.vertices_.front() && this->vertices_.back() == ed.vertices_.back()) { return true; } if (this->vertices_.back() == ed.vertices_.front() && this->vertices_.front() == ed.vertices_.back()) { return true; } return false; } bool Edge::operator!=(const Edge& ed) const { return !(*this == ed); } bool Edge::operator<(const Edge& ed) const { if (this->vertices_.front() < ed.vertices_.front()) { return true; } if (this->vertices_.front() > ed.vertices_.front()) { return false; } if (this->vertices_.back() < ed.vertices_.back()) { return true; } return false; } bool Edge::operator<=(const Edge& ed) const { return (*this < ed || *this == ed); } bool Edge::operator>(const Edge& ed) const { return !(*this <= ed); } bool Edge::operator>=(const Edge& ed) const { return !(*this < ed); } ostream& operator<<(ostream& os, const Edge& ed) { os << "Vertices" << endl; os << ed.vertices_.front() << " " << ed.vertices_.back() << endl; return os; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/edgecontainer.cc000066400000000000000000000127261412152065700205070ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include #include #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/edgecontainer.h" namespace votca { namespace tools { using namespace std; EdgeContainer::EdgeContainer(Edge edge) { addEdge(edge); } EdgeContainer::EdgeContainer(vector edges) { for (Edge& edge : edges) { addEdge(edge); } } Index EdgeContainer::getMaxDegree(void) const { Index max = 0; for (const auto& vertex_and_neigh_and_count : adj_list_) { Index degree = getDegree(vertex_and_neigh_and_count.first); if (degree > max) { max = degree; } } return max; } Index EdgeContainer::getDegree(const Index vertex) const { if (!adj_list_.count(vertex)) { throw invalid_argument("vertex is not defined"); } Index degree_count = 0; if (adj_list_.at(vertex).size() == 0) { return degree_count; } for (const pair& neighbor_and_count : adj_list_.at(vertex)) { if (neighbor_and_count.first == vertex) { degree_count += neighbor_and_count.second * 2; } else { degree_count += neighbor_and_count.second; } } return degree_count; } vector EdgeContainer::getVerticesDegree(Index degree) const { vector vertices; for (const auto& vertex_and_neigh_and_count : adj_list_) { Index degree_count = getDegree(vertex_and_neigh_and_count.first); if (degree_count == degree) { vertices.push_back(vertex_and_neigh_and_count.first); } } return vertices; } bool EdgeContainer::vertexExistWithDegree(Index degree) const { for (const auto& vertex_and_neigh_and_count : adj_list_) { Index degree_count = getDegree(vertex_and_neigh_and_count.first); if (degree_count == degree) { return true; } } return false; } bool EdgeContainer::edgeExist(const Edge& edge) const { if (adj_list_.count(edge.getEndPoint1())) { if (adj_list_.at(edge.getEndPoint1()).count(edge.getEndPoint2())) { return true; } } if (adj_list_.count(edge.getEndPoint2())) { if (adj_list_.at(edge.getEndPoint2()).count(edge.getEndPoint1())) { return true; } } return false; } bool EdgeContainer::vertexExist(const Index vertex) const { return adj_list_.count(vertex); } void EdgeContainer::addEdge(Edge edge) { Index point1 = edge.getEndPoint1(); Index point2 = edge.getEndPoint2(); if (adj_list_[point1].count(point2)) { ++adj_list_[point1][point2]; } else { adj_list_[point1][point2] = 1; } // Do not add the same edge a second time if the points are the same if (point1 != point2) { if (adj_list_[point2].count(point1)) { ++adj_list_[point2][point1]; } else { adj_list_[point2][point1] = 1; } } return; } void EdgeContainer::addVertex(Index vertex) { assert(adj_list_.count(vertex) == 0 && "Cannot add vertex already exists"); unordered_map empty_temp; adj_list_[vertex] = empty_temp; } vector EdgeContainer::getVertices() const { vector vertices; for (const pair>& vertex_and_neigh_and_count : adj_list_) { vertices.push_back(vertex_and_neigh_and_count.first); } return vertices; } vector EdgeContainer::getNeighVertices(Index vertex) const { vector neigh_verts; if (adj_list_.count(vertex)) { for (const pair& neigh_and_count : adj_list_.at(vertex)) { neigh_verts.push_back(neigh_and_count.first); } } return neigh_verts; } vector EdgeContainer::getNeighEdges(Index vertex) const { vector neigh_edges; if (adj_list_.count(vertex)) { for (const pair& neigh_and_count : adj_list_.at(vertex)) { for (Index count = 0; count < adj_list_.at(vertex).at(neigh_and_count.first); ++count) { neigh_edges.push_back(Edge(vertex, neigh_and_count.first)); } } } return neigh_edges; } vector EdgeContainer::getEdges() const { unordered_map extra_edge_count; for (const auto& vertex_and_neigh_and_count : adj_list_) { for (const pair& neigh_and_count : vertex_and_neigh_and_count.second) { extra_edge_count[Edge(vertex_and_neigh_and_count.first, neigh_and_count.first)] = neigh_and_count.second; } } vector edges; for (pair& edge_count : extra_edge_count) { for (Index count = 0; count < edge_count.second; ++count) { edges.push_back(edge_count.first); } } return edges; } ostream& operator<<(ostream& os, const EdgeContainer edgecontainer) { auto edges = edgecontainer.getEdges(); for (auto edge : edges) { os << edge << endl; } return os; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/eigenio_matrixmarket.cc000066400000000000000000000064621412152065700221070ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/eigen.h" #include "votca/tools/tokenizer.h" #include "votca/tools/types.h" namespace votca { namespace tools { namespace EigenIO_MatrixMarket { Eigen::VectorXd ReadVector(const std::string& filename) { Eigen::VectorXd output; bool success = Eigen::loadMarketVector(output, filename); if (!success) { throw std::runtime_error("Loading Vector from " + filename + " failed"); } return output; } void WriteVector(const std::string& filename, const Eigen::VectorXd& output) { bool success = Eigen::saveMarketVector(output, filename); if (!success) { throw std::runtime_error("Writing Vector to " + filename + " failed"); } } void WriteMatrix(const std::string& filename, const Eigen::MatrixXd& output) { std::ofstream ofs; ofs.open(filename, std::ofstream::out); if (!ofs.is_open()) { throw std::runtime_error("Could not create " + filename); } ofs << "%%MatrixMarket matrix array real general\n"; ofs << output.rows() << " " << output.cols() << "\n"; const Eigen::Map temp(output.data(), output.size()); ofs << temp; ofs.close(); } Eigen::MatrixXd ReadMatrix(const std::string& filename) { int sym = 0; bool iscomplex = false; // has to be false because getMarketHeader only sets // it to true but not to false bool isvector = false; bool success = Eigen::getMarketHeader(filename, sym, iscomplex, isvector); if (!success) { throw std::runtime_error("Could not read " + filename); } if (sym != 0) { throw std::runtime_error("Only supports reading in general matrices"); } if (iscomplex) { throw std::runtime_error( "Only supports reading in matrices with real numbers"); } if (!isvector) { throw std::runtime_error( "Use the eigen method `loadMarket` for sparse data"); } std::ifstream in(filename, std::ios::in); if (!in) { throw std::runtime_error("Could not open " + filename); } std::string line; Index cols = 0; Index rows = 0; do { // Skip comments std::getline(in, line); assert(in.good()); } while (line[0] == '%'); std::istringstream newline(line); newline >> rows >> cols; assert(rows > 0 && cols > 0); Index i = 0; Index n = rows * cols; std::vector entries; entries.reserve(n); double value; while (std::getline(in, line) && (i < n)) { std::istringstream newline2(line); newline2 >> value; entries.push_back(value); i++; } in.close(); return Eigen::Map(entries.data(), rows, cols); } } // namespace EigenIO_MatrixMarket } // namespace tools } // namespace votca tools-2021.2/src/libtools/elements.cc000066400000000000000000000504201412152065700175050ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Third party includes #include // Local VOTCA includes #include "votca/tools/elements.h" namespace votca { namespace tools { /************************* * Public Facing Methods * *************************/ bool Elements::isElement(std::string name) { return isEleShort(name) || isEleFull(name); } Index Elements::getNucCrg(std::string name) { if (!this->_filled_NucCrg) { this->FillNucCrg(); _filled_NucCrg = true; } try { return _NucCrg.at(name); } catch (const std::out_of_range& oor) { throw std::runtime_error("Nuclearcharge of element " + name + " not found."); } } Index Elements::getEleNum(std::string name) { if (!this->_filled_EleNum) { this->FillEleNum(); _filled_EleNum = true; } try { return _EleNum.at(name); } catch (const std::out_of_range& oor) { throw std::runtime_error("Elementnumber of element " + name + " not found."); } } double Elements::getMass(std::string name) { if (!this->_filled_Mass) { this->FillMass(); _filled_Mass = true; } try { return _Mass.at(name); } catch (const std::out_of_range& oor) { throw std::runtime_error("Mass of element " + name + " not found."); } } double Elements::getVdWChelpG(std::string name) { if (!this->_filled_VdWChelpG) { this->FillVdWChelpG(); _filled_VdWChelpG = true; } if (_VdWChelpG.count(name) == 0) { throw std::runtime_error("Element not found in VdWChelpG map " + name); } return _VdWChelpG.at(name); } double Elements::getVdWMK(std::string name) { if (!this->_filled_VdWMK) { this->FillVdWMK(); _filled_VdWMK = true; } if (_VdWMK.count(name) == 0) { throw std::runtime_error("Element not found in VdWMP map " + name); } return _VdWMK.at(name); } double Elements::getPolarizability(std::string name) { if (!this->_filled_ElPolarizability) { this->FillPolarizability(); _filled_ElPolarizability = true; } if (_ElPolarizability.count(name) == 0) { throw std::runtime_error("Element not found in ElPolarizability map " + name); } return _ElPolarizability.at(name); } double Elements::getCovRad(std::string name, std::string unit) { // TODO - This should be replaced with an object, an object that should // auto recognise the units and return it in a standard type if (!this->_filled_CovRad) { this->FillCovRad(); _filled_CovRad = true; } if (!unit.compare("bohr")) { return conv::ang2bohr * _CovRad.find(name)->second; } if (!unit.compare("nm")) { return conv::ang2nm * _CovRad.find(name)->second; } if (!unit.compare("ang")) { return _CovRad.find(name)->second; } throw std::runtime_error("Must specify appropriate units " + unit + " is not known"); } std::string Elements::getEleName(Index elenum) { if (!this->_filled_EleName) { this->FillEleName(); _filled_EleName = true; } return _EleName.at(elenum); } std::string Elements::getEleFull(std::string eleshort) { if (!this->_filled_EleFull) { this->FillEleFull(); _filled_EleFull = true; } return _EleFull.at(eleshort); } std::string Elements::getEleShort(std::string elefull) { if (!this->_filled_EleShort) { this->FillEleShort(); _filled_EleShort = true; } return _EleShort.at(elefull); } bool Elements::isEleFull(std::string fullname) { if (!this->_filled_EleShort) { this->FillEleShort(); _filled_EleShort = true; } std::string name_upper = boost::to_upper_copy(fullname); return _EleShort.count(name_upper); } bool Elements::isEleShort(std::string shortname) { if (!this->_filled_EleFull) { this->FillEleFull(); _filled_EleFull = true; } return _EleFull.count(shortname); } bool Elements::isMassAssociatedWithElement(double mass, double tolerance) { auto closestMatch = findShortNameOfElementClosestInMass_(mass); if (closestMatch.second > tolerance) { return false; } return true; } std::string Elements::getEleShortClosestInMass(double mass, double tolerance) { auto closestMatch = findShortNameOfElementClosestInMass_(mass); if (closestMatch.second > tolerance) { throw std::runtime_error( "In attempt to determine if mass is associated " " with an element the mass exceeds tolerance of a possible match"); } return closestMatch.first; } /******************* * Private Methods * *******************/ std::pair Elements::findShortNameOfElementClosestInMass_( double mass) { if (!this->_filled_Mass) { this->FillMass(); _filled_Mass = true; } std::string eleShort = "H"; double diff = std::fabs(mass - _Mass[eleShort]); for (const auto& ele_pr : _Mass) { if (std::fabs(ele_pr.second - mass) < diff) { eleShort = ele_pr.first; diff = std::fabs(ele_pr.second - mass); } } return std::pair(eleShort, diff); } void Elements::FillMass() { // masses of atoms _Mass["H"] = 1.00794; _Mass["He"] = 4.002602; _Mass["Li"] = 6.941; _Mass["Be"] = 9.012182; _Mass["B"] = 10.811; _Mass["C"] = 12.0107; _Mass["N"] = 14.00674; _Mass["O"] = 15.9994; _Mass["F"] = 18.9984032; _Mass["Ne"] = 20.1797; _Mass["Na"] = 22.989770; _Mass["Mg"] = 24.3050; _Mass["Al"] = 26.981538; _Mass["Si"] = 28.0855; _Mass["P"] = 30.973761; _Mass["S"] = 32.066; _Mass["Cl"] = 35.4527; _Mass["Ar"] = 39.948; _Mass["K"] = 39.098; _Mass["Ca"] = 40.078; _Mass["Sc"] = 44.956; _Mass["Ti"] = 47.867; _Mass["V"] = 50.942; _Mass["Cr"] = 51.996; _Mass["Mn"] = 54.938; _Mass["Fe"] = 55.845; _Mass["Co"] = 58.933; _Mass["Ni"] = 58.693; _Mass["Cu"] = 63.546; _Mass["Zn"] = 65.38; _Mass["Ga"] = 69.723; _Mass["Ge"] = 72.630; _Mass["As"] = 74.922; _Mass["Se"] = 78.971; _Mass["Br"] = 79.90; _Mass["Kr"] = 83.798; _Mass["Rb"] = 85.468; _Mass["Sr"] = 87.62; _Mass["Y"] = 88.906; _Mass["Zr"] = 91.224; _Mass["Nb"] = 92.906; _Mass["Mo"] = 95.95; _Mass["Tc"] = 98.0; _Mass["Ru"] = 101.07; _Mass["Rh"] = 102.91; _Mass["Pd"] = 106.42; _Mass["Ag"] = 107.8682; _Mass["Cd"] = 112.41; _Mass["In"] = 114.82; _Mass["Sn"] = 118.71; _Mass["Sb"] = 121.76; _Mass["Te"] = 127.60; _Mass["I"] = 126.90; _Mass["Xe"] = 131.29; _Mass["Cs"] = 132.91; _Mass["Ba"] = 137.33; _Mass["Hf"] = 178.49; _Mass["Ta"] = 180.49; _Mass["W"] = 183.84; _Mass["Re"] = 186.21; _Mass["Os"] = 190.23; _Mass["Ir"] = 192.22; _Mass["Pt"] = 195.08; _Mass["Au"] = 196.97; _Mass["Hg"] = 200.59; _Mass["Tl"] = 204.38; _Mass["Pb"] = 207.2; _Mass["Bi"] = 208.98; _Mass["Po"] = 209; _Mass["At"] = 210; _Mass["Rn"] = 222; } void Elements::FillVdWChelpG() { // VdW radii in Angstrom as used in CHELPG paper [Journal of Computational // Chemistry 11, 361, 1990]and Gaussian _VdWChelpG["H"] = 1.45; _VdWChelpG["He"] = 1.45; _VdWChelpG["Li"] = 1.5; _VdWChelpG["Be"] = 1.5; _VdWChelpG["B"] = 1.5; _VdWChelpG["C"] = 1.5; _VdWChelpG["N"] = 1.7; _VdWChelpG["O"] = 1.7; _VdWChelpG["F"] = 1.7; _VdWChelpG["Ne"] = 1.7; _VdWChelpG["Na"] = 2.0; _VdWChelpG["Mg"] = 2.0; _VdWChelpG["Al"] = 2.0; _VdWChelpG["Si"] = 2.0; _VdWChelpG["P"] = 2.0; _VdWChelpG["S"] = 2.0; _VdWChelpG["Cl"] = 2.0; _VdWChelpG["Ar"] = 2.0; _VdWChelpG["Ag"] = 1.7; } void Elements::FillNucCrg() { // Nuclear Charges _NucCrg["H"] = 1.00; _NucCrg["He"] = 2.00; _NucCrg["Li"] = 3.00; _NucCrg["Be"] = 4.00; _NucCrg["B"] = 5.00; _NucCrg["C"] = 6.00; _NucCrg["N"] = 7.00; _NucCrg["O"] = 8.00; _NucCrg["F"] = 9.00; _NucCrg["Ne"] = 10.00; _NucCrg["Na"] = 11.00; _NucCrg["Mg"] = 12.00; _NucCrg["Al"] = 13.00; _NucCrg["Si"] = 14.00; _NucCrg["P"] = 15.00; _NucCrg["S"] = 16.00; _NucCrg["Cl"] = 17.00; _NucCrg["Ar"] = 18.00; _NucCrg["K"] = 19.00; _NucCrg["Ca"] = 20.00; _NucCrg["Sc"] = 21.00; _NucCrg["Ti"] = 22.00; _NucCrg["V"] = 23.00; _NucCrg["Cr"] = 24.00; _NucCrg["Mn"] = 25.00; _NucCrg["Fe"] = 26.00; _NucCrg["Co"] = 27.00; _NucCrg["Ni"] = 28.00; _NucCrg["Cu"] = 29.00; _NucCrg["Zn"] = 30.00; _NucCrg["Ga"] = 31.00; _NucCrg["Ge"] = 32.00; _NucCrg["As"] = 33.00; _NucCrg["Se"] = 34.00; _NucCrg["Br"] = 35.00; _NucCrg["Kr"] = 36.00; _NucCrg["Rb"] = 37.00; _NucCrg["Sr"] = 38.00; _NucCrg["Y"] = 39.00; _NucCrg["Zr"] = 40.00; _NucCrg["Nb"] = 41.00; _NucCrg["Mo"] = 42.00; _NucCrg["Tc"] = 43.00; _NucCrg["Ru"] = 44.00; _NucCrg["Rh"] = 45.00; _NucCrg["Pd"] = 46.00; _NucCrg["Ag"] = 47.00; _NucCrg["Cd"] = 48.00; _NucCrg["In"] = 49.00; _NucCrg["Sn"] = 50.00; _NucCrg["Sb"] = 51.00; _NucCrg["Te"] = 52.00; _NucCrg["I"] = 53.00; _NucCrg["Xe"] = 54.00; _NucCrg["Cs"] = 55.00; _NucCrg["Ba"] = 56.00; _NucCrg["Hf"] = 72.00; _NucCrg["Ta"] = 73.00; _NucCrg["W"] = 74.00; _NucCrg["Re"] = 75.00; _NucCrg["Os"] = 76.00; _NucCrg["Ir"] = 77.00; _NucCrg["Pt"] = 78.00; _NucCrg["Au"] = 79.00; _NucCrg["Hg"] = 80.00; _NucCrg["Tl"] = 81.00; _NucCrg["Pb"] = 82.00; _NucCrg["Bi"] = 83.00; _NucCrg["Po"] = 84.00; _NucCrg["At"] = 85.00; _NucCrg["Rn"] = 86.00; } void Elements::FillCovRad() { // Covalent Radii, used by BulkESP to break system into molecules // data from http://pubs.rsc.org/en/content/articlehtml/2008/dt/b801115j // values in [Angstroms] _CovRad["H"] = 0.31; _CovRad["He"] = 0.28; _CovRad["Li"] = 1.28; _CovRad["Be"] = 0.96; _CovRad["B"] = 0.84; // This is for sp3 _CovRad["C"] = 0.76; _CovRad["N"] = 0.71; _CovRad["O"] = 0.66; _CovRad["F"] = 0.57; _CovRad["Ne"] = 0.58; _CovRad["Na"] = 1.66; _CovRad["Mg"] = 1.41; _CovRad["Al"] = 1.21; _CovRad["Si"] = 1.11; _CovRad["P"] = 1.07; _CovRad["S"] = 1.05; _CovRad["Cl"] = 1.02; _CovRad["Ar"] = 1.06; _CovRad["K"] = 2.03; _CovRad["Ca"] = 1.76; _CovRad["Sc"] = 1.70; _CovRad["Ti"] = 1.60; _CovRad["V"] = 1.53; _CovRad["Cr"] = 1.39; _CovRad["Mn"] = 1.61; _CovRad["Fe"] = 1.52; _CovRad["Co"] = 1.50; _CovRad["Ni"] = 1.24; _CovRad["Cu"] = 1.32; _CovRad["Zn"] = 1.22; _CovRad["Ga"] = 1.22; _CovRad["Ge"] = 1.20; _CovRad["As"] = 1.19; _CovRad["Se"] = 1.20; _CovRad["Br"] = 1.20; _CovRad["Kr"] = 1.16; _CovRad["Rb"] = 2.20; _CovRad["Sr"] = 1.95; _CovRad["Y"] = 1.90; _CovRad["Zr"] = 1.75; _CovRad["Nb"] = 1.64; _CovRad["Mo"] = 1.54; _CovRad["Tc"] = 1.47; _CovRad["Ru"] = 1.46; _CovRad["Rh"] = 1.42; _CovRad["Pd"] = 1.39; _CovRad["Ag"] = 1.45; _CovRad["Cd"] = 1.44; _CovRad["In"] = 1.42; _CovRad["Sn"] = 1.39; _CovRad["Sb"] = 1.39; _CovRad["Te"] = 1.38; _CovRad["I"] = 1.39; _CovRad["Xe"] = 1.40; _CovRad["Cs"] = 2.44; _CovRad["Ba"] = 2.15; _CovRad["Hf"] = 1.75; _CovRad["Ta"] = 1.70; _CovRad["W"] = 1.62; _CovRad["Re"] = 1.51; _CovRad["Os"] = 1.44; _CovRad["Ir"] = 1.41; _CovRad["Pt"] = 1.36; _CovRad["Au"] = 1.36; _CovRad["Hg"] = 1.32; _CovRad["Tl"] = 1.45; _CovRad["Pb"] = 1.46; _CovRad["Bi"] = 1.48; _CovRad["Po"] = 1.40; _CovRad["At"] = 1.50; _CovRad["Rn"] = 1.50; } void Elements::FillEleNum() { // Nuclear Charges _EleNum["H"] = 1; _EleNum["He"] = 2; _EleNum["Li"] = 3; _EleNum["Be"] = 4; _EleNum["B"] = 5; _EleNum["C"] = 6; _EleNum["N"] = 7; _EleNum["O"] = 8; _EleNum["F"] = 9; _EleNum["Ne"] = 10; _EleNum["Na"] = 11; _EleNum["Mg"] = 12; _EleNum["Al"] = 13; _EleNum["Si"] = 14; _EleNum["P"] = 15; _EleNum["S"] = 16; _EleNum["Cl"] = 17; _EleNum["Ar"] = 18; _EleNum["K"] = 19; _EleNum["Ca"] = 20; _EleNum["Sc"] = 21; _EleNum["Ti"] = 22; _EleNum["V"] = 23; _EleNum["Cr"] = 24; _EleNum["Mn"] = 25; _EleNum["Fe"] = 26; _EleNum["Co"] = 27; _EleNum["Ni"] = 28; _EleNum["Cu"] = 29; _EleNum["Zn"] = 30; _EleNum["Ga"] = 31; _EleNum["Ge"] = 32; _EleNum["As"] = 33; _EleNum["Se"] = 34; _EleNum["Br"] = 35; _EleNum["Kr"] = 36; _EleNum["Rb"] = 37; _EleNum["Sr"] = 38; _EleNum["Y"] = 39; _EleNum["Zr"] = 40; _EleNum["Nb"] = 41; _EleNum["Mo"] = 42; _EleNum["Tc"] = 43; _EleNum["Ru"] = 44; _EleNum["Rh"] = 45; _EleNum["Pd"] = 46; _EleNum["Ag"] = 47; _EleNum["Cd"] = 48; _EleNum["In"] = 49; _EleNum["Sn"] = 50; _EleNum["Sb"] = 51; _EleNum["Te"] = 52; _EleNum["I"] = 53; _EleNum["Xe"] = 54; _EleNum["Cs"] = 55; _EleNum["Ba"] = 56; _EleNum["Hf"] = 72; _EleNum["Ta"] = 73; _EleNum["W"] = 74; _EleNum["Re"] = 75; _EleNum["Os"] = 76; _EleNum["Ir"] = 77; _EleNum["Pt"] = 78; _EleNum["Au"] = 79; _EleNum["Hg"] = 80; _EleNum["Tl"] = 81; _EleNum["Pb"] = 82; _EleNum["Bi"] = 83; _EleNum["Po"] = 84; _EleNum["At"] = 85; _EleNum["Rn"] = 86; } void Elements::FillEleName() { // Nuclear Charges _EleName[1] = "H"; _EleName[2] = "He"; _EleName[3] = "Li"; _EleName[4] = "Be"; _EleName[5] = "B"; _EleName[6] = "C"; _EleName[7] = "N"; _EleName[8] = "O"; _EleName[9] = "F"; _EleName[10] = "Ne"; _EleName[11] = "Na"; _EleName[12] = "Mg"; _EleName[13] = "Al"; _EleName[14] = "Si"; _EleName[15] = "P"; _EleName[16] = "S"; _EleName[17] = "Cl"; _EleName[18] = "Ar"; _EleName[19] = "K"; _EleName[20] = "Ca"; _EleName[21] = "Sc"; _EleName[22] = "Ti"; _EleName[23] = "V"; _EleName[24] = "Cr"; _EleName[25] = "Mn"; _EleName[26] = "Fe"; _EleName[27] = "Co"; _EleName[28] = "Ni"; _EleName[29] = "Cu"; _EleName[30] = "Zn"; _EleName[31] = "Ga"; _EleName[32] = "Ge"; _EleName[33] = "As"; _EleName[34] = "Se"; _EleName[35] = "Br"; _EleName[36] = "Kr"; _EleName[37] = "Rb"; _EleName[38] = "Sr"; _EleName[39] = "Y"; _EleName[40] = "Zr"; _EleName[41] = "Nb"; _EleName[42] = "Mo"; _EleName[43] = "Tc"; _EleName[44] = "Ru"; _EleName[45] = "Rh"; _EleName[46] = "Pd"; _EleName[47] = "Ag"; _EleName[48] = "Cd"; _EleName[49] = "In"; _EleName[50] = "Sn"; _EleName[51] = "Sb"; _EleName[52] = "Te"; _EleName[53] = "I"; _EleName[54] = "Xe"; _EleName[55] = "Cs"; _EleName[56] = "Ba"; _EleName[72] = "Hf"; _EleName[73] = "Ta"; _EleName[74] = "W"; _EleName[75] = "Re"; _EleName[76] = "Os"; _EleName[77] = "Ir"; _EleName[78] = "Pt"; _EleName[79] = "Au"; _EleName[80] = "Hg"; _EleName[81] = "Tl"; _EleName[82] = "Pb"; _EleName[83] = "Bi"; _EleName[84] = "Po"; _EleName[85] = "At"; _EleName[86] = "Rn"; } void Elements::FillEleShort() { // VdW radii in Angstrom as used in MK Gaussian _EleShort["HYDROGEN"] = "H"; _EleShort["HELIUM"] = "He"; _EleShort["LITHIUM"] = "Li"; _EleShort["BERYLLIUM"] = "Be"; _EleShort["BORON"] = "B"; _EleShort["CARBON"] = "C"; _EleShort["NITROGEN"] = "Ni"; _EleShort["OXYGEN"] = "O"; _EleShort["FLUORINE"] = "Fl"; _EleShort["NEON"] = "Ne"; _EleShort["SODIUM"] = "Na"; _EleShort["MAGNESIUM"] = "Mg"; _EleShort["ALUMINUM"] = "Al"; _EleShort["SILICON"] = "Si"; _EleShort["PHOSPHORUS"] = "Ph"; _EleShort["SULFUR"] = "S"; _EleShort["CLORINE"] = "Cl"; _EleShort["ARGON"] = "Ar"; _EleShort["POTASSIUM"] = "K"; _EleShort["CALCIUM"] = "Ca"; _EleShort["SCANDDIUM"] = "Sc"; _EleShort["TITANIUM"] = "Ti"; _EleShort["VANADIUM"] = "V"; _EleShort["CHROMIUM"] = "Cr"; _EleShort["MANGANESE"] = "Mn"; _EleShort["IRON"] = "Fe"; _EleShort["COBALT"] = "Co"; _EleShort["NICKEL"] = "Ni"; _EleShort["COPPER"] = "Cu"; _EleShort["ZINC"] = "Zn"; _EleShort["GALLIUM"] = "Ga"; _EleShort["GERMANIUM"] = "Ge"; _EleShort["ARSENIC"] = "As"; _EleShort["SELENIUM"] = "Se"; _EleShort["BROMINE"] = "Br"; _EleShort["KRPTON"] = "Kr"; _EleShort["RUBIDIUM"] = "Rb"; _EleShort["STRONTIUM"] = "Sr"; _EleShort["YTTRIUM"] = "Y"; _EleShort["ZIRCONIUM"] = "Zr"; _EleShort["NIOBIUM"] = "Nb"; _EleShort["MOLYBDENUM"] = "Mo"; _EleShort["TECHNETIUM"] = "Tc"; _EleShort["RUTHENIUM"] = "Ru"; _EleShort["RHODIUM"] = "Rh"; _EleShort["PALLADIUM"] = "Pd"; _EleShort["SILVER"] = "Ag"; _EleShort["CADMIUM"] = "Cd"; _EleShort["INDIUM"] = "In"; _EleShort["TIN"] = "Sn"; _EleShort["ANTIMONY"] = "Sb"; _EleShort["TELLURIUM"] = "Te"; _EleShort["IODINE"] = "I"; _EleShort["XENON"] = "Xe"; _EleShort["CAESIUM"] = "Cs"; _EleShort["BARIUM"] = "Ba"; _EleShort["HAFNIUM"] = "Hf"; _EleShort["TANTALUM"] = "Ta"; _EleShort["TUNGSTEN"] = "W"; _EleShort["RHENIUM"] = "Re"; _EleShort["OSMIUM"] = "Os"; _EleShort["IRIDIUM"] = "Ir"; _EleShort["PLATINUM"] = "Pt"; _EleShort["GOLD"] = "Au"; _EleShort["MERCURY"] = "Hg"; _EleShort["THALLIUM"] = "Tl"; _EleShort["LEAD"] = "Pd"; _EleShort["BISMUTH"] = "Bi"; _EleShort["PLONIUM"] = "Po"; _EleShort["ASTATINE"] = "At"; _EleShort["RADON"] = "Rn"; } void Elements::FillEleFull() { // VdW radii in Angstrom as used in MK Gaussian _EleFull["H"] = "HYDROGEN"; _EleFull["He"] = "HELIUM"; _EleFull["Li"] = "LITHIUM"; _EleFull["Be"] = "BERYLLIUM"; _EleFull["B"] = "BORON"; _EleFull["C"] = "CARBON"; _EleFull["N"] = "NITROGEN"; _EleFull["O"] = "OXYGEN"; _EleFull["F"] = "FLUORINE"; _EleFull["Ne"] = "NEON"; _EleFull["Na"] = "SODIUM"; _EleFull["Mg"] = "MAGNESIUM"; _EleFull["Al"] = "ALUMINUM"; _EleFull["Si"] = "SILICON"; _EleFull["P"] = "PHOSPHORUS"; _EleFull["S"] = "SULFUR"; _EleFull["Cl"] = "CHLORINE"; _EleFull["Ar"] = "ARGON"; _EleFull["K"] = "POTASSIUM"; _EleFull["Ca"] = "CALCIUM"; _EleFull["Sc"] = "SCANDIUM"; _EleFull["Ti"] = "TITANIUM"; _EleFull["V"] = "VANADIUM"; _EleFull["Cr"] = "CHROMIUM"; _EleFull["Mn"] = "MANGANESE"; _EleFull["Fe"] = "IRON"; _EleFull["Co"] = "COBALT"; _EleFull["Ni"] = "NICKEL"; _EleFull["Cu"] = "COPPER"; _EleFull["Zn"] = "ZINC"; _EleFull["Ga"] = "GALLIUM"; _EleFull["Ge"] = "GERMANIUM"; _EleFull["As"] = "ARSENIC"; _EleFull["Se"] = "SELENIUM"; _EleFull["Br"] = "BROMINE"; _EleFull["Kr"] = "KRYPTON"; _EleFull["Rb"] = "RUBIDIUM"; _EleFull["Sr"] = "STRONTIUM"; _EleFull["Y"] = "YTTRIUM"; _EleFull["Zr"] = "ZIRCONIUM"; _EleFull["Nb"] = "NIOBIUM"; _EleFull["Mo"] = "MOLYBDENUM"; _EleFull["Tc"] = "TECHNETIUM"; _EleFull["Ru"] = "TUTHENIUM"; _EleFull["Rh"] = "RHODIUM"; _EleFull["Pd"] = "PALLADIUM"; _EleFull["Ag"] = "SILVER"; _EleFull["Cd"] = "CADMIUM"; _EleFull["In"] = "INDIUM"; _EleFull["Sn"] = "TIN"; _EleFull["Sb"] = "ANTIMONY"; _EleFull["Te"] = "TELLURIUM"; _EleFull["I"] = "IODINE"; _EleFull["Xe"] = "XENON"; _EleFull["Cs"] = "CEASIUM"; _EleFull["Ba"] = "BARIUM"; _EleFull["Hf"] = "HAFNIUM"; _EleFull["Ta"] = "TANTALUM"; _EleFull["W"] = "TUNGSTEN"; _EleFull["Re"] = "RHENIUM"; _EleFull["Os"] = "OSMIUM"; _EleFull["Ir"] = "IRIDIUM"; _EleFull["Pt"] = "PLATINUM"; _EleFull["Au"] = "GOLD"; _EleFull["Hg"] = "MERCURY"; _EleFull["Tl"] = "THALLIUM"; _EleFull["Pb"] = "LEAD"; _EleFull["Bi"] = "BISMUTH"; _EleFull["Po"] = "POLONIUM"; _EleFull["At"] = "ASTATINE"; _EleFull["Rn"] = "RADON"; } void Elements::FillVdWMK() { // VdW radii in Angstrom as used in MK Gaussian _VdWMK["H"] = 1.2; _VdWMK["He"] = 1.2; _VdWMK["Li"] = 1.37; _VdWMK["Be"] = 1.45; _VdWMK["B"] = 1.45; _VdWMK["C"] = 1.5; _VdWMK["N"] = 1.5; _VdWMK["O"] = 1.4; _VdWMK["F"] = 1.35; _VdWMK["Ne"] = 1.3; _VdWMK["Na"] = 1.57; _VdWMK["Mg"] = 1.36; _VdWMK["Al"] = 1.24; _VdWMK["Si"] = 1.17; _VdWMK["P"] = 1.8; _VdWMK["S"] = 1.75; _VdWMK["Cl"] = 1.7; _VdWMK["Ag"] = 2.0; } void Elements::FillPolarizability() { _ElPolarizability["H"] = 0.496e-3; _ElPolarizability["C"] = 1.334e-3; _ElPolarizability["N"] = 1.073e-3; _ElPolarizability["O"] = 0.837e-3; _ElPolarizability["S"] = 2.926e-3; _ElPolarizability["F"] = 0.440e-3; _ElPolarizability["Si"] = 3.962e-3; // B3LYP/6-311+g(2d,2p) _ElPolarizability["Zn"] = 5.962e-3; // B3LYP/6-311+g(2d,2p) _ElPolarizability["Al"] = 5.80e-3; //[1]P. Fuentealba, “The static dipole polarizability of // aluminium atom: discrepancy between theory and experiment,” // Chemical physics letters, vol. 397, no. 4, pp. 459–461, 2004. } } // namespace tools } // namespace votca tools-2021.2/src/libtools/filesystem.cc000066400000000000000000000027701412152065700200620ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/filesystem.h" namespace votca { namespace tools { namespace filesystem { std::string GetFileExtension(const std::string& filename) { size_t i = filename.rfind('.', filename.length()); if (i != std::string::npos) { return (filename.substr(i + 1, filename.length() - i)); } return (""); } std::string GetFileBase(const std::string& filename) { size_t i = filename.rfind('.', filename.length()); if (i != std::string::npos) { return (filename.substr(0, i)); } return filename; } bool FileExists(const std::string& filename) { std::ifstream infile(filename); return infile.good(); } } // namespace filesystem } // namespace tools } // namespace votca tools-2021.2/src/libtools/globals.cc000066400000000000000000000057301412152065700173200ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/globals.h" #include namespace votca { Log::Level Log::current_level = Log::info; namespace tools { std::string GetVotcaShare() { char *votca_share = getenv("VOTCASHARE"); if (votca_share == nullptr) { throw std::runtime_error("VOTCASHARE not set, cannot open help files."); } return std::string(votca_share); } bool VotcaShareSet() { return (getenv("VOTCASHARE") != nullptr); } std::string globals::url = "http://www.votca.org"; std::string globals::email = "devs@votca.org"; std::string globals::man::option(".TP\n\\fB%1%\\fR\n%2%\n"); std::string globals::man::header(".TH \"%1%\" 1 \"\" \"Version: %2%\"\n\n"); std::string globals::man::name( ".SH NAME\n" "\n.P\n" "%1% \\- Part of the VOTCA package\n" "\n.P\n" "For more info please visit %2%\n\n"); std::string globals::man::authors( "\n.SH AUTHORS\n" "\n.P\n" "Written and maintained by the VOTCA Development Team <%1%>\n"); std::string globals::man::copyright( "\n.SH COPYRIGHT\n" "\n.P\n\n" "Copyright 2009\\-2020 The VOTCA Development Team (%1%).\n" "\n.P\n" "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" "\n.P\n" "http://www.apache.org/licenses/LICENSE\\-2.0\n" "\n.P\n" "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."); std::string globals::man::synopsis( "\n.SH SYNOPSIS\n" "\n.P\n\\fB%1%\\fR [\\fIOPTION\\fR] [\\fIARGUMENT\\fR]\n"); std::string globals::man::description( "\n.SH DESCRIPTION\n" "\n.P\n%1%\n"); std::string globals::man::options("\n.SH OPTIONS\n"); std::string globals::tex::section("\n\\subsection{%1%}"); std::string globals::tex::label("\n\\label{prog:%1%}"); std::string globals::tex::description("\n%1%"); std::string globals::tex::option("\n\\item[ ] \\texttt{%1%} %2%"); std::string globals::tex::options( "\n\\begin{compactitem}%1%\n\\end{compactitem}\n"); } // namespace tools } // namespace votca tools-2021.2/src/libtools/graph.cc000066400000000000000000000124541412152065700167770ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Local VOTCA includes #include "votca/tools/graph.h" using namespace std; namespace votca { namespace tools { class GraphNode; bool nodeForEveryVertex_(vector vertices, unordered_map nodes) { for (const Index vertex : vertices) { if (nodes.count(vertex) == 0) { return false; } } return true; } Graph::Graph(vector edges, unordered_map nodes) { edge_container_ = EdgeContainer(edges); vector vertices = edge_container_.getVertices(); assert(nodeForEveryVertex_(vertices, nodes) && "A node must exist for every vertex."); nodes_ = nodes; for (const pair id_and_node : nodes_) { if (edge_container_.vertexExist(id_and_node.first) == false) { edge_container_.addVertex(id_and_node.first); } } calcId_(); } bool Graph::operator!=(const Graph& graph) const { return id_.compare(graph.id_); } bool Graph::operator==(const Graph& graph) const { return !(*(this) != graph); } vector> Graph::getIsolatedNodes(void) const { vector> isolated_nodes; vector vertices_degree_0 = edge_container_.getVerticesDegree(0); for (const Index vertex : vertices_degree_0) { pair id_and_node{vertex, nodes_.at(vertex)}; isolated_nodes.push_back(id_and_node); } return isolated_nodes; } vector> Graph::getNeighNodes(Index vertex) const { vector neigh_vertices = edge_container_.getNeighVertices(vertex); vector> neigh_ids_and_nodes; for (const Index& neigh_vert : neigh_vertices) { auto id_and_node = pair(neigh_vert, nodes_.at(neigh_vert)); neigh_ids_and_nodes.push_back(id_and_node); } return neigh_ids_and_nodes; } void Graph::setNode(Index vertex, GraphNode& graph_node) { assert(nodes_.count(vertex) && "Can only set a node that already exists"); nodes_[vertex] = graph_node; calcId_(); } void Graph::setNode(std::pair& id_and_node) { setNode(id_and_node.first, id_and_node.second); } GraphNode Graph::getNode(const Index vertex) const { assert(nodes_.count(vertex)); return nodes_.at(vertex); } vector> Graph::getNodes(void) const { vector> vec_nodes; for (const pair& id_and_node : nodes_) { vec_nodes.push_back(id_and_node); } return vec_nodes; } vector Graph::getJunctions() const { vector junctions; Index max_degree = edge_container_.getMaxDegree(); for (Index degree = 3; degree <= max_degree; ++degree) { vector vertices = edge_container_.getVerticesDegree(degree); junctions.insert(junctions.end(), vertices.begin(), vertices.end()); } return junctions; } void Graph::clearNodes() { nodes_.clear(); } void Graph::copyNodes(Graph& graph) { assert(nodes_.size() == 0); for (const pair& id_and_node : graph.nodes_) { this->nodes_[id_and_node.first] = id_and_node.second; } } void Graph::calcId_() { auto nodes = getNodes(); sort(nodes.begin(), nodes.end(), cmpVertNodePair); string struct_Id_temp = ""; for (const pair& id_and_node : nodes) { struct_Id_temp.append(id_and_node.second.getStringId()); } id_ = struct_Id_temp; return; } Index Graph::getDegree(Index vertex) const { if (edge_container_.vertexExist(vertex)) { return edge_container_.getDegree(vertex); } if (nodes_.count(vertex)) { return 0; } throw invalid_argument( "vertex does not exist within the graph the degree is " "not defined."); } bool Graph::vertexExist(Index vertex) const { if (edge_container_.vertexExist(vertex)) { return true; } if (nodes_.count(vertex)) { return true; } return false; } vector Graph::getVerticesDegree(Index degree) const { return edge_container_.getVerticesDegree(degree); } vector Graph::getVertices() const { return edge_container_.getVertices(); } ostream& operator<<(ostream& os, const Graph graph) { os << "Graph" << endl; for (const pair& id_and_node : graph.nodes_) { os << "Node " << id_and_node.first << endl; os << id_and_node.second << endl; } return os; } bool cmpVertNodePair(const pair& id_and_node1, const pair& id_and_node2) { string str1_Id = id_and_node1.second.getStringId(); return str1_Id.compare(id_and_node2.second.getStringId()) < 0; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graph_bf_visitor.cc000066400000000000000000000045101412152065700212170ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/graph_bf_visitor.h" #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graphnode.h" using namespace std; namespace votca { namespace tools { bool Graph_BF_Visitor::queEmpty() const { return edge_que_.empty(); } Edge Graph_BF_Visitor::getEdge_() { Edge oldest_edge = edge_que_.at(0).front(); edge_que_.at(0).pop(); if (edge_que_.at(0).size() == 0) { edge_que_.pop_front(); } return oldest_edge; } // Add edges to be explored void Graph_BF_Visitor::addEdges_(const Graph &graph, Index vertex) { vector newest_edges = graph.getNeighEdges(vertex); // If first edges to be added if (edge_que_.empty()) { queue first_edge_queue; for (const Edge &edge : newest_edges) { Index neigh_vert = edge.getOtherEndPoint(vertex); if (explored_.count(neigh_vert) == 0) { first_edge_queue.push(edge); } } if (!first_edge_queue.empty()) { edge_que_.push_back(first_edge_queue); } } else { if (edge_que_.size() == 1) { queue new_edge_queue; for (const Edge &edge : newest_edges) { Index neigh_vert = edge.getOtherEndPoint(vertex); if (explored_.count(neigh_vert) == 0) { new_edge_queue.push(edge); } } if (!new_edge_queue.empty()) { edge_que_.push_back(new_edge_queue); } } else { for (const Edge &edge : newest_edges) { Index neigh_vert = edge.getOtherEndPoint(vertex); if (explored_.count(neigh_vert) == 0) { edge_que_.at(1).push(edge); } } } } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graph_df_visitor.cc000066400000000000000000000042271412152065700212260ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graph_df_visitor.h" #include "votca/tools/graphnode.h" using namespace std; namespace votca { namespace tools { bool Graph_DF_Visitor::queEmpty() const { return edge_list_.empty(); } Edge Graph_DF_Visitor::getEdge_() { Edge ed = edge_list_.back(); edge_list_.pop_back(); return ed; } // Add edges to be explored void Graph_DF_Visitor::addEdges_(const Graph& g, Index vertex) { auto eds = g.getNeighEdges(vertex); if (edge_list_.empty()) { // If first edges to be added for (auto ed : eds) { Index neigh_vert = ed.getOtherEndPoint(vertex); if (explored_.count(neigh_vert) == 0) { edge_list_.push_back(ed); } } } else { for (const auto& ed : eds) { Index neigh_vert = ed.getOtherEndPoint(vertex); if (explored_.count(neigh_vert) == 0) { edge_list_.push_back(ed); } else { // Check if edge has already been added earlier in the queue // if so we wil move it to the end list::iterator edge_found_iterator = find(edge_list_.begin(), edge_list_.end(), ed); if (edge_found_iterator != edge_list_.end()) { // Move the edge to the back if it was stored earlier on. edge_list_.splice(edge_list_.end(), edge_list_, edge_found_iterator); } } } } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graphalgorithm.cc000066400000000000000000000232341412152065700207040ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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 writingraph, 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/graph.h" #include "votca/tools/graph_bf_visitor.h" #include "votca/tools/graph_df_visitor.h" #include "votca/tools/graphalgorithm.h" #include "votca/tools/graphvisitor.h" using namespace std; namespace votca { namespace tools { /********************** * Internal Functions * **********************/ /******************** * Public Functions * ********************/ bool singleNetwork(Graph& graph, GraphVisitor& graph_visitor) { exploreGraph(graph, graph_visitor); return graph_visitor.getExploredVertices().size() == graph.getVertices().size() && graph.getIsolatedNodes().size() == 0; } std::set exploreBranch(Graph g, Index starting_vertex, const Edge& edge) { // Check if the starting vertex is in the graph if (!g.vertexExist(starting_vertex)) { throw invalid_argument( "Cannot explore a branch of the graph when the " "exploration is started from a vertex that does not exist within the " "graph."); } if (!g.edgeExist(edge)) { throw invalid_argument( "Edge does not exist in the graph so exploration of" " the graph branch cannot continue"); } if (!edge.contains(starting_vertex)) { throw invalid_argument( "The edge determining which branch to explore does " "not contain the starting vertex."); } set branch_edges; if (edge.getEndPoint1() == edge.getEndPoint2()) { branch_edges.insert(edge); return branch_edges; } Graph_BF_Visitor gv_breadth_first; GraphNode gn; pair pr_gn(starting_vertex, gn); gv_breadth_first.exploreNode(pr_gn, g); gv_breadth_first.setStartingVertex(edge.getOtherEndPoint(starting_vertex)); gv_breadth_first.initialize(g); branch_edges.insert(edge); while (!gv_breadth_first.queEmpty()) { Edge ed = gv_breadth_first.nextEdge(g); branch_edges.insert(ed); gv_breadth_first.exec(g, ed); } vector neigh_edges = g.getNeighEdges(starting_vertex); for (Edge& ed : neigh_edges) { Index neigh_vertex = ed.getOtherEndPoint(starting_vertex); if (neigh_vertex != starting_vertex) { if (gv_breadth_first.vertexExplored(neigh_vertex)) { branch_edges.insert(ed); } } } return branch_edges; } ReducedGraph reduceGraph(Graph graph) { /**************************** * Internal Function Class ****************************/ /** * \brief This class is to help keep track of which vertices have and have not * been explored. * * It is only used within the function and hence the encapsulation, it is not * a public class and is not meant to be. **/ class ExplorationRecord { private: unordered_map> vertex_explored_; size_t unexplored_vertex_count_; public: explicit ExplorationRecord( const unordered_map>& vertex_explored) : vertex_explored_(vertex_explored), unexplored_vertex_count_(vertex_explored.size()){}; void explore(Index vertex) { vertex_explored_[vertex].first = true; --unexplored_vertex_count_; } bool unexploredVerticesExist() { return unexplored_vertex_count_ > 0; } Index getUnexploredVertex() { vector remaining_unexplored; for (const pair>& vertex_record : vertex_explored_) { bool vertex_explored = vertex_record.second.first; if (!vertex_explored) { Index degree = vertex_record.second.second; if (degree > 2) { return vertex_record.first; } remaining_unexplored.push_back(vertex_record.first); } } // Search tips next for (const Index& vertex : remaining_unexplored) { if (vertex_explored_[vertex].second == 1) { return vertex; } } // Finally if there are no tips or junctions left we will return a vertex // of degree 2 if one exists for (const Index& vertex : remaining_unexplored) { if (!vertex_explored_[vertex].first) { return vertex; } } throw runtime_error( "You cannot get an unexplored vertex as they have all" " been explored."); } }; // Class ExplorationRecord unordered_map> unexplored_vertices; vector vertices = graph.getVertices(); for (const Index& vertex : vertices) { unexplored_vertices[vertex] = pair(false, graph.getDegree(vertex)); } ExplorationRecord exploration_record(unexplored_vertices); vector> chains; while (exploration_record.unexploredVerticesExist()) { Graph_DF_Visitor graph_visitor; Index starting_vertex = exploration_record.getUnexploredVertex(); exploration_record.explore(starting_vertex); graph_visitor.setStartingVertex(starting_vertex); graph_visitor.initialize(graph); vector chain{starting_vertex}; Index old_vertex = starting_vertex; bool new_chain = false; while (!graph_visitor.queEmpty()) { Edge edge = graph_visitor.nextEdge(graph); vector unexplored_vertex = graph_visitor.getUnexploredVertex(edge); if (new_chain) { if (unexplored_vertex.size() == 0) { old_vertex = edge.getEndPoint1(); chain.push_back(old_vertex); new_chain = false; } else { old_vertex = edge.getOtherEndPoint(unexplored_vertex.at(0)); chain.push_back(old_vertex); new_chain = false; } } Index new_vertex = edge.getOtherEndPoint(old_vertex); if (unexplored_vertex.size() == 0) { chain.push_back(new_vertex); chains.push_back(chain); chain.clear(); new_chain = true; } else if (graph.getDegree(new_vertex) == 1) { chain.push_back(new_vertex); chains.push_back(chain); chain.clear(); exploration_record.explore(new_vertex); new_chain = true; } else if (graph.getDegree(new_vertex) > 2) { chain.push_back(new_vertex); chains.push_back(chain); chain.clear(); exploration_record.explore(new_vertex); new_chain = true; } else if (unexplored_vertex.size() == 1) { chain.push_back(new_vertex); old_vertex = new_vertex; exploration_record.explore(new_vertex); } graph_visitor.exec(graph, edge); } } vector reduced_edges; for (vector chain : chains) { ReducedEdge reduced_edge(chain); reduced_edges.push_back(reduced_edge); } ReducedGraph reduced_g(reduced_edges); auto nodes_graph = graph.getNodes(); reduced_g.clearNodes(); reduced_g.copyNodes(graph); auto nodes_reduced_g = reduced_g.getNodes(); return reduced_g; } vector decoupleIsolatedSubGraphs(Graph graph) { const std::vector& vertices = graph.getVertices(); // bool vector to see if vertex is already part of graph std::vector vertex_analysed = std::vector(vertices.size(), false); std::vector subGraphs; Index i = 0; while (i < Index(vertices.size())) { if (vertex_analysed[i]) { i++; continue; } Graph_BF_Visitor graph_visitor_breadth_first; graph_visitor_breadth_first.setStartingVertex(vertices[i]); exploreGraph(graph, graph_visitor_breadth_first); set sub_graph_explored_vertices = graph_visitor_breadth_first.getExploredVertices(); for (Index vertex : sub_graph_explored_vertices) { for (Index j = 0; j < Index(vertices.size()); j++) { if (vertex_analysed[j]) { continue; } if (vertex == vertices[j]) { vertex_analysed[j] = true; break; } } } set sub_graph_edges; unordered_map sub_graph_nodes; for (Index vertex : sub_graph_explored_vertices) { for (const Edge& sub_graph_edge : graph.getNeighEdges(vertex)) { sub_graph_edges.insert(sub_graph_edge); } sub_graph_nodes[vertex] = graph.getNode(vertex); } subGraphs.push_back( Graph(std::vector(sub_graph_edges.begin(), sub_graph_edges.end()), sub_graph_nodes)); } return subGraphs; } void exploreGraph(Graph& graph, GraphVisitor& graph_visitor) { if (!graph.vertexExist(graph_visitor.getStartingVertex())) { string err = "Cannot explore graph starting at vertex " + to_string(graph_visitor.getStartingVertex()) + " because it does not exist in the " "graph. You can change the starting vertex by using the " "setStartingVertex method of the visitor instance."; throw invalid_argument(err); } // Create a list of all vertices and determine if they have all been // explored when the visitor que is empty graph_visitor.initialize(graph); while (!graph_visitor.queEmpty()) { Edge edge = graph_visitor.nextEdge(graph); graph_visitor.exec(graph, edge); } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graphdistvisitor.cc000066400000000000000000000035431412152065700213020ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/graphdistvisitor.h" #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graph_bf_visitor.h" #include "votca/tools/graphnode.h" #include "votca/tools/graphvisitor.h" using namespace std; namespace votca { namespace tools { // Add the distance to the node that has not yet been explored void GraphDistVisitor::exploreNode(pair& p_gn, Graph& g, Edge ed) { // Determine if the node has already been explored Index vertex = p_gn.first; if (vertex == startingVertex_) { p_gn.second.int_vals_["Dist"] = 0; p_gn.second.initStringId_(); // Update the graph with new graph node g.setNode(p_gn); } else { // Node has not been explored if (explored_.count(vertex) == 0) { Index prev_vertex = ed.getOtherEndPoint(vertex); GraphNode gn_prev = g.getNode(prev_vertex); p_gn.second.int_vals_["Dist"] = gn_prev.int_vals_["Dist"] + 1; p_gn.second.initStringId_(); g.setNode(p_gn); } } // Ensure the graph node is set to explored GraphVisitor::exploreNode(p_gn, g); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graphnode.cc000066400000000000000000000133771412152065700176520ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include #include #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graphnode.h" namespace votca { namespace tools { using namespace std; using namespace boost; /////////////////////////////////////////////////////////// // Local Functions /////////////////////////////////////////////////////////// /// Converts a double into a string with max number of significant /// figures indicated by sf string sig_fig_(double val, Index sf) { return ([val](Index number_of_sig_figs) -> string { stringstream lStream; lStream << setprecision(int(number_of_sig_figs)) << val; return lStream.str(); })(sf); } /// Turns the map of ints into a string that is sorted alphabetically /// by the keys string getIntStringId_(const unordered_map int_vals) { vector keys; // Grab integer keys sort alphabetically and store in string_id string int_string_id; for (auto it : int_vals) { keys.push_back(it.first); } sort(keys.begin(), keys.end()); for (auto key : keys) { int_string_id.append(key); auto it = int_vals.find(key); int_string_id.append(lexical_cast(it->second)); } return int_string_id; } /// Turns the map of doubles into a string that is sorted alphabetically /// by the keys string getDoubleStringId_(const unordered_map double_vals) { vector keys; // Grab double keys sort alphabetically and store in string_id string double_string_id; for (auto it : double_vals) { keys.push_back(it.first); } sort(keys.begin(), keys.end()); for (auto key : keys) { double_string_id.append(key); auto it = double_vals.find(key); double_string_id.append(sig_fig_(it->second, 8)); } return double_string_id; } /// Turns the map of strings into a string that is sorted alphabetically /// by the keys string getStrStringId_(const unordered_map str_vals) { vector keys; // Grab string keys sort alphabetically and store in string_id string str_string_id; for (auto it : str_vals) { keys.push_back(it.first); } sort(keys.begin(), keys.end()); for (auto key : keys) { str_string_id.append(key); auto it = str_vals.find(key); str_string_id.append(lexical_cast(it->second)); } return str_string_id; } /////////////////////////////////////////////////////////// // Private Functions /////////////////////////////////////////////////////////// /// Used to reinitialize the string id if any of the contents /// of the graphnode change void GraphNode::initStringId_() { str_id_.clear(); str_id_.append(getIntStringId_(int_vals_)); str_id_.append(getDoubleStringId_(double_vals_)); str_id_.append(getStrStringId_(str_vals_)); } /////////////////////////////////////////////////////////// // Public Functions /////////////////////////////////////////////////////////// GraphNode::GraphNode(const unordered_map int_vals, const unordered_map double_vals, const unordered_map str_vals) { int_vals_ = int_vals; double_vals_ = double_vals; str_vals_ = str_vals; initStringId_(); } void GraphNode::setInt(const unordered_map int_vals) { int_vals_ = int_vals; initStringId_(); } void GraphNode::setDouble(const unordered_map double_vals) { double_vals_ = double_vals; initStringId_(); } void GraphNode::setStr(const unordered_map str_vals) { str_vals_ = str_vals; initStringId_(); } Index GraphNode::getInt(const string str) { if (int_vals_.count(str) == 0) { throw invalid_argument( "GraphNode does not " "contain value"); } return int_vals_[str]; } double GraphNode::getDouble(const string str) { if (double_vals_.count(str) == 0) { throw invalid_argument( "GraphNode does not " "contain value"); } return double_vals_[str]; } std::string GraphNode::getStr(const string str) { if (str_vals_.count(str) == 0) { throw invalid_argument( "GraphNode does not " "contain value"); } return str_vals_[str]; } bool GraphNode::operator!=(const GraphNode gn) const { return (str_id_.compare(gn.str_id_) != 0); } bool GraphNode::operator==(const GraphNode gn) const { return !((*this) != gn); } ostream& operator<<(ostream& os, const GraphNode gn) { os << "Integer Values" << endl; for (const auto& int_val : gn.int_vals_) { os << int_val.first << " " << int_val.second << endl; } os << "Double Values" << endl; for (const auto& double_val : gn.double_vals_) { os << double_val.first << " " << double_val.second << endl; } os << "String Values" << endl; for (const auto& str_val : gn.str_vals_) { os << str_val.first << " " << str_val.second << endl; } return os; } bool cmpNode(GraphNode gn1, GraphNode gn2) { string str1_Id = gn1.getStringId(); return str1_Id.compare(gn2.getStringId()) < 0; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/graphvisitor.cc000066400000000000000000000061761412152065700204230ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graphvisitor.h" using namespace std; namespace votca { namespace tools { class GraphNode; bool GraphVisitor::queEmpty() const { return true; } void GraphVisitor::exploreNode(pair& vertex_and_node, Graph&, Edge) { explored_.insert(vertex_and_node.first); } vector GraphVisitor::getUnexploredVertex(const Edge edge) const { vector unexp_vert; if (explored_.count(edge.getEndPoint1()) == 0) { unexp_vert.push_back(edge.getEndPoint1()); } if (explored_.count(edge.getEndPoint2()) == 0) { unexp_vert.push_back(edge.getEndPoint2()); } return unexp_vert; } bool GraphVisitor::vertexExplored(const Index vertex) const { return explored_.count(vertex) == 1; } void GraphVisitor::initialize(Graph& graph) { vector neigh_eds = graph.getNeighEdges(startingVertex_); GraphNode graph_node = graph.getNode(startingVertex_); pair vertex_and_graph_node(startingVertex_, graph_node); exploreNode(vertex_and_graph_node, graph); addEdges_(graph, startingVertex_); } void GraphVisitor::exec(Graph& graph, Edge edge) { vector unexp_vert = getUnexploredVertex(edge); // If no vertices are return than just ignore it means the same // vertex was explored from a different direction if (!unexp_vert.size()) { return; } // If two values are returned this is a problem if (unexp_vert.size() > 1) { throw runtime_error( "More than one unexplored vertex in an edge," " did you set the starting node"); } pair vertex_and_node(unexp_vert.at(0), graph.getNode(unexp_vert.at(0))); exploreNode(vertex_and_node, graph, edge); } Edge GraphVisitor::nextEdge(Graph graph) { // Get the edge and at the same time remove it from whatever queue it is in Edge edge = getEdge_(); vector unexplored_vertices = getUnexploredVertex(edge); // Do not add neighboring edges if they belong to a vertex that has already // been explored because they will have already been added if (unexplored_vertices.size()) { addEdges_(graph, unexplored_vertices.at(0)); } return edge; } set GraphVisitor::getExploredVertices() const { return explored_; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/histogram.cc000066400000000000000000000064071412152065700176740ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Local VOTCA includes #include "votca/tools/histogram.h" namespace votca { namespace tools { Histogram::Histogram() = default; Histogram::Histogram(const options_t& op) : _options(op) {} Histogram::~Histogram() = default; void Histogram::ProcessData(DataCollection::selection* data) { _pdf.assign(_options._n, 0); if (_options._auto_interval) { _min = std::numeric_limits::max(); _max = std::numeric_limits::min(); _options._extend_interval = true; } else { _min = _options._min; _max = _options._max; } for (auto& array : *data) { if (_options._extend_interval || _options._auto_interval) { for (auto& value : *array) { _min = std::min(value, _min); _max = std::max(value, _max); } } } _interval = (_max - _min) / (double)(_options._n - 1); double v = 1.; for (auto& array : *data) { for (auto& value : *array) { Index ii = (Index)floor((value - _min) / _interval + 0.5); // the interval should // be centered around // the sampling point if (ii < 0 || ii >= _options._n) { if (_options._periodic) { while (ii < 0) { ii += _options._n; } ii = ii % _options._n; } else { continue; } } _pdf[ii] += v; } } if (_options._scale == "bond") { for (size_t i = 0; i < _pdf.size(); ++i) { double r = _min + _interval * (double)i; if (std::fabs(r) < 1e-10) { r = _min + _interval * (double)(i + 1); _pdf[i] = _pdf[i + 1]; } _pdf[i] /= (r * r); } } else if (_options._scale == "angle") { for (size_t i = 0; i < _pdf.size(); ++i) { double alpha = _min + _interval * (double)i; double sa = sin(alpha); if (std::fabs(sa) < 1e-5) { if (i < _pdf.size() - 1) { alpha = _min + _interval * (double)(i + 1); _pdf[i] = _pdf[i + 1] / sin(alpha); } else { _pdf[i] = _pdf[i - 1]; } } else { _pdf[i] /= sa; } } } if (_options._periodic) { _pdf[0] = (_pdf[0] + _pdf[_options._n - 1]); _pdf[_options._n - 1] = _pdf[0]; } if (_options._normalize) { Normalize(); } } void Histogram::Normalize() { double norm = 1. / (_interval * accumulate(_pdf.begin(), _pdf.end(), 0.0)); std::transform(_pdf.begin(), _pdf.end(), _pdf.begin(), std::bind2nd(std::multiplies(), norm)); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/histogramnew.cc000066400000000000000000000045741412152065700204110ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/histogramnew.h" using namespace std; namespace votca { namespace tools { void HistogramNew::Initialize_() { if (_periodic) { _step = (_max - _min) / double(_nbins); } else { _step = (_max - _min) / (double(_nbins) - 1.0); } if (_nbins == 1) { _step = 1; } _data.resize(_nbins); double v = _min; for (Index i = 0; i < _nbins; v += _step, ++i) { _data.x(i) = v; } _data.y() = Eigen::VectorXd::Zero(_nbins); _data.yerr() = Eigen::VectorXd::Zero(_nbins); _data.flags() = std::vector(_nbins, 'i'); } void HistogramNew::Initialize(double min, double max, Index nbins) { _min = min; _max = max; _nbins = nbins; Initialize_(); } void HistogramNew::Process(const double &v, double scale) { Index i = (Index)floor((v - _min) / _step + 0.5); if (i < 0 || i >= _nbins) { if (_periodic) { if (i < 0) { i = _nbins - ((-i) % _nbins); } else { i = i % _nbins; } } else { return; } } _data.y(i) += scale; } double HistogramNew::getMinBinVal() const { return _data.getMinY(); } double HistogramNew::getMaxBinVal() const { return _data.getMaxY(); } pair HistogramNew::getInterval(Index bin) const { pair bounds; double value = static_cast(bin); bounds.first = value * _step + _min; bounds.second += _step; return bounds; } void HistogramNew::Normalize() { double area = 0; area = _data.y().cwiseAbs().sum() * _step; double scale = 1. / area; _data.y() *= scale; } void HistogramNew::Clear() { _data.y() = Eigen::VectorXd::Zero(_nbins); _data.yerr() = Eigen::VectorXd::Zero(_nbins); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/linalg.cc000066400000000000000000000071271412152065700171450ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include // Local VOTCA includes #include "votca/tools/linalg.h" namespace votca { namespace tools { Eigen::VectorXd linalg_constrained_qrsolve(const Eigen::MatrixXd &A, const Eigen::VectorXd &b, const Eigen::MatrixXd &constr) { // check matrix for zero column bool nonzero_found = false; for (Index j = 0; j < A.cols(); j++) { nonzero_found = A.col(j).isApproxToConstant(0.0, 1e-9); if (nonzero_found) { throw std::runtime_error("constrained_qrsolve_zero_column_in_matrix"); } } const Index NoVariables = A.cols(); const Index NoConstrains = constr.rows(); // number of constraints is number of rows of constr const Index deg_of_freedom = NoVariables - NoConstrains; Eigen::HouseholderQR QR(constr.transpose()); // Calculate A * Q and store the result in A auto A_new = A * QR.householderQ(); // A_new = [A1 A2], so A2 is just a block of A // [A1 A2] has N rows. A1 has ysize columns // A2 has 2*ngrid-ysize columns Eigen::MatrixXd A2 = A_new.rightCols(deg_of_freedom); // now perform QR-decomposition of A2 to solve the least-squares problem A2 * // z = b A2 has N rows and (2*ngrid-ysize) columns -> Eigen::HouseholderQR QR2(A2); Eigen::VectorXd z = QR2.solve(b); // Next two steps assemble vector from y (which is zero-vector) and z Eigen::VectorXd result = Eigen::VectorXd::Zero(NoVariables); result.tail(deg_of_freedom) = z; // To get the final answer this vector should be multiplied by matrix Q return QR.householderQ() * result; } EigenSystem linalg_eigenvalues(Eigen::MatrixXd &A, Index nmax) { EigenSystem result; #ifdef MKL_FOUND Index n = A.rows(); std::vector ifail(n); MKL_INT lda = MKL_INT(n); // make sure that containers for eigenvalues and eigenvectors are of correct // size result.eigenvalues().resize(nmax); result.eigenvectors().resize(n, nmax); MKL_INT il = 1; MKL_INT iu = MKL_INT(nmax); double abstol = 0.0; // use default double vl = 0.0; double vu = 0.0; // make a pointer to the EIGEN matrix so that LAPACK understands it double *pA = A.data(); double *pV = result.eigenvectors().data(); double *pE = result.eigenvalues().data(); MKL_INT info; MKL_INT m; // call LAPACK via C interface info = LAPACKE_dsyevx(LAPACK_COL_MAJOR, 'V', 'I', 'U', lda, pA, lda, vl, vu, il, iu, abstol, &m, pE, pV, lda, ifail.data()); if (info == 0) { result.info() = Eigen::Success; } else if (info < 0) { result.info() = Eigen::NumericalIssue; } else { result.info() = Eigen::NoConvergence; } #else Eigen::SelfAdjointEigenSolver es(A); result.eigenvectors() = es.eigenvectors().leftCols(nmax); result.eigenvalues() = es.eigenvalues().head(nmax); result.info() = es.info(); #endif return result; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/linspline.cc000066400000000000000000000064421412152065700176730ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/linalg.h" #include "votca/tools/linspline.h" namespace votca { namespace tools { using namespace std; void LinSpline::Interpolate(const Eigen::VectorXd &x, const Eigen::VectorXd &y) { if (x.size() != y.size()) { throw std::invalid_argument( "error in LinSpline::Interpolate : sizes of vectors x and y do not " "match"); } if (x.size() < 2) { throw std::invalid_argument( "error in LinSpline::Interpolate : vectors x and y have to contain at " "least 2 points"); } const Index N = x.size(); // adjust the grid _r.resize(N); // copy the grid points into f _r = x; // LINEAR SPLINE: a(i) * x + b(i) // where i=number of interval // initialize vectors a,b a = Eigen::VectorXd::Zero(N); b = Eigen::VectorXd::Zero(N); // boundary conditions not applicable // calculate a,b for all intervals 0..(N-2), where interval // [x(i),x(i+1)] shall have number i (this means that the last interval // has number N-2) for (Index i = 0; i < N - 1; i++) { a(i) = (y(i + 1) - y(i)) / (x(i + 1) - x(i)); b(i) = y(i) - a(i) * x(i); } } void LinSpline::Fit(const Eigen::VectorXd &x, const Eigen::VectorXd &y) { if (x.size() != y.size()) { throw std::invalid_argument( "error in LinSpline::Fit : sizes of vectors x and y do not match"); } const Index N = x.size(); const Index ngrid = _r.size(); // construct the equation // A*u = b // The matrix A contains all conditions // s_i(x) = (y(i+1)-y(i)) * (x-r(i))/(r(i+1)-r(i)) + y(i) // where y(i) are the unknown values at grid points r(i), and // the condition y=s_i(x) is to be satisfied at all input points: // therefore b=y and u=vector of all unknown y(i) Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, ngrid); // construct matrix A for (Index i = 0; i < N; i++) { Index interval = getInterval(x(i)); A(i, interval) = 1 - (x(i) - _r(interval)) / (_r(interval + 1) - _r(interval)); A(i, interval + 1) = (x(i) - _r(interval)) / (_r(interval + 1) - _r(interval)); } // now do a qr solve Eigen::HouseholderQR QR(A); Eigen::VectorXd sol = QR.solve(y); // vector "sol" contains all y-values of fitted linear splines at each // interval border // get a(i) and b(i) for piecewise splines out of solution vector "sol" a = Eigen::VectorXd::Zero(ngrid - 1); b = Eigen::VectorXd::Zero(ngrid - 1); for (Index i = 0; i < ngrid - 1; i++) { a(i) = (sol(i + 1) - sol(i)) / (_r(i + 1) - _r(i)); b(i) = -a(i) * _r(i) + sol(i); } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/mutex.cc000066400000000000000000000017611412152065700170370ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include "votca/tools/mutex.h" namespace votca { namespace tools { Mutex::Mutex() { pthread_mutex_init(&_mutexVar, nullptr); } Mutex::~Mutex() { pthread_mutex_destroy(&_mutexVar); } void Mutex::Lock() { pthread_mutex_lock(&_mutexVar); } void Mutex::Unlock() { pthread_mutex_unlock(&_mutexVar); } } // namespace tools } // namespace votca tools-2021.2/src/libtools/parcer.cc000066400000000000000000000026651412152065700171550ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include namespace votca { namespace tools { using namespace std; // wrapper written with Denis to do MOO only on a file which give the unitary // transformation + displacement one per line void parce_string(string line, string delims, vector* result) { string::size_type begIdx, endIdx; begIdx = line.find_first_not_of(delims); while (begIdx != string::npos) { endIdx = line.find_first_of(delims, begIdx); if (endIdx == string::npos) { endIdx = line.length(); } result->push_back(line.substr(begIdx, endIdx - begIdx)); if (endIdx == line.length()) { break; cout << "I am still here"; } begIdx = line.find_first_not_of(delims, endIdx); } } } // namespace tools } // namespace votca tools-2021.2/src/libtools/property.cc000066400000000000000000000360231412152065700175600ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include #include #include #include #include // Third party includes #include #include #include #include // Local VOTCA includes #include "votca/tools/colors.h" #include "votca/tools/property.h" #include "votca/tools/propertyiomanipulator.h" #include "votca/tools/tokenizer.h" namespace votca { namespace tools { using namespace std; // ostream modifier defines the output format, level, indentation const Index Property::IOindex = std::ios_base::xalloc(); const Property &Property::get(const string &key) const { Tokenizer tok(key, "."); Tokenizer::iterator n = tok.begin(); if (n == tok.end()) { return *this; } const Property *p; map::const_iterator iter; if (*n == "") { p = this; } else { iter = _map.find(*n); if (iter == _map.end()) { throw std::runtime_error("property not found: " + key); } p = &_properties[((*iter).second)]; } ++n; try { for (; n != tok.end(); ++n) { p = &p->get(*n); } } catch (std::runtime_error &) { // catch here to get full key in // exception throw std::runtime_error("property not found: " + key); } return *p; } Property &Property::set(const std::string &key, const std::string &value) { Property &p = get(key); p.value() = value; return p; } Property &Property::add(const std::string &key, const std::string &value) { std::string path = _path; if (path != "") { path = path + "."; } _properties.push_back(Property(key, value, path + _name)); _map[key] = Index(_properties.size()) - 1; return _properties.back(); } bool Property::hasAttribute(const std::string &attribute) const { std::map::const_iterator it; it = _attributes.find(attribute); if (it == _attributes.end()) { return false; } return true; } bool Property::exists(const std::string &key) const { try { get(key); } catch (std::exception &) { return false; } return true; } void FixPath(tools::Property &prop, std::string path) { prop.path() = path; if (path != "") { path += "."; } path += prop.name(); for (tools::Property &child : prop) { FixPath(child, path); } } void Property::add(const Property &other) { _properties.push_back(other); _map[other.name()] = Index(_properties.size()) - 1; std::string path = _path; if (path != "") { path += "."; } path += _name; FixPath(_properties.back(), path); } Property &Property::get(const string &key) { return const_cast(static_cast(*this).get(key)); } Property &Property::getOradd(const std::string &key) { if (exists(key)) { return get(key); } else { return add(key, ""); } } std::vector Property::Select(const string &filter) const { Tokenizer tok(filter, "."); std::vector selection; if (tok.begin() == tok.end()) { return selection; } selection.push_back(this); for (const auto &n : tok) { std::vector childs; for (const Property *p : selection) { for (const Property &s : p->_properties) { if (wildcmp(n, s.name())) { childs.push_back(&s); } } } selection = childs; } return selection; } std::vector Property::Select(const string &filter) { Tokenizer tok(filter, "."); std::vector selection; if (tok.begin() == tok.end()) { return selection; } selection.push_back(this); for (const auto &n : tok) { std::vector childs; for (Property *p : selection) { for (Property &s : p->_properties) { if (wildcmp(n, s.name())) { childs.push_back(&s); } } } selection = childs; } return selection; } static void start_hndl(void *data, const char *el, const char **attr) { stack *property_stack = (stack *)XML_GetUserData((XML_Parser *)data); Property *cur = property_stack->top(); Property &np = cur->add(el, ""); for (Index i = 0; attr[i]; i += 2) { np.setAttribute(attr[i], attr[i + 1]); } property_stack->push(&np); } static void end_hndl(void *data, const char *) { stack *property_stack = (stack *)XML_GetUserData((XML_Parser *)data); property_stack->pop(); } void char_hndl(void *data, const char *txt, int txtlen) { stack *property_stack = (stack *)XML_GetUserData((XML_Parser *)data); Property *cur = property_stack->top(); cur->value().append(txt, txtlen); } void Property::LoadFromXML(string filename) { ifstream fl; fl.open(filename); if (!fl.is_open()) { throw std::ios_base::failure("Error on open xml file: " + filename); } XML_Parser parser = XML_ParserCreate(nullptr); if (!parser) { throw std::runtime_error("Couldn't allocate memory for xml parser"); } XML_UseParserAsHandlerArg(parser); XML_SetElementHandler(parser, start_hndl, end_hndl); XML_SetCharacterDataHandler(parser, char_hndl); stack pstack; pstack.push(this); XML_SetUserData(parser, (void *)&pstack); while (!fl.eof()) { string line; tools::getline(fl, line); line = line + "\n"; if (line.length() > (size_t)std::numeric_limits::max()) { throw std::runtime_error("Property::LoadFromXML: line is too long"); } if (!XML_Parse(parser, line.c_str(), (int)line.length(), fl.eof())) { throw std::ios_base::failure( filename + ": Parse error at line " + boost::lexical_cast(XML_GetCurrentLineNumber(parser)) + "\n" + XML_ErrorString(XML_GetErrorCode(parser))); } } fl.close(); XML_ParserFree(parser); } void PrintNodeTXT(std::ostream &out, const Property &p, const Index start_level, Index level = 0, string prefix = "", string offset = "") { if ((p.value() != "") || p.HasChildren()) { if (level >= start_level) { if ((p.value()).find_first_not_of("\t\n ") != std::string::npos) { out << offset << prefix << " = " << p.value() << endl; } } else { prefix = ""; } } for (const Property &prop : p) { level++; if (prefix == "") { PrintNodeTXT(out, prop, start_level, level, prefix + prop.name(), offset); } else { PrintNodeTXT(out, prop, start_level, level, prefix + "." + prop.name(), offset); } level--; } } void PrintNodeXML(std::ostream &out, const Property &p, PropertyIOManipulator *piom, Index level = 0, string offset = "") { Property::const_AttributeIterator ia; bool linebreak = true; bool has_value = false; const ColorSchemeBase *color = &DEFAULT_COLORS; string indent(""); Index start_level(0); if (piom) { start_level = piom->getLevel(); indent = piom->getIndentation(); color = piom->getColorScheme(); } string cKey = color->Magenta(); string cAttribute = color->Blue(); string cAttributeValue = color->Green(); string cReset = color->Reset(); // print starting only from the start_level (the first node (level 0) can be // <> ) if (level >= start_level) { // print the node name out << indent << offset << "<" << cKey << p.name() << cReset; // print the node attributes for (ia = p.firstAttribute(); ia != p.lastAttribute(); ++ia) { out << " " << cAttribute << ia->first << cReset << "=\"" << cAttributeValue << ia->second << cReset << "\""; } // print node value if it is not empty has_value = ((p.value()).find_first_not_of("\t\n ") != std::string::npos); if (has_value || p.HasChildren()) { out << ">"; } else { out << "/>" << std::endl; } if (has_value) { out << cAttributeValue << p.value() << cReset; linebreak = false; } // check if we need the end of the line or not if (!has_value && p.HasChildren()) { out << std::endl; } if (!has_value && !p.HasChildren()) { linebreak = false; } } // continue iteratively through the rest of the nodes for (const Property &prop : p) { level++; if (level > start_level) { offset += "\t"; } PrintNodeXML(out, prop, piom, level, offset); if (level > start_level) { offset.resize(offset.size() - 1); } level--; } if (level >= start_level) { if (linebreak) { out << indent << offset << "" << std::endl; } else if (has_value) { out << "" << std::endl; } } } void PrintNodeTEX(std::ostream &out, const Property &p, PropertyIOManipulator *piom, Index level = 0, string prefix = "") { Index start_level = 0; if (piom) { start_level = piom->getLevel(); } string head_name; string section(""); // reference of the description section in the manual string help(""); // if this is the head node, print the header if (level == start_level) { string header_format( "\\subsection{%1%}\n" "\\label{%2%}\n%3%\n" "\\rowcolors{1}{invisiblegray}{white}\n" "{\\small\n " "\\begin{longtable}{m{3cm}|m{2cm}|m{1cm}|m{8cm}}\n" " option & default & unit & description\\\\\n\\hline\n"); head_name = p.name(); string label = "calc:" + head_name; // reference of the xml file in the manual if (p.hasAttribute("section")) { section = p.getAttribute("section"); } if (p.hasAttribute("help")) { help = p.getAttribute("help"); } out << boost::format(header_format) % head_name % label % help; prefix = p.name(); } if (level > start_level) { // if this node has children or a value or is not the first, start recursive // printing if ((p.value() != "" || p.HasChildren()) && level > -1) { string tex_name = boost::replace_all_copy(p.name(), "_", "\\_"); string defaults(""); // default value if supplied if (p.hasAttribute("default")) { defaults = p.getAttribute("default"); } string unit(""); // unit, if supplied if (p.hasAttribute("unit")) { unit = p.getAttribute("unit"); } if (p.hasAttribute("help")) { help = p.getAttribute("help"); } string body_format( " \\hspace{%1%pt}\\hypertarget{%2%}{%3%} & %4% & %5% & %6% \\\\\n"); out << boost::format(body_format) % Index((level - start_level - 1) * 10) % prefix % tex_name % defaults % unit % help; } } // continue iteratively through the rest of the nodes for (const Property &pp : p) { level++; if (prefix == "") { PrintNodeTEX(out, pp, piom, level, prefix); } else { PrintNodeTEX(out, pp, piom, level, prefix); } level--; } // if this is the head node, print the footer if (level == start_level) { string footer_format( "\\end{longtable}\n}\n" "\\noindent Return to the description of " "\\slink{%1%}{\\texttt{%2%}}.\n"); out << boost::format(footer_format) % section % head_name; } } void PrintNodeHLP(std::ostream &out, const Property &p, const Index start_level = 0, Index level = 0, const string &prefix = "", const string &offset = "") { using ColorRGB = Color; // use the RGB palette ColorRGB RGB; // Instance of an RGB palette string fmt = "t|%1%%|15t|" + string(RGB.Blue()) + "%2%" + string(RGB.Green()) + "%|40t|%3%%|55t|" + string(RGB.Reset()) + "%4%\n"; Index leveloffset = level; string help(""); // if this is the head node, print the header if (level == start_level) { string head_name = string(RGB.Magenta()) + p.name(); if (p.hasAttribute("help")) { if (p.hasAttribute("help")) { help = string(RGB.Red()) + p.getAttribute("help"); } out << boost::format(" %1%: %|18t| %2%" + string(RGB.Reset()) + "\n") % head_name % help; } leveloffset = 0; out << boost::format("%|3" + fmt) % "OPTION" % "DEFAULT" % "UNIT" % "DESCRIPTION"; } if (level > start_level) { string ofmt = "%|" + boost::lexical_cast(leveloffset) + fmt; string unit(""); if (p.hasAttribute("unit")) { unit = p.getAttribute("unit"); } string defaults(""); if (p.hasAttribute("default")) { defaults = p.getAttribute("default"); } if (p.hasAttribute("help")) { help = p.getAttribute("help"); } if (!unit.empty()) { unit = "[" + unit + "]"; } if (!defaults.empty()) { defaults = "(" + defaults + ")"; } string name = p.name(); out << boost::format(ofmt) % name % defaults % unit % help; } for (const Property &pp : p) { level++; if (prefix == "") { PrintNodeHLP(out, pp, start_level, level, pp.name(), offset); } else { PrintNodeHLP(out, pp, start_level, level, prefix + "." + pp.name(), offset); } level--; } } std::ostream &operator<<(std::ostream &out, const Property &p) { if (!out.good()) { return out; } std::ostream::sentry sentry(out); if (sentry) { // get the property format object attached to the stream PropertyIOManipulator *pm = (PropertyIOManipulator *)out.pword(int(Property::getIOindex())); string indentation(""); Index level = 0; PropertyIOManipulator::Type type = PropertyIOManipulator::XML; if (pm) { indentation = pm->getIndentation(); level = pm->getLevel(); type = pm->getType(); // check if we > or >> to a file and remove color codes // if ( out.tellp() != -1 ) - not suitable for pipes if (!isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO)) { pm->setColorScheme(); } } switch (type) { default: PrintNodeTXT(out, p, level); break; case PropertyIOManipulator::XML: PrintNodeXML(out, p, pm); break; case PropertyIOManipulator::TXT: PrintNodeTXT(out, p, level, 0, "", indentation); break; case PropertyIOManipulator::TEX: PrintNodeTEX(out, p, pm); break; case PropertyIOManipulator::HLP: PrintNodeHLP(out, p, level, 0, "", indentation); break; } } return out; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/propertyiomanipulator.cc000066400000000000000000000017701412152065700223650ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/propertyiomanipulator.h" namespace votca { namespace tools { PropertyIOManipulator XML(PropertyIOManipulator::XML); PropertyIOManipulator TXT(PropertyIOManipulator::TXT); PropertyIOManipulator TEX(PropertyIOManipulator::TEX); PropertyIOManipulator HLP(PropertyIOManipulator::HLP); } // namespace tools } // namespace votca tools-2021.2/src/libtools/rangeparser.cc000066400000000000000000000044651412152065700202120ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Local VOTCA includes #include "votca/tools/rangeparser.h" #include "votca/tools/tokenizer.h" namespace votca { namespace tools { RangeParser::RangeParser() //: _has_begin(false) , _has_end(false) = default; void RangeParser::Parse(std::string str) { // remove all spaces in string std::string::iterator it = std::remove_if( str.begin(), str.end(), std::bind2nd(std::equal_to(), ' ')); str = std::string(str.begin(), it); Tokenizer tok(str, ","); for (std::string bl : tok) { ParseBlock(bl); } } void RangeParser::ParseBlock(std::string str) { Tokenizer tokenizer(str, ":"); std::vector toks; block_t block; block._stride = 1; tokenizer.ToVector(toks); if (toks.size() > 3 || toks.size() < 1) { throw std::runtime_error("invalid range"); } block._begin = block._end = std::stoi(toks[0]); if (toks.size() == 2) { block._end = std::stoi(toks[1]); } if (toks.size() == 3) { block._stride = std::stoi(toks[1]); block._end = std::stoi(toks[2]); } if (block._begin * block._stride > block._end * block._stride) { throw std::runtime_error( std::string("invalid range " + str + ": begin, end and stride do not form a closed interval")); } _blocks.push_back(block); } RangeParser::iterator& RangeParser::iterator::operator++() { _current += (*_block)._stride; if (_current > (*_block)._end) { ++_block; if (_block != _parent->_blocks.end()) { _current = (*_block)._begin; } else { _current = -1; } } return *this; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/reducededge.cc000066400000000000000000000122251412152065700201320ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include // Local VOTCA includes #include "votca/tools/reducededge.h" namespace votca { namespace tools { using namespace std; /** * Given a chain of vertices where the end points are the same this method * will rotate the chain so that the vertex with the smallest value is at the * end points e.g. * * 3 - 4 - 5 - 9 - 2 - 8 - 3 * * The method will return the chain as * * 2 - 8 - 3 - 4 - 5 - 9 - 2 * * Notice that the order is preserved, because it is assumed that the chain * makes a loop. **/ void moveVertexWithSmallestValueToEnds_(vector& vertices) { vertices.pop_back(); vector::iterator starting_iterator = next(vertices.begin()); Index min_vertex_index = min_element(starting_iterator, vertices.end()) - vertices.begin(); if (vertices.front() > vertices.at(min_vertex_index)) { rotate(vertices.begin(), vertices.begin() + min_vertex_index, vertices.end()); } vertices.push_back(vertices.front()); } /** * This function will determine if it is necessary to reverse the order of * a chain of vertices. E.g. * * 1 - 2 - 4 - 5 * * This chain will not need to be reversed because the end points have end * point 1 smaller than 5 * * This chain will need to be reversed * * 4 - 1 - 8 - 2 * * Because 2 is smaller than 4 * * If the chain has the same end points the next two vertices will be compared * * 1 - 2 - 3 - 4 - 1 * ^ ^ * | | * * The 2 is smaller than the 4 so there is no need to reverse the order. * * 4 - 9 - 8 - 6 - 4 * * In this case th 6 is smaller than the 9 so the order will be reversed. * **/ bool verticesShouldBeReversed_(vector& vertices) { size_t length = vertices.size(); size_t max_index = length / 2; for (size_t index = 0; index < max_index; ++index) { if (vertices.at(index) < vertices.at(length - 1 - index)) { return false; } else if (vertices.at(index) > vertices.at(length - 1 - index)) { return true; } } return false; } ReducedEdge::ReducedEdge(vector vertices) { assert(vertices.size() >= 2 && "Edge vertices must consist of at least two vertices."); // Smallest value always placed at the front of the vector // If we have a loop will arange the edge so that the smallest valued vertex // sits at both ends if (vertices.back() == vertices.front() && vertices.size() > 2) { moveVertexWithSmallestValueToEnds_(vertices); } if (verticesShouldBeReversed_(vertices)) { reverse(vertices.begin(), vertices.end()); } vertices_ = vertices; } vector ReducedEdge::expand() const { vector edges; for (size_t index = 0; index < (vertices_.size() - 1); ++index) { Edge ed(vertices_.at(index), vertices_.at(index + 1)); edges.push_back(ed); } return edges; } bool ReducedEdge::vertexExistInChain(const int& vertex) const { vector::const_iterator vertex_iterator = find(vertices_.begin(), vertices_.end(), vertex); return vertex_iterator != vertices_.end(); } bool ReducedEdge::operator==(const ReducedEdge& edge) const { if (edge.vertices_.size() != vertices_.size()) { return false; } for (size_t index = 0; index < vertices_.size(); ++index) { if (vertices_.at(index) != edge.vertices_.at(index)) { return false; } } return true; } bool ReducedEdge::operator!=(const ReducedEdge& edge) const { return !(*this == edge); } bool ReducedEdge::operator<(const ReducedEdge& edge) const { if (this->vertices_.front() < edge.vertices_.front()) { return true; } if (this->vertices_.front() > edge.vertices_.front()) { return false; } if (this->vertices_.back() < edge.vertices_.back()) { return true; } if (vertices_.size() < edge.vertices_.size()) { return true; } for (size_t index = 0; index < vertices_.size(); ++index) { if (vertices_.at(index) > edge.vertices_.at(index)) { return false; } } if (*this == edge) { return false; } return true; } bool ReducedEdge::operator<=(const ReducedEdge& edge) const { return (*this < edge || *this == edge); } bool ReducedEdge::operator>(const ReducedEdge& edge) const { return !(*this <= edge); } bool ReducedEdge::operator>=(const ReducedEdge& edge) const { return !(*this < edge); } ostream& operator<<(ostream& os, const ReducedEdge& edge) { os << "Vertices" << endl; for (auto vertex : edge.vertices_) { os << vertex << " "; } os << endl; return os; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/reducedgraph.cc000066400000000000000000000306451412152065700203350ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ // Standard includes #include #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/reducedgraph.h" using namespace std; namespace votca { namespace tools { class GraphNode; /****************************************************************************** * Internal Private Functions ******************************************************************************/ /** * \brief Function will compare a chain with a vector of chains * * If the one of the chains in the vector of chains is equivalent will return * true. A chain is simply a vector of integers where each integer represents * a vertex along an edge. The vertices appear in the chain in the same order * as they exist in a graph. **/ bool compareChainWithChains_(const vector& chain, const vector>& chains) { bool match = false; for (const vector& chain2 : chains) { if (chain2.size() == chain.size()) { match = true; for (size_t index = 0; index < chain.size(); ++index) { if (chain2.at(index) != chain.at(index)) { match = false; break; } } // Cycle vertices in each chain if (match) { return true; } } // Chains same size } return false; } /** * \brief Given a vector of Reduced Edges will find and return junctions if any * exist * * A junction is a vertex in a graph that has 3 or more edges eminating from it. * * Consider three reduced edges given by * * Edge Reduced Edge when Expanded (chain of vertices) * 1, 5 : 1 - 3 - 4 - 6 - 5 * 5, 10 : 5 - 2 - 10 * 5, 9 : 5 - 8 - 9 * * Graph: * * 1 - 3 - 4 - 6 - 5 - 2 - 10 * | * 8 - 9 * * Reduced Graph: * * 1 - 5 - 10 * | * 9 * * Here vertex 5 would be found to be a junction * * @param[in,out] - vector of reduced edges * @return - set of integers containing junctions **/ set getVertexJunctions_(const vector& reduced_edges) { unordered_map vertex_count; for (ReducedEdge reduced_edge : reduced_edges) { // if loop, increment value is double and the first index is skipped to // prevent over counting of the first number Index increment = 1; size_t index = 0; if (reduced_edge.loop()) { ++index; increment = 2; } vector chain = reduced_edge.getChain(); for (; index < chain.size(); ++index) { if (vertex_count.count(chain.at(index))) { vertex_count[chain.at(index)] += increment; } else { vertex_count[chain.at(index)] = increment; } } } set junctions; for (pair vertex_and_count : vertex_count) { if (vertex_and_count.second > 2) { junctions.insert(vertex_and_count.first); } } return junctions; } /** * \breif function adds an edge to an unordered_map and a vector if it is found * to not be a loop * * A loop is an edge that essentially makes a circle. In an edge that is a loop * will have both end points equal to the samve vertex. E.g. a reduced edge * like this: * * Edge Expanded edge (chain of vertices) * 2, 2 : 2 - 4 - 3 - 5 - 2 * * Graph * * 2 - 4 * | | * 5 - 3 * * Reduced Graph * * - 2 * |_| * * @param[in,out] - vector of edges, an edge is added to the vector if it is not * a loop * @param[in] - a reduced edge, the edge to be added * @param[in,out] - an unordered_map that stores the edge and its chain if it * is found to not be a loop **/ void addEdgeIfNotLoop_( vector& edges, const ReducedEdge reduced_edge, unordered_map>>& expanded_edges) { Edge edge(reduced_edge.getEndPoint1(), reduced_edge.getEndPoint2()); if (expanded_edges.count(edge)) { bool match = compareChainWithChains_(reduced_edge.getChain(), expanded_edges[edge]); if (!match) { expanded_edges[edge].push_back(reduced_edge.getChain()); } } else { expanded_edges[edge].push_back(reduced_edge.getChain()); } edges.push_back(edge); } /** * \brief This is a helper function used to help store the vertex chain in a * reproducable order * * Ordering chains in a reproducable manner enable quicker comparison between * chains. * * E.g. Given a chain * * End Point 1 * v * 1 - 4 - 3 - 5 - 6 - 2 - 1 * ^ * End Point 2 * * This function will ensure that it is reordered such that the next consecutive * number in the chain after end point 2 is the lower number, in this case the * two numbers that are compared are 4 and 2. The 2 is smaller so the chain is * reordered. * * 1 - 2 - 6 - 5 - 3 - 4 - 1 * * @param[in,out] - vector of integers containing the chain **/ void orderChainAfterInitialVertex_(vector& chain) { size_t ignore_first_and_last_vertex = 2; size_t total_number_to_parse = (chain.size() - ignore_first_and_last_vertex) / 2; bool reverse_vector = false; for (size_t count = 0; count < (total_number_to_parse); ++count) { if (chain.at(chain.size() - count - 1) < chain.at(count + 1)) { reverse_vector = true; break; } } if (reverse_vector) { reverse(chain.begin(), chain.end()); } } bool reorderAndStoreChainIfDoesNotExist_( vector& edges, unordered_map>>& expanded_edges, vector chain, Index vertex, size_t& chain_index) { Edge edge(vertex, vertex); edges.push_back(edge); vector new_chain; for (size_t index = 0; index < chain.size(); ++index) { if (((chain_index + index) % chain.size()) == 0) { ++chain_index; } Index new_chain_index = (chain_index + index) % chain.size(); new_chain.push_back(chain.at(new_chain_index)); } // Ensure that the new_chain is sorted so after the first vertex they are // ordered from smallest to largest orderChainAfterInitialVertex_(new_chain); bool match = compareChainWithChains_(new_chain, expanded_edges[edge]); if (!match) { expanded_edges[edge].push_back(new_chain); return true; } return false; } set getAllVertices_(const std::vector& reduced_edges) { set vertices; for (const ReducedEdge& reduced_edge : reduced_edges) { vector chain = reduced_edge.getChain(); for (const Index vertex : chain) { vertices.insert(vertex); } } return vertices; } set getAllConnectedVertices_( const unordered_map>>& expanded_edges) { set all_vertices; for (const auto& edge_and_chains : expanded_edges) { for (vector chain : edge_and_chains.second) { all_vertices.insert(chain.begin(), chain.end()); } } return all_vertices; } /****************************************************************************** * Private Class Methods ******************************************************************************/ void ReducedGraph::init_(vector reduced_edges, unordered_map nodes) { vector edges; nodes_ = nodes; junctions_ = getVertexJunctions_(reduced_edges); for (const ReducedEdge& reduced_edge : reduced_edges) { if (reduced_edge.loop() && junctions_.count(reduced_edge.getEndPoint1()) == 0) { vector chain = reduced_edge.getChain(); size_t chain_index = 0; bool edge_added = false; for (Index vertex : chain) { if (junctions_.count(vertex)) { edge_added = reorderAndStoreChainIfDoesNotExist_( edges, expanded_edges_, chain, vertex, chain_index); break; } ++chain_index; } if (!edge_added) { addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_); } } else { addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_); } } edge_container_ = EdgeContainer(edges); calcId_(); } /****************************************************************************** * Public Class Methods ******************************************************************************/ ReducedGraph::ReducedGraph(std::vector reduced_edges) { set vertices = getAllVertices_(reduced_edges); unordered_map nodes; for (const Index vertex : vertices) { GraphNode gn; nodes[vertex] = gn; } init_(reduced_edges, nodes); } ReducedGraph::ReducedGraph(std::vector reduced_edges, unordered_map nodes) { set vertices = getAllVertices_(reduced_edges); if (nodes.size() < vertices.size()) { throw invalid_argument( "The number of nodes passed into a reduced graph " "must be greater or equivalent to the number of vertices"); } for (const Index vertex : vertices) { if (nodes.count(vertex) == 0) { throw invalid_argument("A vertex is missing its corresponding node."); } } init_(reduced_edges, nodes); // Add all the nodes that are isolated for (pair& id_and_node : nodes) { if (vertices.count(id_and_node.first) == 0) { edge_container_.addVertex(id_and_node.first); } } } Graph ReducedGraph::expandGraph() const { vector all_expanded_edges; for (const pair>> edge_and_vertices : expanded_edges_) { vector> edges_local = expandEdge(edge_and_vertices.first); for (vector& edges : edges_local) { all_expanded_edges.insert(all_expanded_edges.end(), edges.begin(), edges.end()); } } return Graph(all_expanded_edges, nodes_); } vector> ReducedGraph::expandEdge(const Edge& edge) const { vector> all_edges; vector> chains = expanded_edges_.at(edge); for (vector vertices : chains) { vector edges; for (size_t index = 0; index < (vertices.size() - 1); ++index) { Edge edge_temp(vertices.at(index), vertices.at(index + 1)); edges.push_back(edge_temp); } all_edges.push_back(edges); } return all_edges; } vector> ReducedGraph::getNodes() const { vector vertices = edge_container_.getVertices(); vector> nodes; for (const Index vertex : vertices) { pair id_and_node(vertex, nodes_.at(vertex)); nodes.push_back(id_and_node); } set all_connected_vertices = getAllConnectedVertices_(expanded_edges_); // Grab the nodes that are not attached to any edges for (pair id_and_node : nodes_) { if (!all_connected_vertices.count(id_and_node.first)) { nodes.push_back(id_and_node); } } return nodes; } vector ReducedGraph::getVerticesDegree(Index degree) const { if (degree == 0) { set all_connected_vertices = getAllConnectedVertices_(expanded_edges_); vector vertices; for (const pair id_and_node : nodes_) { if (all_connected_vertices.count(id_and_node.first) == false) { vertices.push_back(id_and_node.first); } return vertices; } } return edge_container_.getVerticesDegree(degree); } ostream& operator<<(ostream& os, const ReducedGraph graph) { os << "Graph" << endl; for (const pair& id_and_node : graph.nodes_) { os << "Node " << id_and_node.first << endl; os << id_and_node.second << endl; } os << endl; os << graph.edge_container_ << endl; os << endl; os << "Expanded Edge Chains" << endl; for (const pair>>& edge_and_chains : graph.expanded_edges_) { for (const vector& chain : edge_and_chains.second) { for (const Index vertex : chain) { os << vertex << " "; } os << endl; } os << endl; } return os; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/spline.cc000066400000000000000000000037171412152065700171720ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/spline.h" namespace votca { namespace tools { using namespace std; Index Spline::GenerateGrid(double min, double max, double h) { Index vec_size = (Index)((max - min) / h + 1.00000001); _r.resize(vec_size); int i; double r_init; for (r_init = min, i = 0; i < vec_size - 1; r_init += h) { _r[i++] = r_init; } _r[i] = max; return _r.size(); } Eigen::VectorXd Spline::Calculate(const Eigen::VectorXd &x) { Eigen::VectorXd y(x.size()); for (Index i = 0; i < x.size(); ++i) { y(i) = Calculate(x(i)); } return y; } Eigen::VectorXd Spline::CalculateDerivative(const Eigen::VectorXd &x) { Eigen::VectorXd y(x.size()); for (Index i = 0; i < x.size(); ++i) { y(i) = CalculateDerivative(x(i)); } return y; } void Spline::Print(std::ostream &out, double interval) { for (double x = _r[0]; x < _r[_r.size() - 1]; x += interval) { out << x << " " << Calculate(x) << "\n"; } } Index Spline::getInterval(double r) { if (r < _r[0]) { return 0; } if (r > _r[_r.size() - 2]) { return _r.size() - 2; } Index i; for (i = 0; i < _r.size(); ++i) { if (_r[i] > r) { break; } } return i - 1; } double Spline::getGridPoint(int i) { if (i >= _r.size()) { return 0; } return _r[i]; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/table.cc000066400000000000000000000143531412152065700167650ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include #include #include // Third party includes #include #include // Local VOTCA includes #include "votca/tools/lexical_cast.h" #include "votca/tools/table.h" #include "votca/tools/tokenizer.h" namespace votca { namespace tools { using namespace boost; using namespace std; void Table::resize(Index N) { _x.conservativeResize(N); _y.conservativeResize(N); _flags.resize(N); if (_has_yerr) { _yerr.conservativeResize(N); } } void Table::Load(string filename) { ifstream in; in.open(filename); if (!in) { throw runtime_error(string("error, cannot open file ") + filename); } setErrorDetails("file " + filename); in >> *this; in.close(); } void Table::Save(string filename) const { ofstream out; out.open(filename); if (!out) { throw runtime_error(string("error, cannot open file ") + filename); } if (_has_comment) { string str = "# " + _comment_line; boost::replace_all(str, "\n", "\n# "); boost::replace_all(str, "\\n", "\n# "); out << str << endl; } out << (*this); out.close(); } void Table::clear(void) { _x.resize(0); _y.resize(0); _flags.resize(0); _yerr.resize(0); } double Table::getMaxY() const { return _y.maxCoeff(); } double Table::getMinY() const { return _y.minCoeff(); } double Table::getMaxX() const { return _x.maxCoeff(); } double Table::getMinX() const { return _x.minCoeff(); } // TODO: this functon is weired, reading occours twice, cleanup!! // TODO: modify function to work properly, when _has_yerr is true istream &operator>>(istream &in, Table &t) { size_t N = 0; bool bHasN = false; string line; Index line_number = 0; t.clear(); // read till the first data line while (tools::getline(in, line)) { line_number++; string conversion_error = t.getErrorDetails() + ", line " + boost::lexical_cast(line_number); // remove comments and xmgrace stuff line = line.substr(0, line.find("#")); line = line.substr(0, line.find("@")); // tokenize string and put it to vector Tokenizer tok(line, " \t"); vector tokens = tok.ToVector(); // skip empty lines if (tokens.size() == 0) { continue; } // if first line is only 1 token, it's the size if (tokens.size() == 1) { N = lexical_cast(tokens[0], conversion_error); bHasN = true; } else if (tokens.size() == 2) { // it's the first data line with 2 or 3 entries t.push_back(std::stod(tokens[0]), std::stod(tokens[1]), 'i'); } else if (tokens.size() > 2) { char flag = 'i'; string sflag = tokens.back(); if (sflag == "i" || sflag == "o" || sflag == "u") { flag = sflag[0]; } t.push_back(std::stod(tokens[0]), std::stod(tokens[1]), flag); } else { throw runtime_error("error, wrong table format"); } } // read the rest while (tools::getline(in, line)) { line_number++; string conversion_error = t.getErrorDetails() + ", line " + boost::lexical_cast(line_number); // remove comments and xmgrace stuff line = line.substr(0, line.find("#")); line = line.substr(0, line.find("@")); // tokenize string and put it to vector Tokenizer tok(line, " \t"); vector tokens; tok.ToVector(tokens); // skip empty lines if (tokens.size() == 0) { continue; } // it's a data line if (tokens.size() == 2) { t.push_back(std::stod(tokens[0]), std::stod(tokens[1]), 'i'); } else if (tokens.size() > 2) { char flag = 'i'; if (tokens[2] == "i" || tokens[2] == "o" || tokens[2] == "u") { flag = tokens[2][0]; } t.push_back(std::stod(tokens[0]), std::stod(tokens[1]), flag); } else { // otherwise error throw runtime_error("error, wrong table format"); } // was size given and did we read N values? if (bHasN) { if (--N == 0) { break; } } } return in; } void Table::GenerateGridSpacing(double min, double max, double spacing) { Index vec_size = (Index)((max - min) / spacing + 1.00000001); resize(vec_size); int i; double r_init; for (r_init = min, i = 0; i < vec_size - 1; r_init += spacing) { _x[i++] = r_init; } _x[i] = max; } void Table::Smooth(Index Nsmooth) { Index n_2 = size() - 2; if (n_2 < 0) { throw std::runtime_error( "Smoothing only works for arrays of size 3 and larger"); } for (Index i = 0; i < Nsmooth; i++) { _y.segment(1, n_2) = (0.25 * (_y.head(n_2) + 2 * _y.segment(1, n_2) + _y.tail(n_2))).eval(); } } std::ostream &operator<<(std::ostream &out, const Table &t) { // TODO: use a smarter precision guess, XXX.YYYYY=8, so 10 should be enough out.precision(10); if (t._has_yerr) { for (Index i = 0; i < t._x.size(); ++i) { out << t._x[i] << " " << t._y[i] << " " << t._yerr[i]; if (t._flags[i] == '\0' || t._flags[i] == ' ') { out << "\n"; } else { out << " " << t._flags[i] << "\n"; } } } else { for (Index i = 0; i < t._x.size(); ++i) { out << t._x[i] << " " << t._y[i]; if (t._flags[i] == '\0' || t._flags[i] == ' ') { out << "\n"; } else { out << " " << t._flags[i] << "\n"; } } } out << std::flush; return out; } // TODO: modify this function to be able to treat _has_yerr == true void Table::push_back(double x, double y, char flags) { Index n = size(); resize(n + 1); _x[n] = x; _y[n] = y; _flags[n] = flags; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/thread.cc000066400000000000000000000041541412152065700171430ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Local VOTCA includes #include "votca/tools/lexical_cast.h" #include "votca/tools/thread.h" #include "votca/tools/types.h" using namespace std; namespace votca { namespace tools { void *runwrapper(void *arg) { Thread *thread = (Thread *)(arg); thread->Run(); pthread_exit(nullptr); return nullptr; } Thread::Thread() = default; Thread::~Thread() = default; void Thread::Start() { pthread_attr_init(&_attr); /* * according to the POSIX standard, threads are created in the joinable state * by default * however, some platforms do not obey * * explicitly create the thread in the joinable state * the main program can then wait for the thread by calling * pthread_join(thread) * */ pthread_attr_setdetachstate(&_attr, PTHREAD_CREATE_JOINABLE); _finished = false; Index rc = pthread_create(&_thread, &_attr, runwrapper, static_cast(this)); if (rc) { throw std::runtime_error("ERROR; return code from pthread_create() is " + boost::lexical_cast(rc)); } } void Thread::WaitDone() { void *status; Index rc = pthread_join(_thread, &status); if (rc) { throw std::runtime_error("ERROR; return code from pthread_join() is " + boost::lexical_cast(rc)); } _finished = true; pthread_attr_destroy(&_attr); } bool Thread::IsFinished() const { return _finished; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/tokenizer.cc000066400000000000000000000027701412152065700177100ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/tokenizer.h" namespace votca { namespace tools { int wildcmp(const std::string &wild, const std::string &string) { return wildcmp(wild.c_str(), string.c_str()); } int wildcmp(const char *wild, const char *string) { // Written by Jack Handy - jakkhandy@hotmail.com const char *cp = nullptr, *mp = nullptr; while ((*string) && (*wild != '*')) { if ((*wild != *string) && (*wild != '?')) { return 0; } wild++; string++; } while (*string) { if (*wild == '*') { if (!*++wild) { return 1; } mp = wild; cp = string + 1; } else if ((*wild == *string) || (*wild == '?')) { wild++; string++; } else { wild = mp; string = cp++; } } while (*wild == '*') { wild++; } return !*wild; } } // namespace tools } // namespace votca tools-2021.2/src/libtools/version.cc000066400000000000000000000021651412152065700173610ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Local VOTCA includes #include "votca/tools/version.h" #include "votca/tools/votca_tools_config.h" namespace votca { namespace tools { // defines gitversion #include "gitversion.h" static const std::string version_str = std::string(TOOLS_VERSION) + " " + gitversion + " (compiled " __DATE__ ", " __TIME__ ")"; const std::string &ToolsVersionStr() { return version_str; } } // namespace tools } // namespace votca tools-2021.2/src/tests/000077500000000000000000000000001412152065700146745ustar00rootroot00000000000000tools-2021.2/src/tests/CMakeLists.txt000066400000000000000000000040211412152065700174310ustar00rootroot00000000000000find_package(Boost 1.53.0 REQUIRED COMPONENTS unit_test_framework) # Each test listed in Alphabetical order foreach(PROG test_calculator test_constants test_correlate test_crosscorrelate test_cubicspline test_datacollection test_edge_base test_edgecontainer test_elements test_filesystem test_floatingpointcomparison test_graphalgorithm test_graph_base test_graph_bf_visitor test_graph_df_visitor test_graphdistvisitor test_graphnode test_graphvisitor test_histogramnew test_identity test_linalg test_name test_objectfactory test_property test_reducededge test_reducedgraph test_structureparameters test_table test_thread test_tokenizer test_random test_akimaspline test_linspline test_unitconverter test_eigenio_matrixmarket) file(GLOB ${PROG}_SOURCES ${PROG}*.cc) add_executable(unit_${PROG} ${${PROG}_SOURCES}) target_compile_definitions(unit_${PROG} PRIVATE TOOLS_TEST_DATA_FOLDER="${CMAKE_CURRENT_SOURCE_DIR}/DataFiles") target_link_libraries(unit_${PROG} votca_tools Boost::unit_test_framework Boost::filesystem) target_compile_definitions(unit_${PROG} PRIVATE BOOST_TEST_DYN_LINK) add_test(unit_${PROG} unit_${PROG}) # run tests for tools (for coverage) as well set_tests_properties(unit_${PROG} PROPERTIES LABELS "tools;votca;unit") if(VALGRIND_FOUND) # https://github.com/votca/tools/issues/268 # tests seem to trigger a 'Address 0x0 is not stack'd, malloc'd or (recently) free'd' in valgrind set(BROCKEN_MKL_TEST test_crosscorrelate test_cubicspline test_linalg test_linspline) if(MKL_FOUND AND PROG IN_LIST BROCKEN_MKL_TEST) continue() endif() add_test(NAME memory_${PROG} COMMAND "${VALGRIND_EXECUTABLE}" --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes --error-exitcode=1 $) set_tests_properties(memory_${PROG} PROPERTIES LABELS "tools;votca;memory") endif(VALGRIND_FOUND) endforeach(PROG) tools-2021.2/src/tests/DataFiles/000077500000000000000000000000001412152065700165305ustar00rootroot00000000000000tools-2021.2/src/tests/DataFiles/eigenio_matrixmarket/000077500000000000000000000000001412152065700227375ustar00rootroot00000000000000tools-2021.2/src/tests/DataFiles/eigenio_matrixmarket/eigen_matrix.mm000066400000000000000000000001641412152065700257460ustar00rootroot00000000000000%%MatrixMarket matrix array real general % A 4x3 dense matrix 4 3 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0tools-2021.2/src/tests/DataFiles/eigenio_matrixmarket/eigen_vector.mm000066400000000000000000000001251412152065700257410ustar00rootroot00000000000000%%MatrixMarket matrix array real general % v 4 entry dense vector 4 1 1.0 2.0 3.0 4.0tools-2021.2/src/tests/DataFiles/linalg/000077500000000000000000000000001412152065700177765ustar00rootroot00000000000000tools-2021.2/src/tests/DataFiles/linalg/H.mm000066400000000000000000000062311412152065700205220ustar00rootroot00000000000000%%MatrixMarket matrix array real general 17 17 13.2968 -1.99797 0 0 0 -0.265757 0 0 0 -0.0909339 -0.147467 -0.0909339 -0.147467 -0.0909339 -0.147467 -0.0909339 -0.147467 -1.99797 -4.04413 0 0 0 -3.49418 0 0 0 -0.994581 -1.89399 -0.994581 -1.89399 -0.994581 -1.89399 -0.994581 -1.89399 0 0 -3.93849 0 0 0 -2.25634 0 0 -0.780336 -0.599314 -0.780336 -0.599314 0.780336 0.599314 0.780336 0.599314 0 0 0 -3.5 0 0 0 -2.25634 0 -0.780336 -0.599314 0.780336 0.599314 0.780336 0.599314 -0.780336 -0.599314 0 0 0 0 -3 0 0 0 -2.25634 -0.780336 -0.599314 0.780336 0.599314 -0.780336 -0.599314 0.780336 0.599314 -0.265757 -3.49418 0 0 0 -2.9 0 0 0 -1.38139 -2.47289 -1.38139 -2.47289 -1.38139 -2.47289 -1.38139 -2.47289 0 0 -2.25634 0 0 0 -2.8 0 0 -1.03641 -0.999519 -1.03641 -0.999519 1.03641 0.999519 1.03641 0.999519 0 0 0 -2.25634 0 0 0 -2.7 0 -1.03641 -0.999519 1.03641 0.999519 1.03641 0.999519 -1.03641 -0.999519 0 0 0 0 -2.25634 0 0 0 -2.6 -1.03641 -0.999519 1.03641 0.999519 -1.03641 -0.999519 1.03641 0.999519 -0.0909339 -0.994581 -0.780336 -0.780336 -0.780336 -1.38139 -1.03641 -1.03641 -1.03641 -2.5 -2.29509 -0.0552941 -0.512094 -0.0552941 -0.512094 -0.0552941 -0.512094 -0.147467 -1.89399 -0.599314 -0.599314 -0.599314 -2.47289 -0.999519 -0.999519 -0.999519 -2.29509 -2.4 -0.512094 -1.30279 -0.512094 -1.30279 -0.512094 -1.30279 -0.0909339 -0.994581 -0.780336 0.780336 0.780336 -1.38139 -1.03641 1.03641 1.03641 -0.0552941 -0.512094 -2.3 -2.29509 -0.0552941 -0.512094 -0.0552941 -0.512094 -0.147467 -1.89399 -0.599314 0.599314 0.599314 -2.47289 -0.999519 0.999519 0.999519 -0.512094 -1.30279 -2.29509 -2.2 -0.512094 -1.30279 -0.512094 -1.30279 -0.0909339 -0.994581 0.780336 0.780336 -0.780336 -1.38139 1.03641 1.03641 -1.03641 -0.0552941 -0.512094 -0.0552941 -0.512094 -1.9 -2.29509 -0.0552941 -0.512094 -0.147467 -1.89399 0.599314 0.599314 -0.599314 -2.47289 0.999519 0.999519 -0.999519 -0.512094 -1.30279 -0.512094 -1.30279 -2.29509 -1.8 -0.512094 -1.30279 -0.0909339 -0.994581 0.780336 -0.780336 0.780336 -1.38139 1.03641 -1.03641 1.03641 -0.0552941 -0.512094 -0.0552941 -0.512094 -0.0552941 -0.512094 -1.5 -2.29509 -0.147467 -1.89399 0.599314 -0.599314 0.599314 -2.47289 0.999519 -0.999519 0.999519 -0.512094 -1.30279 -0.512094 -1.30279 -0.512094 -1.30279 -2.29509 -1tools-2021.2/src/tests/test_akimaspline.cc000066400000000000000000000047561412152065700205530ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE akimaspline_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/akimaspline.h" using namespace votca::tools; BOOST_AUTO_TEST_SUITE(akimaspline_test) BOOST_AUTO_TEST_CASE(interpolate_test) { int size = 80; Eigen::VectorXd x = Eigen::VectorXd::Zero(size); Eigen::VectorXd y = Eigen::VectorXd::Zero(size); for (int i = 0; i < size; ++i) { x(i) = 0.25 * i; y(i) = std::sin(x(i)); } AkimaSpline cspline; cspline.setBCInt(0); cspline.Interpolate(x, y); Eigen::VectorXd rs = Eigen::VectorXd::Zero(10); rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0; Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10); values_ref << 0.434362, 0.452449, 0.717761, 0.681639, 0.564937, 0.388734, 0.783279, 0.52316, 0, 0; Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10); derivatives_ref << 0.906562, 0.902216, 0.698382, 0.747323, 0.818045, 0.918909, 0.615268, 0.854075, 1.02038, 1.02038; Eigen::VectorXd values = cspline.Calculate(rs); Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs); bool equal_val = values_ref.isApprox(values, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << values.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5); if (!equal_derivative) { std::cout << "result value" << std::endl; std::cout << derivatives.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << derivatives_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_derivative, true); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_calculator.cc000066400000000000000000000147241412152065700204030ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE calculator_test // Standard includes #include // Third party includes #include #include // Local VOTCA includes #include "votca/tools/calculator.h" using namespace ::votca; BOOST_AUTO_TEST_SUITE(calculator_test) BOOST_AUTO_TEST_CASE(load_defaults_test) { class TestCalc : public tools::Calculator { public: std::string Identify() override { return "testcalc"; } void Initialize(const tools::Property &user_options) override { // Create folder for test const char dir_path[] = "calculators"; boost::filesystem::path dir(dir_path); boost::filesystem::create_directory(dir); dir.append("xml"); boost::filesystem::create_directory(dir); std::ofstream defaults("calculators/xml/testcalc.xml"); defaults << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << "\n" << ""; defaults.close(); // Load and check the options tools::Property final_opt = LoadDefaultsAndUpdateWithUserOptions("calculators", user_options); std::string prop0 = final_opt.get("option0").as(); Index prop1 = final_opt.get("option1").as(); double prop2 = final_opt.get("option2").as(); std::string prop3 = final_opt.get("option3.nested").as(); double prop4 = final_opt.get("option4").as(); bool prop5 = final_opt.get("option5").as(); std::string prop6 = final_opt.get("option6").as(); const tools::Property &prop7 = final_opt.get("option7"); std::string prop71 = prop7.get("option71").as(); Index prop8 = final_opt.get("option8").as(); Index prop9 = final_opt.get("option9").as(); BOOST_CHECK_EQUAL(prop0, "foo"); BOOST_CHECK_EQUAL(prop1, 42); BOOST_CHECK_CLOSE(prop2, -3.141592, 0.00001); BOOST_CHECK_EQUAL(prop3, "nested_value"); BOOST_CHECK_CLOSE(prop4, 3.141592, 0.00001); BOOST_CHECK_EQUAL(prop5, true); BOOST_CHECK_EQUAL(prop6, "1,3"); BOOST_CHECK_EQUAL(prop71, "none"); BOOST_CHECK_EQUAL(prop8, 8); BOOST_CHECK_EQUAL(prop9, 9); } }; setenv("VOTCASHARE", ".", 1); char buff[FILENAME_MAX]; std::cout << "WARNING: the VOTCASHARE env. variable has been updated to " << getcwd(buff, FILENAME_MAX) << "\n"; // Generate user options tools::Property user_options; tools::Property &opt = user_options.add("options", ""); tools::Property &opt_test = opt.add("testcalc", ""); opt_test.add("option1", "42"); tools::Property &new_prop = opt_test.add("option3", ""); new_prop.add("nested", "nested_value"); opt_test.add("option8", ""); opt_test.add("option9", "9"); TestCalc test_calc; test_calc.Initialize(user_options); } BOOST_AUTO_TEST_CASE(test_choices) { class TestChoices : public tools::Calculator { std::string _line; public: std::string Identify() override { return "testchoices"; } void SetOption(const std::string &line) { _line = line; } void Initialize(const tools::Property &user_options) override { // Create folder for test const char dir_path[] = "calculators"; boost::filesystem::path dir(dir_path); boost::filesystem::create_directory(dir); dir.append("xml"); boost::filesystem::create_directory(dir); std::ofstream defaults("calculators/xml/testchoices.xml"); defaults << "\n" << "\n" << _line << "\n" << ""; defaults.close(); // Load and check the options tools::Property final_opt = LoadDefaultsAndUpdateWithUserOptions("calculators", user_options); std::cout << final_opt << "\n"; } }; setenv("VOTCASHARE", ".", 1); char buff[FILENAME_MAX]; std::cout << "WARNING: the VOTCASHARE env. variable has been updated to " << getcwd(buff, FILENAME_MAX) << "\n"; // Generate user options tools::Property user_options; tools::Property &opt = user_options.add("options", ""); opt.add("testchoices", ""); TestChoices test1, test2, test3, test4, test5, test6, test7; test1.SetOption("boom\n"); test2.SetOption("some\n"); test3.SetOption("3.14\n"); test4.SetOption("-2\n"); test5.SetOption("-3.14\n"); test6.SetOption("tux\n"); test7.SetOption("\n"); BOOST_CHECK_THROW(test1.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test2.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test3.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test4.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test5.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test6.Initialize(user_options), std::runtime_error); BOOST_CHECK_THROW(test7.Initialize(user_options), std::runtime_error); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_constants.cc000066400000000000000000000037151412152065700202640ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE constants_test // Third party includes #include // Local VOTCA includes #include "votca/tools/constants.h" using namespace votca::tools; using namespace votca::tools::conv; using namespace votca::tools::topology_constants; BOOST_AUTO_TEST_SUITE(constants_test) BOOST_AUTO_TEST_CASE(constants_test1) { BOOST_CHECK_CLOSE(Pi, boost::math::constants::pi(), 5E-5); BOOST_CHECK_CLOSE(kB, 8.617332478E-5, 5E-5); BOOST_CHECK_CLOSE(hbar, 6.5821192815E-16, 5E-5); BOOST_CHECK_CLOSE(bohr2nm, 0.052917721092, 5E-5); BOOST_CHECK_CLOSE(nm2bohr, 18.897259886, 5E-5); BOOST_CHECK_CLOSE(ang2bohr, 1.8897259886, 5E-5); BOOST_CHECK_CLOSE(bohr2ang, 1.0 / 1.8897259886, 5E-5); BOOST_CHECK_CLOSE(nm2ang, 10.0, 5E-5); BOOST_CHECK_CLOSE(ang2nm, 0.1, 5E-5); BOOST_CHECK_CLOSE(hrt2ev, 27.21138602, 5E-5); BOOST_CHECK_CLOSE(ev2hrt, 1.0 / 27.21138602, 5E-5); BOOST_CHECK_CLOSE(ev2kj_per_mol, 96.485, 5E-5); BOOST_CHECK_EQUAL(unassigned_element, "unassigned"); BOOST_CHECK_EQUAL(unassigned_bead_type, "unassigned"); BOOST_CHECK_EQUAL(unassigned_residue_type, "unassigned"); BOOST_CHECK_EQUAL(unassigned_molecule_type, "unassigned"); BOOST_CHECK_EQUAL(unassigned_residue_id, -1); BOOST_CHECK_EQUAL(unassigned_molecule_id, -1); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_correlate.cc000066400000000000000000000032251412152065700202240ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE correlate_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/correlate.h" using namespace votca; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(correlate_test) BOOST_AUTO_TEST_CASE(correlation_test) { DataCollection d; DataCollection::array* x = d.CreateArray("first"); x->resize(50); for (Index i = 0; i < Index(x->size()); i++) { (*x)[i] = double(i) * 0.5; } DataCollection::array* y = d.CreateArray("second"); *y = *x; DataCollection::array* z = d.CreateArray("third"); *z = *x; std::reverse(z->begin(), z->end()); DataCollection::selection s; s.push_back(x); s.push_back(y); s.push_back(z); Correlate cor; cor.CalcCorrelations(s); BOOST_CHECK_CLOSE(cor.getData()[0], 1, 1e-9); BOOST_CHECK_CLOSE(cor.getData()[1], -1, 1e-9); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_crosscorrelate.cc000066400000000000000000000046231412152065700213010ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE crosscorrelate_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/crosscorrelate.h" using namespace votca; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(crosscorrelate_test) BOOST_AUTO_TEST_CASE(crosscorrelate) { DataCollection d; DataCollection::array* x = d.CreateArray("first"); x->resize(50); for (Index i = 0; i < Index(x->size()); i++) { (*x)[i] = std::sin(double(i) * 0.5) + std::cos(double(i) * 1.5); } DataCollection::selection s; s.push_back(x); CrossCorrelate cor; cor.AutoCorrelate(s); std::vector& corr = cor.getData(); Eigen::Map m(corr.data(), corr.size()); Eigen::VectorXd corr_ref = Eigen::VectorXd::Zero(50); corr_ref << 1, 0.467627, -0.228828, -0.0618146, 0.270531, -0.24973, -0.956717, -0.674499, 0.117233, 0.172174, -0.246548, 0.0477983, 0.84253, 0.842251, 0.0484615, -0.245153, 0.170656, 0.11432, -0.672333, -0.951362, -0.250719, 0.264426, -0.0608222, -0.22103, 0.466958, 0.989178, 0.466958, -0.22103, -0.0608222, 0.264426, -0.250719, -0.951362, -0.672333, 0.11432, 0.170656, -0.245153, 0.0484615, 0.842251, 0.84253, 0.0477983, -0.246548, 0.172174, 0.117233, -0.674499, -0.956717, -0.24973, 0.270531, -0.0618146, -0.228828, 0.467627; bool equal_val = corr_ref.isApprox(m, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << m.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << corr_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_cubicspline.cc000066400000000000000000000142701412152065700205460ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE cubicspline_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/cubicspline.h" using namespace votca::tools; BOOST_AUTO_TEST_SUITE(cubicspline_test) BOOST_AUTO_TEST_CASE(spline_grid_high) { CubicSpline cspline; cspline.setBCInt(0); cspline.GenerateGrid(0, 9, 2); Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(5); values_ref << 0, 2, 4, 6, 9; bool equal_val = values_ref.isApprox(cspline.getX(), 1e-5); BOOST_CHECK_EQUAL(equal_val, true); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << cspline.getX().transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } } BOOST_AUTO_TEST_CASE(spline_grid_low) { CubicSpline cspline; cspline.setBCInt(0); cspline.GenerateGrid(0, 7, 2); Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(4); values_ref << 0, 2, 4, 7; bool equal_val = values_ref.isApprox(cspline.getX(), 1e-5); BOOST_CHECK_EQUAL(equal_val, true); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << cspline.getX().transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } } BOOST_AUTO_TEST_CASE(cubicspline_fit_test) { votca::Index size = 80; Eigen::VectorXd x = Eigen::VectorXd::Zero(size); Eigen::VectorXd y = Eigen::VectorXd::Zero(size); for (votca::Index i = 0; i < size; ++i) { x(i) = 0.25 * double(i); y(i) = std::sin(x(i)); } CubicSpline cspline; cspline.setBCInt(0); cspline.GenerateGrid(0.4, 0.6, 0.1); Eigen::VectorXd gridpoints_ref = Eigen::VectorXd::Zero(3); gridpoints_ref << 0.4, 0.5, 0.6; bool grid_check = cspline.getX().isApprox(gridpoints_ref, 1e-5); BOOST_CHECK_EQUAL(grid_check, true); if (!grid_check) { std::cout << "result value" << std::endl; std::cout << cspline.getX().transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << gridpoints_ref.transpose() << std::endl; } cspline.Fit(x, y); Eigen::VectorXd rs = Eigen::VectorXd::Zero(10); rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0; Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10); values_ref << 0.311213, 0.310352, 0.296153, 0.298304, 0.304759, 0.313364, 0.291851, 0.30691, 0.33058, 0.33058; Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10); derivatives_ref << -0.0430277, -0.0430282, -0.0430231, -0.0430267, -0.0430313, -0.0430272, -0.0430128, -0.0430308, -0.04306, -0.04306; Eigen::VectorXd values = cspline.Calculate(rs); Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs); bool equal_val = values_ref.isApprox(values, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << values.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5); if (!equal_derivative) { std::cout << "result value" << std::endl; std::cout << derivatives.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << derivatives_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_derivative, true); } BOOST_AUTO_TEST_CASE(cubicspline_interpolate_test) { int size = 80; Eigen::VectorXd x = Eigen::VectorXd::Zero(size); Eigen::VectorXd y = Eigen::VectorXd::Zero(size); for (int i = 0; i < size; ++i) { x(i) = 0.25 * i; y(i) = std::sin(x(i)); } CubicSpline cspline; cspline.setBCInt(0); cspline.Interpolate(x, y); Eigen::VectorXd rs = Eigen::VectorXd::Zero(10); rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0; Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10); values_ref << 0.434964, 0.452886, 0.717353, 0.681639, 0.564637, 0.389415, 0.78332, 0.522684, 0, 0; Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10); derivatives_ref << 0.900494, 0.891601, 0.69661, 0.731673, 0.825305, 0.921091, 0.621663, 0.852451, 0.999978, 0.999978; Eigen::VectorXd values = cspline.Calculate(rs); Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs); bool equal_val = values_ref.isApprox(values, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << values.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5); if (!equal_derivative) { std::cout << "result value" << std::endl; std::cout << derivatives.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << derivatives_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_derivative, true); } BOOST_AUTO_TEST_CASE(cubicspline_matrix_test) { CubicSpline cspline; cspline.setBCInt(0); cspline.GenerateGrid(0.4, 0.6, 0.1); Eigen::MatrixXd A = Eigen::MatrixXd::Zero(1, 6); Eigen::MatrixXd Aref = Eigen::MatrixXd::Zero(1, 6); Aref << 0.0, -9.0, 10.0, 0.0, -0.03333333, -0.01666667; cspline.AddToFitMatrix(A, 0.5, 0, 0, 1.0, 1.0); bool equalMatrix = Aref.isApprox(A, 1e-5); if (!equalMatrix) { std::cout << "result A" << std::endl; std::cout << A << std::endl; std::cout << "ref A" << std::endl; std::cout << Aref << std::endl; } BOOST_CHECK_EQUAL(equalMatrix, true); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_datacollection.cc000066400000000000000000000147401412152065700212350ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE datacollection_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/datacollection.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(datacollection_test) BOOST_AUTO_TEST_CASE(constructors_test) { DataCollection datacollection; } /** * Check to see if the arrays are created correctly **/ BOOST_AUTO_TEST_CASE(test_createarray) { DataCollection datacollection; string name_tag1 = "x positions"; string name_tag2 = "y positions"; string name_tag3 = "z positions"; datacollection.CreateArray(name_tag1); datacollection.CreateArray(name_tag2); datacollection.CreateArray(name_tag3); BOOST_CHECK_EQUAL(datacollection.size(), 3); } BOOST_AUTO_TEST_CASE(test_getname) { DataCollection datacollection; string name_tag1 = "x positions"; string name_tag2 = "y positions"; string name_tag3 = "z positions"; auto xpositions = datacollection.CreateArray(name_tag1); auto ypositions = datacollection.CreateArray(name_tag2); auto zpositions = datacollection.CreateArray(name_tag3); bool x_compare_name = !name_tag1.compare(xpositions->getName()); bool y_compare_name = !name_tag2.compare(ypositions->getName()); bool z_compare_name = !name_tag3.compare(zpositions->getName()); BOOST_CHECK(x_compare_name); BOOST_CHECK(y_compare_name); BOOST_CHECK(z_compare_name); } BOOST_AUTO_TEST_CASE(test_data) { DataCollection datacollection; string name_tag1 = "x positions"; string name_tag2 = "y positions"; string name_tag3 = "z positions"; auto xpositions = datacollection.CreateArray(name_tag1); auto ypositions = datacollection.CreateArray(name_tag2); auto zpositions = datacollection.CreateArray(name_tag3); bool x_compare_name = !name_tag1.compare(xpositions->getName()); bool y_compare_name = !name_tag2.compare(ypositions->getName()); bool z_compare_name = !name_tag3.compare(zpositions->getName()); BOOST_CHECK(x_compare_name); BOOST_CHECK(y_compare_name); BOOST_CHECK(z_compare_name); xpositions->push_back(1); xpositions->push_back(3); ypositions->push_back(-4); ypositions->push_back(4); ypositions->push_back(4); zpositions->push_back(5); BOOST_CHECK_EQUAL(datacollection.Data().at(0)->size(), 2); BOOST_CHECK_EQUAL(datacollection.Data().at(1)->size(), 3); BOOST_CHECK_EQUAL(datacollection.Data().at(2)->size(), 1); BOOST_CHECK_EQUAL(datacollection.Data().at(0)->at(0), 1); BOOST_CHECK_EQUAL(datacollection.Data().at(0)->at(1), 3); BOOST_CHECK_EQUAL(datacollection.Data().at(1)->at(0), -4); BOOST_CHECK_EQUAL(datacollection.Data().at(1)->at(1), 4); BOOST_CHECK_EQUAL(datacollection.Data().at(1)->at(2), 4); BOOST_CHECK_EQUAL(datacollection.Data().at(2)->at(0), 5); } BOOST_AUTO_TEST_CASE(test_bracket) { DataCollection datacollection; string name_tag1 = "x positions"; string name_tag2 = "y positions"; string name_tag3 = "z positions"; auto xpositions = datacollection.CreateArray(name_tag1); auto ypositions = datacollection.CreateArray(name_tag2); auto zpositions = datacollection.CreateArray(name_tag3); bool x_compare_name = !name_tag1.compare(xpositions->getName()); bool y_compare_name = !name_tag2.compare(ypositions->getName()); bool z_compare_name = !name_tag3.compare(zpositions->getName()); BOOST_CHECK(x_compare_name); BOOST_CHECK(y_compare_name); BOOST_CHECK(z_compare_name); xpositions->push_back(1); xpositions->push_back(3); ypositions->push_back(-4); ypositions->push_back(4); ypositions->push_back(4); zpositions->push_back(5); BOOST_CHECK_EQUAL(datacollection[0].size(), 2); BOOST_CHECK_EQUAL(datacollection[1].size(), 3); BOOST_CHECK_EQUAL(datacollection[2].size(), 1); BOOST_CHECK_EQUAL(datacollection[0].at(0), 1); BOOST_CHECK_EQUAL(datacollection[0].at(1), 3); BOOST_CHECK_EQUAL(datacollection[1].at(0), -4); BOOST_CHECK_EQUAL(datacollection[1].at(1), 4); BOOST_CHECK_EQUAL(datacollection[1].at(2), 4); BOOST_CHECK_EQUAL(datacollection[2].at(0), 5); } BOOST_AUTO_TEST_CASE(test_arraybyname) { DataCollection datacollection; string name_tag1 = "x positions"; string name_tag2 = "y positions"; string name_tag3 = "z positions"; auto xpositions = datacollection.CreateArray(name_tag1); auto ypositions = datacollection.CreateArray(name_tag2); auto zpositions = datacollection.CreateArray(name_tag3); bool x_compare_name = !name_tag1.compare(xpositions->getName()); bool y_compare_name = !name_tag2.compare(ypositions->getName()); bool z_compare_name = !name_tag3.compare(zpositions->getName()); BOOST_CHECK(x_compare_name); BOOST_CHECK(y_compare_name); BOOST_CHECK(z_compare_name); xpositions->push_back(1); xpositions->push_back(2); xpositions->push_back(3); ypositions->push_back(-4); ypositions->push_back(4); ypositions->push_back(4); zpositions->push_back(5); zpositions->push_back(-5); zpositions->push_back(5); x_compare_name = !name_tag1.compare(datacollection.Data().at(0)->getName()); y_compare_name = !name_tag2.compare(datacollection.Data().at(1)->getName()); z_compare_name = !name_tag3.compare(datacollection.Data().at(2)->getName()); auto xPosArray = datacollection.ArrayByName(name_tag1); BOOST_CHECK_EQUAL(xPosArray->at(0), 1); BOOST_CHECK_EQUAL(xPosArray->at(1), 2); BOOST_CHECK_EQUAL(xPosArray->at(2), 3); auto yPosArray = datacollection.ArrayByName(name_tag2); BOOST_CHECK_EQUAL(yPosArray->at(0), -4); BOOST_CHECK_EQUAL(yPosArray->at(1), 4); BOOST_CHECK_EQUAL(yPosArray->at(2), 4); auto zPosArray = datacollection.ArrayByName(name_tag3); BOOST_CHECK_EQUAL(zPosArray->at(0), 5); BOOST_CHECK_EQUAL(zPosArray->at(1), -5); BOOST_CHECK_EQUAL(zPosArray->at(2), 5); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_edge_base.cc000066400000000000000000000044711412152065700201460ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE edge_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/edge.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(edge_test) BOOST_AUTO_TEST_CASE(constructors_test) { Edge ed(2, 3); } BOOST_AUTO_TEST_CASE(ouput_test) { Edge ed(2, 3); cout << ed << endl; } BOOST_AUTO_TEST_CASE(equivalence_test) { Edge ed(2, 3); Edge ed2(2, 4); Edge ed3(3, 2); BOOST_CHECK_EQUAL(ed, ed); BOOST_CHECK_EQUAL(ed, ed3); BOOST_CHECK_EQUAL((ed == ed2), false); } BOOST_AUTO_TEST_CASE(nequivalence_test) { Edge ed(2, 3); Edge ed2(2, 4); BOOST_CHECK_EQUAL(ed != ed2, true); BOOST_CHECK_EQUAL((ed != ed), false); } BOOST_AUTO_TEST_CASE(getter_test) { Edge ed(2, 3); BOOST_CHECK_EQUAL(ed.getEndPoint1(), 2); BOOST_CHECK_EQUAL(ed.getEndPoint2(), 3); Edge ed2(3, 2); BOOST_CHECK_EQUAL(ed.getEndPoint1(), 2); BOOST_CHECK_EQUAL(ed.getEndPoint2(), 3); } BOOST_AUTO_TEST_CASE(less_test) { Edge ed1(1, 2); Edge ed2(2, 1); BOOST_CHECK_EQUAL(!(ed1 < ed2), true); Edge ed3(3, 0); BOOST_CHECK_EQUAL(ed3 < ed1, true); Edge ed4(1, 5); BOOST_CHECK_EQUAL(ed1 < ed4, true); Edge ed5(2, 2); BOOST_CHECK_EQUAL(ed4 < ed5, true); } BOOST_AUTO_TEST_CASE(greater_test) { Edge ed1(1, 2); Edge ed2(2, 1); BOOST_CHECK_EQUAL(!(ed1 > ed2), true); Edge ed3(3, 0); BOOST_CHECK_EQUAL(!(ed3 > ed1), true); } BOOST_AUTO_TEST_CASE(hash_key_test) { set e_set; Edge ed(23, 43); e_set.insert(ed); unordered_map e_map; e_map[2] = ed; } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_edgecontainer.cc000066400000000000000000000143071412152065700210560ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE edgecontainer_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/edgecontainer.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(edgecontainer_test) BOOST_AUTO_TEST_CASE(create_test) { EdgeContainer edCo; Edge ed(1, 2); EdgeContainer edCo2(ed); Edge ed2(3, 4); vector eds{ed, ed2}; EdgeContainer edCo3(eds); } BOOST_AUTO_TEST_CASE(getdegree_test) { { Edge ed(1, 2); Edge ed2(2, 3); vector eds{ed, ed2}; EdgeContainer edge_container(eds); BOOST_CHECK(edge_container.getDegree(1) == 1); BOOST_CHECK(edge_container.getDegree(2) == 2); BOOST_CHECK(edge_container.getDegree(3) == 1); BOOST_CHECK_THROW(edge_container.getDegree(4), invalid_argument); } { // _ // / \ 3 // \ / | // 1 - 4 - 8 - 5 // Edge ed1(1, 4); Edge ed2(1, 1); Edge ed3(4, 8); Edge ed4(8, 3); Edge ed5(8, 5); vector edges{ed1, ed2, ed3, ed4, ed5}; EdgeContainer edge_container(edges); BOOST_CHECK_EQUAL(edge_container.getDegree(1), 3); BOOST_CHECK_EQUAL(edge_container.getDegree(4), 2); BOOST_CHECK_EQUAL(edge_container.getDegree(8), 3); BOOST_CHECK_EQUAL(edge_container.getDegree(3), 1); BOOST_CHECK_EQUAL(edge_container.getDegree(5), 1); } } BOOST_AUTO_TEST_CASE(edgeexist_test) { Edge ed(1, 2); Edge ed2(2, 3); vector eds{ed, ed2}; EdgeContainer edCo(eds); BOOST_CHECK(edCo.edgeExist(ed)); BOOST_CHECK(edCo.edgeExist(ed2)); Edge ed3(3, 4); BOOST_CHECK(!edCo.edgeExist(ed3)); } BOOST_AUTO_TEST_CASE(vertexexist_test) { Edge ed(1, 2); Edge ed2(2, 3); vector eds{ed, ed2}; EdgeContainer edCo(eds); BOOST_CHECK(edCo.vertexExist(1)); BOOST_CHECK(edCo.vertexExist(2)); BOOST_CHECK(edCo.vertexExist(3)); BOOST_CHECK(!edCo.vertexExist(4)); } BOOST_AUTO_TEST_CASE(addedge_test) { Edge ed(1, 2); Edge ed2(2, 3); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed2); BOOST_CHECK(edCo.edgeExist(ed)); BOOST_CHECK(edCo.edgeExist(ed2)); // Should be able to add the same edge more than once edCo.addEdge(ed); } BOOST_AUTO_TEST_CASE(getedges_test) { Edge ed(1, 2); Edge ed2(2, 3); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed2); auto vec_ed = edCo.getEdges(); bool ed_found = false; bool ed2_found = false; for (auto e1 : vec_ed) { if (e1 == ed) { ed_found = true; } if (e1 == ed2) { ed2_found = true; } } BOOST_CHECK(ed_found); BOOST_CHECK(ed2_found); // Should be able to add an edge more than once edCo.addEdge(ed); vec_ed = edCo.getEdges(); votca::Index ed_count = 0; votca::Index ed2_count = 0; for (auto e1 : vec_ed) { if (e1 == ed) { ++ed_count; } if (e1 == ed2) { ++ed2_count; } } BOOST_CHECK_EQUAL(ed_count, 2); BOOST_CHECK_EQUAL(ed2_count, 1); } BOOST_AUTO_TEST_CASE(getvertices_test) { Edge ed(1, 2); Edge ed2(2, 3); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed2); auto vec_vert = edCo.getVertices(); bool vert_found = false; bool vert2_found = false; bool vert3_found = false; for (auto ver : vec_vert) { if (ver == 1) { vert_found = true; } if (ver == 2) { vert2_found = true; } if (ver == 3) { vert3_found = true; } } BOOST_CHECK(vert_found); BOOST_CHECK(vert2_found); BOOST_CHECK(vert3_found); } BOOST_AUTO_TEST_CASE(getneighvertices_test) { // // 1 - 2 - 3 // Edge ed(1, 2); Edge ed2(2, 3); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed2); auto vec_vert = edCo.getNeighVertices(1); BOOST_CHECK_EQUAL(vec_vert.at(0), 2); vec_vert = edCo.getNeighVertices(2); bool vert_found = false; bool vert3_found = false; for (auto ver : vec_vert) { if (ver == 1) { vert_found = true; } if (ver == 3) { vert3_found = true; } } BOOST_CHECK(vert_found); BOOST_CHECK(vert3_found); } BOOST_AUTO_TEST_CASE(getneighedges) { Edge ed(1, 2); Edge ed2(2, 3); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed2); auto vec_edgs = edCo.getNeighEdges(1); BOOST_CHECK_EQUAL(vec_edgs.at(0), ed); vec_edgs = edCo.getNeighEdges(2); bool edge_found = false; bool edge2_found = false; for (auto e1 : vec_edgs) { if (e1 == ed) { edge_found = true; } if (e1 == ed2) { edge2_found = true; } } BOOST_CHECK(edge_found); BOOST_CHECK(edge2_found); // Should be able to add the same edge more than once Edge ed3(3, 4); edCo.addEdge(ed); edCo.addEdge(ed3); vec_edgs = edCo.getNeighEdges(1); BOOST_CHECK_EQUAL(vec_edgs.size(), 2); BOOST_CHECK_EQUAL(vec_edgs.at(0), ed); BOOST_CHECK_EQUAL(vec_edgs.at(1), ed); vec_edgs = edCo.getNeighEdges(2); BOOST_CHECK_EQUAL(vec_edgs.size(), 3); votca::Index edge_count = 0; votca::Index edge_count2 = 0; for (auto e1 : vec_edgs) { if (e1 == ed) { ++edge_count; } if (e1 == ed2) { ++edge_count2; } } BOOST_CHECK_EQUAL(edge_count, 2); BOOST_CHECK_EQUAL(edge_count2, 1); } BOOST_AUTO_TEST_CASE(getmaxdegree) { Edge ed(1, 2); Edge ed1(2, 3); Edge ed2(2, 4); Edge ed3(3, 5); EdgeContainer edCo; edCo.addEdge(ed); edCo.addEdge(ed1); edCo.addEdge(ed2); edCo.addEdge(ed3); votca::Index maxD = edCo.getMaxDegree(); BOOST_CHECK_EQUAL(maxD, 3); edCo.addEdge(ed); maxD = edCo.getMaxDegree(); BOOST_CHECK_EQUAL(maxD, 4); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_eigenio_matrixmarket.cc000066400000000000000000000062271412152065700224600ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE eigenio_matrixmarket // Third party includes #include // Local VOTCA includes #include "votca/tools/eigenio_matrixmarket.h" #include "votca/tools/votca_tools_config.h" #include using namespace votca::tools; BOOST_AUTO_TEST_SUITE(eigenio_matrixmarket) BOOST_AUTO_TEST_CASE(readvector_test) { Eigen::VectorXd ref = Eigen::VectorXd::Zero(4); ref << 1.0, 2.0, 3.0, 4.0; std::cout << std::string(TOOLS_TEST_DATA_FOLDER) << std::endl; Eigen::VectorXd readin = EigenIO_MatrixMarket::ReadVector(std::string(TOOLS_TEST_DATA_FOLDER) + "/eigenio_matrixmarket/eigen_vector.mm"); bool check = ref.isApprox(readin, 1e-5); if (!check) { std::cout << "ref" << std::endl; std::cout << ref.transpose() << std::endl; std::cout << "result" << std::endl; std::cout << readin.transpose() << std::endl; } BOOST_CHECK(check); } BOOST_AUTO_TEST_CASE(writevector_test) { Eigen::VectorXd test = Eigen::VectorXd::Random(5); EigenIO_MatrixMarket::WriteVector("VectorRandom.mm", test); Eigen::VectorXd readin = EigenIO_MatrixMarket::ReadVector("VectorRandom.mm"); bool check = test.isApprox(readin, 1e-5); if (!check) { std::cout << "ref" << std::endl; std::cout << test.transpose() << std::endl; std::cout << "result" << std::endl; std::cout << readin.transpose() << std::endl; } BOOST_CHECK(check); } BOOST_AUTO_TEST_CASE(readmatrix_test) { Eigen::MatrixXd ref = Eigen::MatrixXd::Zero(4, 3); ref << 1.0, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0; Eigen::MatrixXd readin = EigenIO_MatrixMarket::ReadMatrix(std::string(TOOLS_TEST_DATA_FOLDER) + "/eigenio_matrixmarket/eigen_matrix.mm"); bool check = ref.isApprox(readin, 1e-5); if (!check) { std::cout << "ref" << std::endl; std::cout << ref << std::endl; std::cout << "result" << std::endl; std::cout << readin << std::endl; } BOOST_CHECK(check); } BOOST_AUTO_TEST_CASE(writematrix_test) { Eigen::MatrixXd test = Eigen::MatrixXd::Random(4, 3); EigenIO_MatrixMarket::WriteMatrix("MatrixRandom.mm", test); Eigen::MatrixXd readin = EigenIO_MatrixMarket::ReadMatrix("MatrixRandom.mm"); bool check = test.isApprox(readin, 1e-5); if (!check) { std::cout << "ref" << std::endl; std::cout << test << std::endl; std::cout << "result" << std::endl; std::cout << readin << std::endl; } BOOST_CHECK(check); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_elements.cc000066400000000000000000000047441412152065700200670ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE elements_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/elements.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(elements_test) BOOST_AUTO_TEST_CASE(constructors_test) { Elements ele; } BOOST_AUTO_TEST_CASE(accessors_test) { Elements ele; BOOST_CHECK_EQUAL(ele.getVdWChelpG("H"), 1.45); BOOST_CHECK_THROW(ele.getVdWChelpG("Blah"), runtime_error); BOOST_CHECK_EQUAL(ele.getMass("K"), 39.098); BOOST_CHECK_EQUAL(ele.getEleNum("Li"), 3); BOOST_CHECK_EQUAL(ele.getNucCrg("H"), 1); BOOST_CHECK_EQUAL(ele.getEleName(17), "Cl"); BOOST_CHECK_EQUAL(ele.getEleShort("MAGNESIUM"), "Mg"); BOOST_CHECK_EQUAL(ele.getEleFull("Ge"), "GERMANIUM"); BOOST_CHECK_EQUAL(ele.getVdWMK("F"), 1.35); BOOST_CHECK_THROW(ele.getVdWMK("Pb"), runtime_error); BOOST_CHECK_CLOSE(ele.getCovRad("Cl", "ang"), 1.02, 1e-3); BOOST_CHECK_CLOSE(ele.getCovRad("Cl", "nm"), 0.102, 1e-3); BOOST_CHECK_THROW(ele.getCovRad("Cl", "Blah"), runtime_error); BOOST_CHECK_EQUAL(ele.getPolarizability("F"), 0.440e-3); BOOST_CHECK_THROW(ele.getPolarizability("Pb"), runtime_error); BOOST_CHECK(ele.isMassAssociatedWithElement(12.01, 0.01)); BOOST_CHECK(!ele.isMassAssociatedWithElement(12.51, 0.01)); BOOST_CHECK_EQUAL("C", ele.getEleShortClosestInMass(12.01, 0.01)); BOOST_CHECK(ele.isElement("Carbon")); BOOST_CHECK(ele.isElement("CARBON")); BOOST_CHECK(ele.isElement("C")); BOOST_CHECK(!ele.isElement("1C")); BOOST_CHECK(ele.isEleFull("Carbon")); BOOST_CHECK(ele.isEleFull("CARBON")); BOOST_CHECK(!ele.isEleFull("C")); BOOST_CHECK(ele.isEleShort("C")); BOOST_CHECK(!ele.isEleShort("Carbon")); BOOST_CHECK(!ele.isEleShort("CARBON")); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_filesystem.cc000066400000000000000000000037451412152065700204370ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/filesystem.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(filesystem_test) BOOST_AUTO_TEST_CASE(FileExists) { std::string filename = "blablablablablabla.txt"; BOOST_CHECK_EQUAL(filesystem::FileExists(filename), false); std::string filename2 = "test_exist.txt"; std::ofstream outfile(filename2); outfile << "my text here!" << std::endl; outfile.close(); BOOST_CHECK_EQUAL(filesystem::FileExists(filename2), true); } BOOST_AUTO_TEST_CASE(GetFileExtension) { std::string filename = "bla.txt"; BOOST_CHECK_EQUAL(filesystem::GetFileExtension(filename), "txt"); std::string filename2 = "blubb"; BOOST_CHECK_EQUAL(filesystem::GetFileExtension(filename2), ""); std::string filename3 = "a.b.c.d.gro"; BOOST_CHECK_EQUAL(filesystem::GetFileExtension(filename3), "gro"); } BOOST_AUTO_TEST_CASE(GetFileBase) { std::string filename = "bla.txt"; BOOST_CHECK_EQUAL(filesystem::GetFileBase(filename), "bla"); std::string filename2 = "blubb"; BOOST_CHECK_EQUAL(filesystem::GetFileBase(filename2), "blubb"); std::string filename3 = "a.b.c.d.gro"; BOOST_CHECK_EQUAL(filesystem::GetFileBase(filename3), "a.b.c.d"); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_floatingpointcomparison.cc000066400000000000000000000023351412152065700232150ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE floatingpointcomparison_test // Third party includes #include // Local VOTCA includes #include "votca/tools/floatingpointcomparison.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(floatingpointcomparison_test) BOOST_AUTO_TEST_CASE(comparison_test) { double var1 = 1.000; double var2 = 1.010; BOOST_CHECK(isApproximatelyEqual(var1, var2, 0.1)); BOOST_CHECK(isApproximatelyEqual(var1, var2, 0.01)); BOOST_CHECK(!isApproximatelyEqual(var1, var2, 0.001)); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graph_base.cc000066400000000000000000000402351412152065700203410ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graph_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graphnode.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(graph_test) BOOST_AUTO_TEST_CASE(constructors_test) { Graph g; } /** * \brief Test on isolated nodes method * * The isolated nodes method is meant to grab any nodes that have no edges, as * in they exist as islands within the context of the graph. */ BOOST_AUTO_TEST_CASE(isolatednodes_test) { { /// Here gn is a single node as is thus isolated vector vec_ed; GraphNode gn; unordered_map m_gn; m_gn[0] = gn; Graph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); BOOST_CHECK_EQUAL(iso_gn.at(0).first, 0); } { /// In this test case gn, gn1 and gn2 are all islands no edges have been /// specified to connect them. Calling getIsolatedNodes() thus returns all /// three of them. vector vec_ed; GraphNode gn; GraphNode gn1; GraphNode gn2; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; Graph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); bool node0 = false; bool node1 = false; bool node2 = false; for (auto n_pr : iso_gn) { if (n_pr.first == 0) { node0 = true; } if (n_pr.first == 1) { node1 = true; } if (n_pr.first == 2) { node2 = true; } } BOOST_CHECK(node0); BOOST_CHECK(node1); BOOST_CHECK(node2); } { /// In this test both node 0 and 1 share an edge and are no longer isolated /// however node 2 is isolated, a call getIsolatedNodes() only returns node /// 2 vector vec_ed; Edge ed(0, 1); vec_ed.push_back(ed); GraphNode gn; GraphNode gn1; GraphNode gn2; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; Graph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); bool node0 = false; bool node1 = false; bool node2 = false; for (auto n_pr : iso_gn) { if (n_pr.first == 0) { node0 = true; } if (n_pr.first == 1) { node1 = true; } if (n_pr.first == 2) { node2 = true; } } BOOST_CHECK(!node0); BOOST_CHECK(!node1); BOOST_CHECK(node2); } /// In this test the junctions of the graph are returned, the junctions /// consist of vertices of three or more connections { /// In this test both node 0 and 1 share an edge there are no junctions Edge ed(0, 1); vector vec_ed{ed}; GraphNode gn; GraphNode gn1; GraphNode gn2; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; Graph g(vec_ed, m_gn); auto junctions = g.getJunctions(); BOOST_CHECK(!junctions.size()); } /// In this test the junctions of the graph are returned, the junctions /// consist of vertices of three or more connections { /// In this test both node 0 and 1 share an edge there are no junctions Edge ed(0, 2); Edge ed2(1, 2); Edge ed3(3, 2); vector vec_ed{ed, ed2, ed3}; GraphNode gn; GraphNode gn1; GraphNode gn2; GraphNode gn3; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; Graph g(vec_ed, m_gn); auto junctions = g.getJunctions(); BOOST_CHECK_EQUAL(junctions.size(), 1); BOOST_CHECK_EQUAL(junctions.at(0), 2); } } BOOST_AUTO_TEST_CASE(junctions_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; Graph g(vec_ed, m_gn); // A junction should consist of a vertex with degree of 3 or more auto junctions = g.getJunctions(); BOOST_CHECK(junctions.size() == 1); BOOST_CHECK_EQUAL(junctions.at(0), 2); } BOOST_AUTO_TEST_CASE(get_edges_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; Graph g(vec_ed, m_gn); auto edges = g.getEdges(); bool ed0_found = false; bool ed1_found = false; bool ed2_found = false; bool ed3_found = false; for (auto ed_temp : edges) { if (ed_temp == ed) { ed0_found = true; } if (ed_temp == ed1) { ed1_found = true; } if (ed_temp == ed2) { ed2_found = true; } if (ed_temp == ed3) { ed3_found = true; } } BOOST_CHECK(ed0_found); BOOST_CHECK(ed1_found); BOOST_CHECK(ed2_found); BOOST_CHECK(ed3_found); } BOOST_AUTO_TEST_CASE(get_vertices_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; Graph g(vec_ed, m_gn); auto vertices = g.getVertices(); vector vertices_found(5, false); for (auto vertex : vertices) { if (vertex == 0) { vertices_found.at(0) = true; } if (vertex == 1) { vertices_found.at(1) = true; } if (vertex == 2) { vertices_found.at(2) = true; } if (vertex == 3) { vertices_found.at(3) = true; } if (vertex == 4) { vertices_found.at(4) = true; } } for (auto found : vertices_found) { BOOST_CHECK(found); } } BOOST_AUTO_TEST_CASE(compare_test) { { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; Graph g(vec_ed, m_gn); auto vec_pr = g.getNodes(); sort(vec_pr.begin(), vec_pr.end(), cmpVertNodePair); BOOST_CHECK_EQUAL(vec_pr.at(0).first, 0); BOOST_CHECK_EQUAL(vec_pr.at(1).first, 1); BOOST_CHECK_EQUAL(vec_pr.at(2).first, 2); BOOST_CHECK_EQUAL(vec_pr.at(3).first, 3); BOOST_CHECK_EQUAL(vec_pr.at(4).first, 4); } { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); /// Only difference is here where we have rearanged the nodes unordered_map m_gn; m_gn[4] = gn; m_gn[1] = gn1; m_gn[3] = gn2; m_gn[2] = gn3; m_gn[0] = gn4; Graph g(vec_ed, m_gn); auto vec_pr = g.getNodes(); sort(vec_pr.begin(), vec_pr.end(), cmpVertNodePair); BOOST_CHECK_EQUAL(vec_pr.at(0).first, 4); BOOST_CHECK_EQUAL(vec_pr.at(1).first, 1); BOOST_CHECK_EQUAL(vec_pr.at(2).first, 3); BOOST_CHECK_EQUAL(vec_pr.at(3).first, 2); BOOST_CHECK_EQUAL(vec_pr.at(4).first, 0); } } BOOST_AUTO_TEST_CASE(neighbornode_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; /// Here the graph nodes are assigne to different vertices m_gn[0] = gn4; m_gn[1] = gn1; m_gn[2] = gn3; m_gn[3] = gn2; m_gn[4] = gn; Graph g(vec_ed, m_gn); auto neigh1 = g.getNeighNodes(0); BOOST_CHECK_EQUAL(neigh1.size(), 1); bool neigh1_found1 = neigh1.at(0).second == gn1; BOOST_CHECK(neigh1_found1); auto neigh2 = g.getNeighNodes(1); BOOST_CHECK_EQUAL(neigh2.size(), 2); bool neigh2_found1 = false; bool neigh2_found2 = false; for (auto neigh_pr : neigh2) { if (neigh_pr.second == gn4) { neigh2_found1 = true; } if (neigh_pr.second == gn3) { neigh2_found2 = true; } } BOOST_CHECK(neigh2_found1); BOOST_CHECK(neigh2_found2); auto neigh3 = g.getNeighNodes(2); BOOST_CHECK_EQUAL(neigh3.size(), 3); bool neigh3_found1 = false; bool neigh3_found2 = false; bool neigh3_found3 = false; for (auto neigh_pr : neigh3) { if (neigh_pr.second == gn1) { neigh3_found1 = true; } if (neigh_pr.second == gn2) { neigh3_found2 = true; } if (neigh_pr.second == gn) { neigh3_found3 = true; } } BOOST_CHECK(neigh3_found1); BOOST_CHECK(neigh3_found2); BOOST_CHECK(neigh3_found3); auto neigh4 = g.getNeighNodes(3); BOOST_CHECK_EQUAL(neigh4.size(), 1); bool neigh4_found1 = neigh4.at(0).second == gn3; BOOST_CHECK(neigh4_found1); auto neigh5 = g.getNeighNodes(4); BOOST_CHECK_EQUAL(neigh5.size(), 1); bool neigh5_found1 = neigh5.at(0).second == gn3; BOOST_CHECK(neigh5_found1); } /** * \brief Equivalence test * * Here we demonstrate how the equivalence test works it is purely dependendent * on whether the contents of the graphnodes in the graph contain the same * information. */ BOOST_AUTO_TEST_CASE(id_test) { { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; vector vec_ed; Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed1); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; /// Here the graph nodes are assigne to different vertices m_gn[4] = gn; m_gn[1] = gn1; m_gn[3] = gn2; m_gn[2] = gn3; m_gn[0] = gn4; Graph g(vec_ed, m_gn); /// Here is what the string id of the graph should look like string str = "a0b1c2d3e4"; string s_id = g.getId(); BOOST_CHECK_EQUAL(s_id, str); Graph g2(vec_ed, m_gn); BOOST_CHECK(g == g2); /// Here we switch up which vertices contain which graphnodes and show that /// the graph id is the same. This is because the vertex ids are not used to /// create the id and neither the edges. Only the contens in the graphnodes m_gn[1] = gn3; m_gn[2] = gn1; Graph g3(vec_ed, m_gn); BOOST_CHECK(g == g3); GraphNode gn5(int_vals3, double_vals, str_vals); m_gn[5] = gn5; Graph g4(vec_ed, m_gn); BOOST_CHECK(g != g4); } } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graph_bf_visitor.cc000066400000000000000000000113341412152065700215730ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graph_bf_visitor_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graph.h" #include "votca/tools/graph_bf_visitor.h" #include "votca/tools/graphnode.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(graph_bf_visitor_test) BOOST_AUTO_TEST_CASE(constructor_test) { Graph_BF_Visitor gb_v; } BOOST_AUTO_TEST_CASE(basic_test) { // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; Graph g(edges, nodes); Graph_BF_Visitor gb_v; BOOST_CHECK(gb_v.queEmpty()); BOOST_CHECK_THROW(gb_v.exec(g, ed), runtime_error); // Default starts with node index 0 gb_v.initialize(g); BOOST_CHECK_EQUAL(gb_v.queEmpty(), false); // No exception should be thrown at this point Edge ed1 = gb_v.nextEdge(g); BOOST_CHECK_EQUAL(ed, ed1); gb_v.exec(g, ed1); BOOST_CHECK(gb_v.queEmpty()); // Show which vertices have been explored auto exploredV = gb_v.getExploredVertices(); bool v0 = false; bool v1 = false; for (auto ver : exploredV) { if (ver == 0) { v0 = true; } if (ver == 1) { v1 = true; } } // Both vertices should have been explored BOOST_CHECK(v0); BOOST_CHECK(v1); } BOOST_AUTO_TEST_CASE(basic_test2) { // This tests demonstrates that this particular graph visitor // explores the graph in a breadth first, and first in first out order // // 0 -> 1 -> 2 // | // v // 3 // | // v // 4 // // Create edge Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(0, 3); Edge ed3(3, 4); vector edges; edges.push_back(ed); edges.push_back(ed1); edges.push_back(ed2); edges.push_back(ed3); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; GraphNode gn4; GraphNode gn5; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; nodes[3] = gn4; nodes[4] = gn5; Graph g(edges, nodes); Graph_BF_Visitor gb_v; BOOST_CHECK(gb_v.queEmpty()); BOOST_CHECK_THROW(gb_v.exec(g, ed), runtime_error); // Default starts with node index 0 gb_v.initialize(g); BOOST_CHECK_EQUAL(gb_v.queEmpty(), false); // No exception should be thrown at this point // First two edges found should be ed and ed2 vector temp; Edge ed5 = gb_v.nextEdge(g); temp.push_back(ed5); gb_v.exec(g, ed5); ed5 = gb_v.nextEdge(g); temp.push_back(ed5); bool found_ed = false; bool found_ed2 = false; for (auto temp_ed : temp) { if (temp_ed == ed) { found_ed = true; } if (temp_ed == ed2) { found_ed2 = true; } } BOOST_CHECK(found_ed); BOOST_CHECK(found_ed2); // Next two edges are ed1 and ed3 they are equal distance apart from the // starting vertex so the order does not matter. temp.clear(); gb_v.exec(g, ed5); ed5 = gb_v.nextEdge(g); temp.push_back(ed5); gb_v.exec(g, ed5); ed5 = gb_v.nextEdge(g); temp.push_back(ed5); bool found_ed1 = false; bool found_ed3 = false; for (auto temp_ed : temp) { if (temp_ed == ed1) { found_ed1 = true; } if (temp_ed == ed3) { found_ed3 = true; } } BOOST_CHECK(found_ed1); BOOST_CHECK(found_ed3); gb_v.exec(g, ed5); BOOST_CHECK(gb_v.queEmpty()); // Show which vertices have been explored auto exploredV = gb_v.getExploredVertices(); bool v0 = false; bool v1 = false; bool v2 = false; bool v3 = false; bool v4 = false; for (auto ver : exploredV) { if (ver == 0) { v0 = true; } if (ver == 1) { v1 = true; } if (ver == 2) { v2 = true; } if (ver == 3) { v3 = true; } if (ver == 4) { v4 = true; } } // All 5 vertices should have been explored BOOST_CHECK(v0); BOOST_CHECK(v1); BOOST_CHECK(v2); BOOST_CHECK(v3); BOOST_CHECK(v4); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graph_df_visitor.cc000066400000000000000000000111631412152065700215750ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graph_df_visitor_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graph.h" #include "votca/tools/graph_df_visitor.h" #include "votca/tools/graphnode.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(graph_df_visitor_test) BOOST_AUTO_TEST_CASE(constructor_test) { Graph_DF_Visitor gd_v; } BOOST_AUTO_TEST_CASE(basic_test) { // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; Graph g(edges, nodes); Graph_DF_Visitor gd_v; BOOST_CHECK(gd_v.queEmpty()); BOOST_CHECK_THROW(gd_v.exec(g, ed), runtime_error); // Default starts with node index 0 gd_v.initialize(g); BOOST_CHECK_EQUAL(gd_v.queEmpty(), false); // No exception should be thrown at this point Edge ed1 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed, ed1); gd_v.exec(g, ed1); BOOST_CHECK(gd_v.queEmpty()); // Show which vertices have been explored auto exploredV = gd_v.getExploredVertices(); bool v0 = false; bool v1 = false; for (auto ver : exploredV) { if (ver == 0) { v0 = true; } if (ver == 1) { v1 = true; } } // Both vertices should have been explored BOOST_CHECK(v0); BOOST_CHECK(v1); } BOOST_AUTO_TEST_CASE(basic_test2) { // This tests demonstrates that this particular graph visitor // explores the graph in a depth first, and last in first out order // // 0 -> 1 -> 2 // | // v // 3 // | // v // 4 // // Create edge Edge ed0(0, 1); Edge ed1(1, 2); Edge ed2(0, 3); Edge ed3(3, 4); vector edges; edges.push_back(ed0); edges.push_back(ed1); edges.push_back(ed2); edges.push_back(ed3); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; GraphNode gn4; GraphNode gn5; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; nodes[3] = gn4; nodes[4] = gn5; Graph g(edges, nodes); Graph_DF_Visitor gd_v; BOOST_CHECK(gd_v.queEmpty()); BOOST_CHECK_THROW(gd_v.exec(g, ed0), runtime_error); // Default starts with node index 0 gd_v.initialize(g); BOOST_CHECK_EQUAL(gd_v.queEmpty(), false); // No exception should be thrown at this point // The visitor can progress down either branch it does not matter which one // it just matters that it completely explores the chosen branch before // exploring the next branch Edge ed5 = gd_v.nextEdge(g); gd_v.exec(g, ed5); if (ed5 == ed2) { ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed3, ed5); gd_v.exec(g, ed5); ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed0, ed5); gd_v.exec(g, ed5); ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed1, ed5); gd_v.exec(g, ed5); } else if (ed5 == ed0) { ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed1, ed5); gd_v.exec(g, ed5); ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed2, ed5); gd_v.exec(g, ed5); ed5 = gd_v.nextEdge(g); BOOST_CHECK_EQUAL(ed3, ed5); gd_v.exec(g, ed5); } else { // one of the staring edges should eithe be ed0 or ed2 BOOST_CHECK(false); } BOOST_CHECK(gd_v.queEmpty()); // Show which vertices have been explored auto exploredV = gd_v.getExploredVertices(); bool v0 = false; bool v1 = false; bool v2 = false; bool v3 = false; bool v4 = false; for (auto ver : exploredV) { if (ver == 0) { v0 = true; } if (ver == 1) { v1 = true; } if (ver == 2) { v2 = true; } if (ver == 3) { v3 = true; } if (ver == 4) { v4 = true; } } // All 5 vertices should have been explored BOOST_CHECK(v0); BOOST_CHECK(v1); BOOST_CHECK(v2); BOOST_CHECK(v3); BOOST_CHECK(v4); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graphalgorithm.cc000066400000000000000000000431771412152065700212660ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graphalgorithm_test // Standard includes #include #include #include #include #include #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/edge.h" #include "votca/tools/graph.h" #include "votca/tools/graph_bf_visitor.h" #include "votca/tools/graphalgorithm.h" #include "votca/tools/graphdistvisitor.h" #include "votca/tools/graphnode.h" #include "votca/tools/reducedgraph.h" using namespace std; using namespace votca::tools; using namespace boost; using namespace boost::unit_test; BOOST_AUTO_TEST_SUITE(graphalgorithm_test) BOOST_AUTO_TEST_CASE(single_network_algorithm_test) { { // In this test we add two nodes and an edge describing // their connection thus the singleNetwork function will // return true. // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; Graph g(edges, nodes); Graph_BF_Visitor gb_v; BOOST_CHECK(gb_v.queEmpty()); // gb_v.exec(g,ed); BOOST_CHECK_THROW(gb_v.exec(g, ed), runtime_error); bool single_n = singleNetwork(g, gb_v); cerr << "is single network " << single_n << endl; BOOST_CHECK(single_n); BOOST_CHECK(gb_v.queEmpty()); Graph_BF_Visitor gb_v2; gb_v2.setStartingVertex(2); BOOST_CHECK_THROW(singleNetwork(g, gb_v2), invalid_argument); } { // In this test we add 3 nodes but only one edge // this means that one of the nodes will not be // attached to the other two. Thus the singleNetwork // function should return false. // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; Graph g(edges, nodes); Graph_BF_Visitor gb_v; BOOST_CHECK(gb_v.queEmpty()); BOOST_CHECK_THROW(gb_v.exec(g, ed), runtime_error); bool single_n = singleNetwork(g, gb_v); BOOST_CHECK(!single_n); BOOST_CHECK(gb_v.queEmpty()); } } BOOST_AUTO_TEST_CASE(decouple_isolated_subgraphs_test) { // 1 - 2 - 3 // | | 8 - 9 - 10 11 // 4 - 5 - 6 -7 Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(2, 4); Edge ed4(4, 5); Edge ed5(3, 5); Edge ed6(5, 6); Edge ed7(6, 7); Edge ed8(8, 9); Edge ed9(9, 10); vector edges{ed1, ed2, ed3, ed4, ed5, ed6, ed7, ed8, ed9}; unordered_map nodes; for (votca::Index index = 1; index < 12; ++index) { GraphNode gn; nodes[index] = gn; } Graph graph(edges, nodes); vector sub_graphs = decoupleIsolatedSubGraphs(graph); BOOST_CHECK_EQUAL(sub_graphs.size(), 3); unordered_map vertices_sub_graph1; vertices_sub_graph1[1] = false; vertices_sub_graph1[2] = false; vertices_sub_graph1[3] = false; vertices_sub_graph1[4] = false; vertices_sub_graph1[5] = false; vertices_sub_graph1[6] = false; vertices_sub_graph1[7] = false; unordered_map vertices_sub_graph2; vertices_sub_graph2[8] = false; vertices_sub_graph2[9] = false; vertices_sub_graph2[10] = false; unordered_map vertices_sub_graph3; vertices_sub_graph3[11] = false; for (const Graph& sub_graph : sub_graphs) { const vector vertices = sub_graph.getVertices(); if (vertices_sub_graph1.count(vertices.at(0))) { for (const votca::Index& vertex : vertices) { if (vertices_sub_graph1.count(vertex)) { vertices_sub_graph1.at(vertex) = true; } } } else if (vertices_sub_graph2.count(vertices.at(0))) { for (const votca::Index& vertex : vertices) { if (vertices_sub_graph2.count(vertex)) { vertices_sub_graph2.at(vertex) = true; } } } else if (vertices_sub_graph3.count(vertices.at(0))) { for (const votca::Index& vertex : vertices) { if (vertices_sub_graph3.count(vertex)) { vertices_sub_graph3.at(vertex) = true; } } } } BOOST_CHECK_EQUAL(vertices_sub_graph1.size(), 7); for (const pair& found : vertices_sub_graph1) { BOOST_CHECK(found.second); } BOOST_CHECK_EQUAL(vertices_sub_graph2.size(), 3); for (const pair& found : vertices_sub_graph2) { BOOST_CHECK(found.second); } BOOST_CHECK_EQUAL(vertices_sub_graph3.size(), 1); for (const pair& found : vertices_sub_graph3) { BOOST_CHECK(found.second); } } BOOST_AUTO_TEST_CASE(reduceGraph_algorithm_test) { { // Create edge // 2 // | // 0 - 1 - 3 // | // 4 Edge ed1(0, 1); Edge ed2(1, 2); Edge ed3(1, 3); Edge ed4(1, 4); // // 5 - 6 // Edge ed5(5, 6); vector edges; edges.push_back(ed1); edges.push_back(ed2); edges.push_back(ed3); edges.push_back(ed4); edges.push_back(ed5); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; GraphNode gn4; GraphNode gn5; GraphNode gn6; GraphNode gn7; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; nodes[3] = gn4; nodes[4] = gn5; nodes[5] = gn6; nodes[6] = gn7; Graph g(edges, nodes); ReducedGraph reduced_g = reduceGraph(g); vector edges2 = reduced_g.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 5); vector found_edges(5, false); for (Edge& edge : edges2) { if (edge == ed1) { found_edges.at(0) = true; } if (edge == ed2) { found_edges.at(1) = true; } if (edge == ed3) { found_edges.at(2) = true; } if (edge == ed4) { found_edges.at(3) = true; } if (edge == ed5) { found_edges.at(4) = true; } } for (const bool& found : found_edges) { BOOST_CHECK(found); } } { // Test that the reduced graph handles loops correctly // // 1 - 2 // | | // 4 - 3 // // Should reduce this to // // 1 - 1 // vector edges{Edge(1, 2), Edge(2, 3), Edge(3, 4), Edge(1, 4)}; unordered_map nodes; for (votca::Index vertex = 1; vertex <= 4; ++vertex) { GraphNode gn; nodes[vertex] = gn; } Graph graph(edges, nodes); ReducedGraph reduced_graph = reduceGraph(graph); vector edges2 = reduced_graph.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 1); Edge ed_check(1, 1); BOOST_CHECK_EQUAL(edges2.at(0), ed_check); vector> edges3 = reduced_graph.expandEdge(ed_check); BOOST_CHECK_EQUAL(edges3.size(), 1); BOOST_CHECK_EQUAL(edges3.at(0).size(), 4); vector found_edge(4, false); for (const Edge& edge : edges3.at(0)) { if (edge == edges.at(0)) { found_edge.at(0) = true; } if (edge == edges.at(1)) { found_edge.at(1) = true; } if (edge == edges.at(2)) { found_edge.at(2) = true; } if (edge == edges.at(3)) { found_edge.at(3) = true; } } for (bool found : found_edge) { BOOST_CHECK(found); } } { // Test that the reduced graph handles loop and edge correctly // // 1 - 2 // | | // 4 - 3 - 5 - 6 // // Should reduce this to // // 3 - 3 // 3 - 6 // vector edges{Edge(1, 2), Edge(2, 3), Edge(3, 4), Edge(1, 4), Edge(3, 5), Edge(5, 6)}; unordered_map nodes; for (votca::Index vertex = 1; vertex <= 6; ++vertex) { GraphNode gn; nodes[vertex] = gn; } Graph graph(edges, nodes); ReducedGraph reduced_graph = reduceGraph(graph); vector edges2 = reduced_graph.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 2); cout << "EDGE CHECK **************************************" << endl; Edge ed3_3(3, 3); Edge ed3_6(3, 6); bool found_edge3_3 = false; bool found_edge3_6 = false; for (Edge ed : edges2) { if (ed == ed3_3) { found_edge3_3 = true; } else if (ed == ed3_6) { found_edge3_6 = true; } } BOOST_CHECK(found_edge3_3); BOOST_CHECK(found_edge3_6); } { // Test that the reduced graph handles loop and edge correctly // // 1 - 2 6 - 8 // | | | | // 4 - 3 - 5 - 7 - 9 // // Should reduce this to // // 3 - 3 // 3 - 7 // 7 - 7 // vector edges{Edge(1, 2), Edge(2, 3), Edge(3, 4), Edge(1, 4), Edge(3, 5), Edge(5, 7), Edge(7, 6), Edge(6, 8), Edge(8, 9), Edge(9, 7)}; unordered_map nodes; for (votca::Index vertex = 1; vertex <= 9; ++vertex) { GraphNode gn; nodes[vertex] = gn; } Graph graph(edges, nodes); ReducedGraph reduced_graph = reduceGraph(graph); vector junctions = reduced_graph.getJunctions(); BOOST_CHECK_EQUAL(junctions.size(), 2); bool found_junction_3 = false; bool found_junction_7 = false; for (votca::Index junction : junctions) { if (junction == 3) { found_junction_3 = true; } else if (junction == 7) { found_junction_7 = true; } } BOOST_CHECK(found_junction_3); BOOST_CHECK(found_junction_7); vector edges2 = reduced_graph.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 3); Edge ed3_3(3, 3); Edge ed3_7(3, 7); Edge ed7_7(7, 7); bool found_edge3_3 = false; bool found_edge3_7 = false; bool found_edge7_7 = false; for (Edge ed : edges2) { if (ed == ed3_3) { found_edge3_3 = true; } else if (ed == ed3_7) { found_edge3_7 = true; } else if (ed == ed7_7) { found_edge7_7 = true; } } BOOST_CHECK(found_edge3_3); BOOST_CHECK(found_edge3_7); BOOST_CHECK(found_edge7_7); } { // 4 - 5 // | | // 1 - 2 // \ | // 3 Edge ed1(1, 2); Edge ed2(1, 4); Edge ed3(1, 3); Edge ed4(4, 5); Edge ed5(2, 5); Edge ed6(2, 3); vector edges{ed1, ed2, ed3, ed4, ed5, ed6}; unordered_map nodes; for (votca::Index index = 0; index < 18; ++index) { GraphNode gn; nodes[index] = gn; } Graph g(edges, nodes); ReducedGraph reduced_g = reduceGraph(g); vector junctions = reduced_g.getJunctions(); BOOST_CHECK_EQUAL(junctions.size(), 2); bool found_junction_1 = false; bool found_junction_2 = false; for (votca::Index junction : junctions) { if (junction == 1) { found_junction_1 = true; } else if (junction == 2) { found_junction_2 = true; } } BOOST_CHECK(found_junction_1); BOOST_CHECK(found_junction_2); // Should end up with // _ _ // | | // 1 - 2 // |_ _| // vector edges2 = reduced_g.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 3); votca::Index edge_count1_2 = 0; for (const Edge& edge_temp : edges2) { if (edge_temp == ed1) { ++edge_count1_2; } } BOOST_CHECK_EQUAL(edge_count1_2, 3); } { // Create edge // 2 // | // 0 - 1 - 3 - 9 // | | // 4 - 5 - 6 - 7 - 8 Edge ed1(0, 1); Edge ed2(1, 2); Edge ed3(1, 3); Edge ed4(1, 4); Edge ed5(4, 5); Edge ed6(5, 6); Edge ed7(6, 7); Edge ed8(7, 8); Edge ed9(6, 9); Edge ed10(3, 9); // // 10 - 11 - 12 // // 13 // // 14 - 15 // | | // 16 - 17 // Edge ed11(10, 11); Edge ed12(11, 12); Edge ed13(14, 15); Edge ed14(15, 17); Edge ed15(16, 17); Edge ed16(14, 16); vector edges{ed1, ed2, ed3, ed4, ed5, ed6, ed7, ed8, ed9, ed10, ed11, ed12, ed13, ed14, ed15, ed16}; // Create Graph nodes unordered_map nodes; for (votca::Index index = 0; index < 18; ++index) { GraphNode gn; nodes[index] = gn; } Graph g(edges, nodes); ReducedGraph reduced_g = reduceGraph(g); vector junctions = reduced_g.getJunctions(); BOOST_CHECK_EQUAL(junctions.size(), 2); bool found_junction_1 = false; bool found_junction_6 = false; for (votca::Index junction : junctions) { if (junction == 1) { found_junction_1 = true; } else if (junction == 6) { found_junction_6 = true; } } BOOST_CHECK(found_junction_1); BOOST_CHECK(found_junction_6); // Full Graph // // 2 // | // 0 - 1 - 3 - 9 // | | // 4 - 5 - 6 - 7 - 8 // // 10 - 11 - 12 // // 13 // // 14 - 15 // | | // 16 - 17 // // Reduced Graph // // 2 // | // 0 - 1 - // | | // - 6 - 8 // // 10 - 12 // // 13 // // 14 - // | | // - // Edge ed0_1(0, 1); Edge ed1_2(1, 2); Edge ed1_6(1, 6); Edge ed6_8(6, 8); Edge ed10_12(10, 12); Edge ed14_14(14, 14); votca::Index edge_count0_1 = 0; votca::Index edge_count1_2 = 0; votca::Index edge_count1_6 = 0; votca::Index edge_count6_8 = 0; votca::Index edge_count10_12 = 0; votca::Index edge_count14_14 = 0; vector edges2 = reduced_g.getEdges(); BOOST_CHECK_EQUAL(edges2.size(), 7); for (Edge& edge : edges2) { if (edge == ed0_1) { ++edge_count0_1; } if (edge == ed1_2) { ++edge_count1_2; } if (edge == ed1_6) { ++edge_count1_6; } if (edge == ed6_8) { ++edge_count6_8; } if (edge == ed10_12) { ++edge_count10_12; } if (edge == ed14_14) { ++edge_count14_14; } } BOOST_CHECK_EQUAL(edge_count0_1, 1); BOOST_CHECK_EQUAL(edge_count1_2, 1); BOOST_CHECK_EQUAL(edge_count1_6, 2); BOOST_CHECK_EQUAL(edge_count6_8, 1); BOOST_CHECK_EQUAL(edge_count10_12, 1); BOOST_CHECK_EQUAL(edge_count14_14, 1); } } BOOST_AUTO_TEST_CASE(explorebranch_test) { { // Create edge // 2 - 10 // | // 0 - 1 - 3 - 9 // | | // 4 - 5 - 6 - 7 - 8 Edge ed1(0, 1); Edge ed2(1, 2); Edge ed3(1, 3); Edge ed4(1, 4); Edge ed5(4, 5); Edge ed6(5, 6); Edge ed7(6, 7); Edge ed8(7, 8); Edge ed9(6, 9); Edge ed10(3, 9); Edge ed11(2, 10); vector edges{ed1, ed2, ed3, ed4, ed5, ed6, ed7, ed8, ed9, ed10, ed11}; // Create Graph nodes unordered_map nodes; for (votca::Index index = 0; index < 11; ++index) { GraphNode gn; nodes[index] = gn; } Graph g(edges, nodes); votca::Index starting_vertex = 1; set branch_edges = exploreBranch(g, starting_vertex, ed3); // The following edges should be found in the branch // // 1 - 3 - 9 // | | // 4 - 5 - 6 - 7 - 8 // BOOST_CHECK_EQUAL(branch_edges.size(), 8); vector found_edges(8, false); votca::Index index = 0; for (const Edge& ed : branch_edges) { if (ed == ed3) { found_edges.at(index) = true; } if (ed == ed4) { found_edges.at(index) = true; } if (ed == ed5) { found_edges.at(index) = true; } if (ed == ed6) { found_edges.at(index) = true; } if (ed == ed7) { found_edges.at(index) = true; } if (ed == ed8) { found_edges.at(index) = true; } if (ed == ed9) { found_edges.at(index) = true; } if (ed == ed10) { found_edges.at(index) = true; } ++index; } for (const bool& found : found_edges) { BOOST_CHECK(found); } } } BOOST_AUTO_TEST_CASE(structureid_test) { { // Create edge Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(3, 4); Edge ed4(4, 5); Edge ed5(5, 0); Edge ed6(3, 6); vector edges; edges.push_back(ed); edges.push_back(ed1); edges.push_back(ed2); edges.push_back(ed3); edges.push_back(ed4); edges.push_back(ed5); edges.push_back(ed6); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; GraphNode gn4; GraphNode gn5; GraphNode gn6; GraphNode gn7; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; nodes[3] = gn4; nodes[4] = gn5; nodes[5] = gn6; nodes[6] = gn7; Graph g(edges, nodes); string structId = findStructureId(g); string answer = "Dist0Dist1Dist1Dist1Dist2Dist2Dist3"; BOOST_CHECK_EQUAL(structId, answer); } } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graphdistvisitor.cc000066400000000000000000000106111412152065700216460ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graphdistvisitor_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graph.h" #include "votca/tools/graphdistvisitor.h" #include "votca/tools/graphnode.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(graphdistvisitor_test) BOOST_AUTO_TEST_CASE(constructor_test) { GraphDistVisitor gdv; } BOOST_AUTO_TEST_CASE(basic_test) { // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; Graph g(edges, nodes); GraphDistVisitor gdv; BOOST_CHECK(gdv.queEmpty()); BOOST_CHECK_THROW(gdv.exec(g, ed), runtime_error); // Default starts with node index 0 gdv.initialize(g); BOOST_CHECK_EQUAL(gdv.queEmpty(), false); // No exception should be thrown at this point Edge ed1 = gdv.nextEdge(g); BOOST_CHECK_EQUAL(ed, ed1); gdv.exec(g, ed1); BOOST_CHECK(gdv.queEmpty()); GraphNode gn3 = g.getNode(0); votca::Index dist = gn3.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 0); GraphNode gn4 = g.getNode(1); dist = gn4.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 1); } BOOST_AUTO_TEST_CASE(basic_test2) { // Create edges // // 0 - 1 - 2 // | | // 6 - 4 - 3 // | // 5 // Edge ed(0, 1); Edge ed1(1, 2); Edge ed2(2, 3); Edge ed3(3, 4); Edge ed4(4, 5); Edge ed5(4, 6); Edge ed6(6, 0); vector edges; edges.push_back(ed); edges.push_back(ed1); edges.push_back(ed2); edges.push_back(ed3); edges.push_back(ed4); edges.push_back(ed5); edges.push_back(ed6); // Create Graph nodes GraphNode gn1; GraphNode gn2; GraphNode gn3; GraphNode gn4; GraphNode gn5; GraphNode gn6; GraphNode gn7; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; nodes[2] = gn3; nodes[3] = gn4; nodes[4] = gn5; nodes[5] = gn6; nodes[6] = gn7; Graph g(edges, nodes); GraphDistVisitor gdv; BOOST_CHECK(gdv.queEmpty()); BOOST_CHECK_THROW(gdv.exec(g, ed), runtime_error); // Default starts with node index 0 gdv.initialize(g); BOOST_CHECK_EQUAL(gdv.queEmpty(), false); // No exception should be thrown at this point // First two edges that should be explored are edges ed and ed6 vector temp; Edge ed7 = gdv.nextEdge(g); temp.push_back(ed7); gdv.exec(g, ed7); ed7 = gdv.nextEdge(g); gdv.exec(g, ed7); temp.push_back(ed7); bool found_ed = false; bool found_ed6 = false; for (auto ed_temp : temp) { if (ed_temp == ed) { found_ed = true; } if (ed_temp == ed6) { found_ed6 = true; } } BOOST_CHECK(found_ed); BOOST_CHECK(found_ed6); // Explore the whole graph while (!gdv.queEmpty()) { ed7 = gdv.nextEdge(g); gdv.exec(g, ed7); } // Now let's check that the distances for each node // are correct. The distances are counted from the starting // node which by default is node 0. GraphNode gn8 = g.getNode(0); votca::Index dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 0); gn8 = g.getNode(1); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 1); gn8 = g.getNode(2); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 2); gn8 = g.getNode(3); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 3); gn8 = g.getNode(4); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 2); gn8 = g.getNode(5); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 3); gn8 = g.getNode(6); dist = gn8.getInt("Dist"); BOOST_CHECK_EQUAL(dist, 1); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graphnode.cc000066400000000000000000000071461412152065700202210ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graphnode_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graphnode.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(graphnode_test) BOOST_AUTO_TEST_CASE(constructors_test) { GraphNode gn; } BOOST_AUTO_TEST_CASE(accessors_test) { GraphNode gn; BOOST_CHECK_EQUAL(gn == gn, true); BOOST_CHECK_EQUAL(gn.getStringId(), ""); unordered_map int_vals = {{"Num", 134}}; unordered_map double_vals = {{"Height", 159.32}}; unordered_map str_vals = {{"Name", "George"}}; GraphNode gn2(int_vals, double_vals, str_vals); GraphNode gn3(int_vals, double_vals, str_vals); BOOST_CHECK_EQUAL(gn != gn2, true); BOOST_CHECK_EQUAL(gn2 == gn2, true); BOOST_CHECK_EQUAL(gn3 == gn2, true); } BOOST_AUTO_TEST_CASE(setters_test) { unordered_map int_vals = {{"Num", 134}}; unordered_map double_vals = {{"Height", 159.32}}; unordered_map str_vals = {{"Name", "George"}}; GraphNode gn2(int_vals, double_vals, str_vals); string str{"Num134Height159.32NameGeorge"}; BOOST_CHECK_EQUAL(gn2.getStringId(), str); unordered_map int_vals2 = {{"Second", 2}, {"First", 1}}; gn2.setInt(int_vals2); str = "First1Second2Height159.32NameGeorge"; BOOST_CHECK_EQUAL(gn2.getStringId(), str); unordered_map double_vals2 = {{"Height", 159.32}, {"Weight", 101.43}}; gn2.setDouble(double_vals2); str = "First1Second2Height159.32Weight101.43NameGeorge"; BOOST_CHECK_EQUAL(gn2.getStringId(), str); unordered_map str_vals2 = {{"Name", "George"}, {"Address", "Koogler St"}}; gn2.setStr(str_vals2); str = "First1Second2Height159.32Weight101.43AddressKoogler StNameGeorge"; BOOST_CHECK_EQUAL(gn2.getStringId(), str); } BOOST_AUTO_TEST_CASE(comparisontest) { unordered_map int_vals1 = {{"a", 134}}; unordered_map int_vals2 = {{"b", 134}}; unordered_map double_vals; unordered_map str_vals; GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); BOOST_CHECK_EQUAL(cmpNode(gn1, gn2), true); BOOST_CHECK_EQUAL(cmpNode(gn2, gn1), false); vector vec_gn = {gn1, gn2}; sort(vec_gn.begin(), vec_gn.end(), cmpNode); string str1{"a134"}; string str2{"b134"}; BOOST_CHECK_EQUAL(vec_gn.at(0).getStringId(), str1); BOOST_CHECK_EQUAL(vec_gn.at(1).getStringId(), str2); vector vec_gn2 = {gn2, gn1}; sort(vec_gn2.begin(), vec_gn2.end(), cmpNode); BOOST_CHECK_EQUAL(vec_gn2.at(0).getStringId(), str1); BOOST_CHECK_EQUAL(vec_gn2.at(1).getStringId(), str2); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_graphvisitor.cc000066400000000000000000000042201412152065700207610ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE graphvisitor_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graph.h" #include "votca/tools/graphnode.h" #include "votca/tools/graphvisitor.h" using namespace std; using namespace votca::tools; class GraphVisitorTest : public GraphVisitor { private: void addEdges_(const Graph&, votca::Index) override { throw runtime_error("Undefined method."); } Edge getEdge_() override { throw runtime_error("Undefined method."); } }; BOOST_AUTO_TEST_SUITE(graphvisitor_test) BOOST_AUTO_TEST_CASE(constructor_test) { GraphVisitorTest gv; } BOOST_AUTO_TEST_CASE(basic_test) { // Create edge Edge ed(0, 1); vector edges; edges.push_back(ed); // Create Graph nodes GraphNode gn1; GraphNode gn2; unordered_map nodes; nodes[0] = gn1; nodes[1] = gn2; Graph g(edges, nodes); GraphVisitorTest gv; BOOST_CHECK(gv.queEmpty()); BOOST_CHECK_THROW(gv.exec(g, ed), runtime_error); BOOST_CHECK_THROW(gv.initialize(g), runtime_error); // No exception should be thrown at this point gv.exec(g, ed); // Error because no nextEdge function ptr passed in BOOST_CHECK_THROW(gv.nextEdge(g), runtime_error); BOOST_CHECK_EQUAL(gv.getStartingVertex(), 0); gv.setStartingVertex(2); BOOST_CHECK_EQUAL(gv.getStartingVertex(), 2); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_histogramnew.cc000066400000000000000000000065351412152065700207620ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE histogramnew_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/histogramnew.h" #include "votca/tools/table.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(histogramnew_test) BOOST_AUTO_TEST_CASE(create_test) { HistogramNew hn; } BOOST_AUTO_TEST_CASE(init_test) { HistogramNew hn; double min_v = 1.2; double max_v = 102.0; hn.Initialize(min_v, max_v, 10); } BOOST_AUTO_TEST_CASE(step_test) { HistogramNew hn; double min_v = 1; double max_v = 9; hn.Initialize(min_v, max_v, 8); double step = hn.getStep(); votca::Index value = static_cast(step); BOOST_CHECK_EQUAL(value * 10, 10); } BOOST_AUTO_TEST_CASE(nbins_test) { HistogramNew hn; double min_v = 1.0; double max_v = 9.0; hn.Initialize(min_v, max_v, 8); votca::Index bins = hn.getNBins(); BOOST_CHECK_EQUAL(bins * 10, 80); } BOOST_AUTO_TEST_CASE(Process_test) { HistogramNew hn; double min_v = 0.0; double max_v = 10.0; hn.Initialize(min_v, max_v, 11); vector data; for (double x = 0; x < 10; ++x) { data.push_back(x); } hn.ProcessRange(data.begin(), data.end()); hn.Process(4.5); BOOST_CHECK_EQUAL(static_cast(hn.getStep() * 10), 10); auto dat = hn.data(); // Range -0.5 - 0.5 BOOST_CHECK_EQUAL(static_cast(dat.y(0)), 1); // Range 0.5 - 1.5 BOOST_CHECK_EQUAL(static_cast(dat.y(1)), 1); // Range 1.5 - 2.5 BOOST_CHECK_EQUAL(static_cast(dat.y(2)), 1); // Range 2.5 - 3.5 BOOST_CHECK_EQUAL(static_cast(dat.y(3)), 1); // Range 3.5 - 4.5 BOOST_CHECK_EQUAL(static_cast(dat.y(4)), 1); // Range 4.5 - 5.5 BOOST_CHECK_EQUAL(static_cast(dat.y(5)), 2); // Range 5.5 - 6.5 BOOST_CHECK_EQUAL(static_cast(dat.y(6)), 1); // Range 6.5 - 7.5 BOOST_CHECK_EQUAL(static_cast(dat.y(7)), 1); // Range 7.5 - 8.5 BOOST_CHECK_EQUAL(static_cast(dat.y(8)), 1); // Range 8.5 - 9.5 BOOST_CHECK_EQUAL(static_cast(dat.y(9)), 1); // Range 9.5 - 10.5 BOOST_CHECK_EQUAL(static_cast(dat.y(10)), 0); } BOOST_AUTO_TEST_CASE(minmax_test) { HistogramNew hn; double min_v = 0.0; double max_v = 10.0; hn.Initialize(min_v, max_v, 10); vector data; for (double x = 0; x < 9; ++x) { data.push_back(x); } hn.ProcessRange(data.begin(), data.end()); hn.Process(4.5); BOOST_CHECK_EQUAL(static_cast(hn.getMinBinVal()), 0); BOOST_CHECK_EQUAL(static_cast(hn.getMaxBinVal()), 2); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_identity.cc000066400000000000000000000024531412152065700200770ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE identity_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/identity.h" #include "votca/tools/types.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(identity_test) BOOST_AUTO_TEST_CASE(constructors_test) { Identity id; Identity id2(232); } BOOST_AUTO_TEST_CASE(simple_test) { Identity id; Identity id2(32); BOOST_CHECK_EQUAL(id2.getId(), 32); id2.setId(34); BOOST_CHECK_EQUAL(id2.getId(), 34); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_linalg.cc000066400000000000000000000054321412152065700175140ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE linalg_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/eigenio_matrixmarket.h" #include "votca/tools/linalg.h" using namespace votca::tools; BOOST_AUTO_TEST_SUITE(linalg_test) BOOST_AUTO_TEST_CASE(linalg_constrained_qrsolve_test) { Eigen::VectorXd b = Eigen::VectorXd::Zero(3); b(0) = 11; b(1) = -3; b(2) = 8; Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3); A(0, 0) = 1; A(0, 1) = 1; A(0, 2) = 1; A(1, 0) = 1; A(1, 1) = -1; A(2, 1) = 1; A(2, 2) = 1; Eigen::MatrixXd B = Eigen::MatrixXd::Zero(1, 3); B(0, 1) = -1; B(0, 2) = 3; Eigen::VectorXd x = linalg_constrained_qrsolve(A, b, B); Eigen::VectorXd x_ref = Eigen::VectorXd::Zero(3); x_ref(0) = 3; x_ref(1) = 6; x_ref(2) = 2; bool equal = x_ref.isApprox(x, 1e-7); if (!equal) { std::cout << "result" << std::endl; std::cout << x << std::endl; std::cout << "ref" << std::endl; std::cout << x_ref << std::endl; } BOOST_CHECK_EQUAL(equal, true); } BOOST_AUTO_TEST_CASE(linalg_mkl_test) { votca::Index nmax = 10; Eigen::MatrixXd H = EigenIO_MatrixMarket::ReadMatrix( std::string(TOOLS_TEST_DATA_FOLDER) + "/linalg/H.mm"); Eigen::SelfAdjointEigenSolver es(H); Eigen::MatrixXd V_ref = es.eigenvectors().block(0, 0, H.rows(), nmax); Eigen::VectorXd E_ref = es.eigenvalues().segment(0, nmax); EigenSystem result = linalg_eigenvalues(H, nmax); bool check_energy = E_ref.isApprox(result.eigenvalues(), 0.0001); bool check_vector = result.eigenvectors().cwiseAbs().isApprox(V_ref.cwiseAbs(), 0.0001); if (!check_vector || !check_energy) { std::cout << "E_ref" << std::endl; std::cout << E_ref << std::endl; std::cout << "E" << std::endl; std::cout << result.eigenvalues() << std::endl; std::cout << "V_ref" << std::endl; std::cout << V_ref << std::endl; std::cout << "V" << std::endl; std::cout << result.eigenvectors() << std::endl; } BOOST_CHECK_EQUAL(check_energy, 1); BOOST_CHECK_EQUAL(check_vector, 1); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_linspline.cc000066400000000000000000000101061412152065700202350ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE linspline_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "../../include/votca/tools/linspline.h" using namespace votca::tools; BOOST_AUTO_TEST_SUITE(linspline_test) BOOST_AUTO_TEST_CASE(fit_test) { int size = 80; Eigen::VectorXd x = Eigen::VectorXd::Zero(size); Eigen::VectorXd y = Eigen::VectorXd::Zero(size); for (int i = 0; i < size; ++i) { x(i) = 0.25 * i; y(i) = std::sin(x(i)); } LinSpline cspline; cspline.setBCInt(0); cspline.GenerateGrid(0.4, 0.6, 0.1); cspline.Fit(x, y); Eigen::VectorXd rs = Eigen::VectorXd::Zero(10); rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0; Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10); values_ref << 0.218354, 0.225766, 0.230181, 0.231299, 0.23465, 0.199824, 0.227947, 0.235767, 0.0515847, 0.0515847; Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10); derivatives_ref << 0.370599, 0.370599, -0.0223429, -0.0223429, -0.0223429, 0.370599, -0.0223429, -0.0223429, 0.370599, 0.370599; Eigen::VectorXd values = cspline.Calculate(rs); Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs); bool equal_val = values_ref.isApprox(values, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << values.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5); if (!equal_derivative) { std::cout << "result value" << std::endl; std::cout << derivatives.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << derivatives_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_derivative, true); } BOOST_AUTO_TEST_CASE(interpolate_test) { int size = 80; Eigen::VectorXd x = Eigen::VectorXd::Zero(size); Eigen::VectorXd y = Eigen::VectorXd::Zero(size); for (int i = 0; i < size; ++i) { x(i) = 0.25 * i; y(i) = std::sin(x(i)); } LinSpline cspline; cspline.setBCInt(0); cspline.Interpolate(x, y); Eigen::VectorXd rs = Eigen::VectorXd::Zero(10); rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0; Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10); values_ref << 0.433021, 0.451583, 0.713605, 0.681639, 0.560311, 0.386617, 0.777538, 0.519868, 0, 0; Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10); derivatives_ref << 0.928086, 0.928086, 0.639329, 0.639329, 0.808853, 0.928086, 0.639329, 0.808853, 0.989616, 0.989616; Eigen::VectorXd values = cspline.Calculate(rs); Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs); bool equal_val = values_ref.isApprox(values, 1e-5); if (!equal_val) { std::cout << "result value" << std::endl; std::cout << values.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << values_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_val, true); bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5); if (!equal_derivative) { std::cout << "result value" << std::endl; std::cout << derivatives.transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << derivatives_ref.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal_derivative, true); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_name.cc000066400000000000000000000023541412152065700171660ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE name_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/name.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(name_test) BOOST_AUTO_TEST_CASE(constructors_test) { Name nm; Name nm2("S"); } BOOST_AUTO_TEST_CASE(accessors_test) { Name nm; nm.setName("New Name"); BOOST_CHECK_EQUAL(nm.getName(), "New Name"); Name nm2("Name2"); BOOST_CHECK_EQUAL(nm2.getName(), "Name2"); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_objectfactory.cc000066400000000000000000000041241412152065700211010ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #include #include #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE name_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/objectfactory.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(objectfactory_test) class base { public: base() = default; virtual ~base() = default; virtual std::string identify() = 0; }; class A : public base { public: std::string identify() override { return "A"; } }; class B : public base { public: std::string identify() override { return "B"; } }; BOOST_AUTO_TEST_CASE(construction_test) { ObjectFactory factory; factory.Register("A"); factory.Register("B"); std::unique_ptr A = factory.Create("A"); BOOST_REQUIRE_EQUAL(A->identify(), "A"); BOOST_REQUIRE(factory.IsRegistered("A")); std::unique_ptr B = factory.Create("B"); BOOST_REQUIRE_EQUAL(B->identify(), "B"); std::vector keys = factory.getKeys(); bool A_present = (std::find(keys.begin(), keys.end(), "A") != keys.end()); bool B_present = (std::find(keys.begin(), keys.end(), "B") != keys.end()); BOOST_REQUIRE(A_present); BOOST_REQUIRE(B_present); BOOST_REQUIRE_THROW(factory.Create("C"), std::runtime_error); BOOST_REQUIRE_EQUAL(factory.IsRegistered("D"), false); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_property.cc000066400000000000000000000112041412152065700201240ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE property_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/property.h" using namespace votca::tools; BOOST_AUTO_TEST_SUITE(property_test) BOOST_AUTO_TEST_CASE(eigen_test) { Property prop; prop.add("vec", "1 2 3 4 5 6 7 8"); Eigen::VectorXd result = prop.get("vec").as(); Eigen::VectorXd ref; ref.resize(8); ref << 1, 2, 3, 4, 5, 6, 7, 8; BOOST_CHECK_EQUAL(ref.isApprox(result, 0.0001), true); BOOST_CHECK_THROW(prop.get("vec").as(), std::runtime_error); Property prop2; prop.add("vec", "1 2 3"); Eigen::Vector3d result2 = prop.get("vec").as(); Eigen::Vector3d ref2{1, 2, 3}; BOOST_CHECK_EQUAL(ref2.isApprox(result2, 0.0001), true); } BOOST_AUTO_TEST_CASE(readin) { std::ofstream xmlfile("notnormalized.xml"); xmlfile << "" << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile << " " << std::endl; xmlfile.close(); Property prop; prop.LoadFromXML("notnormalized.xml"); Property& e = prop.get("basis.element"); BOOST_CHECK_EQUAL(e.getAttribute("name"), "Al"); BOOST_REQUIRE_THROW(prop.get("basis.blabla"), std::runtime_error); Property& c = prop.get("basis.element.shell.constant.contractions"); BOOST_CHECK_EQUAL(c.getAttribute("type"), "D"); BOOST_REQUIRE_THROW(c.getAttribute("bla"), std::runtime_error); } BOOST_AUTO_TEST_CASE(select) { std::ofstream xmlfile("test_select.xml"); xmlfile << "" << std::endl; xmlfile << " " << std::endl; xmlfile << " blabla" << std::endl; xmlfile << " lala" << std::endl; xmlfile << " blabla" << std::endl; xmlfile << " lala" << std::endl; xmlfile << " " << std::endl; xmlfile << "" << std::endl; xmlfile.close(); Property prop; prop.LoadFromXML("test_select.xml"); std::vector s1 = prop.Select("A.B.Ca"); BOOST_CHECK_EQUAL(s1.size(), 2); const Property& propB = prop.get("A.B"); std::vector s2 = propB.Select("Ca"); BOOST_CHECK_EQUAL(s2.size(), 2); std::vector s3 = prop.Select("B"); BOOST_CHECK_EQUAL(s3.size(), 0); std::vector s4 = prop.Select("hello"); BOOST_CHECK_EQUAL(s4.size(), 0); std::vector s5 = prop.Select(""); BOOST_CHECK_EQUAL(s5.size(), 0); std::vector s6 = prop.Select("."); BOOST_CHECK_EQUAL(s6.size(), 0); std::vector s7 = prop.Select("A"); BOOST_CHECK_EQUAL(s7.size(), 1); std::vector s8 = prop.Select("A.B.C*"); BOOST_CHECK_EQUAL(s8.size(), 4); } BOOST_AUTO_TEST_CASE(printtostream) { Property prop; Property& p = prop.add("hello", ""); p.add("hi", "5"); p.add("ho", "bumm"); std::stringstream dudu; dudu << prop; std::string printout = dudu.str(); std::string ref = "<>\n" " \n" " 5\n" " bumm\n" " \n" "\n"; BOOST_CHECK_EQUAL(printout, ref); } BOOST_AUTO_TEST_CASE(addproperty) { Property one("one", "", ""); one.add("hello", ""); Property two("two", "", ""); two.add("goodbye", "4"); two.add("goodbye", "3"); two.add("bye", "1"); one.add(two); BOOST_CHECK_EQUAL(one.get("two.goodbye").path(), "one.two"); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_random.cc000066400000000000000000000037571412152065700175360ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE random2_test // Standard includes #include #include // Third party includes #include #include // Local VOTCA includes #include "votca/tools/random.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(random2_test) BOOST_AUTO_TEST_CASE(random_int_test) { Random random; votca::Index seed = 1; random.init(seed); random.setMaxInt(50); std::vector results; votca::Index number = 1e5; results.reserve(number); for (votca::Index i = 0; i < number; i++) { results.push_back(random.rand_uniform_int()); } // average should be close to 25 double average = std::accumulate(results.begin(), results.end(), 0); average /= double(number); BOOST_CHECK_CLOSE(average, 25, 1.0); } BOOST_AUTO_TEST_CASE(random_double_test) { Random random; votca::Index seed = 1; random.init(seed); std::vector results; votca::Index number = 1e5; results.reserve(number); for (votca::Index i = 0; i < number; i++) { results.push_back(random.rand_uniform()); } // average should be close to 0.5 double average = std::accumulate(results.begin(), results.end(), 0.0); average /= double(number); BOOST_CHECK_CLOSE(average, 0.5, 1.0); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_reducededge.cc000066400000000000000000000114371412152065700205100ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE edge_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/reducededge.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(edge_test) BOOST_AUTO_TEST_CASE(constructors_test) { ReducedEdge ed(2, 3); } BOOST_AUTO_TEST_CASE(ouput_test) { ReducedEdge ed(2, 3); cout << ed << endl; } BOOST_AUTO_TEST_CASE(equivalence_test) { ReducedEdge ed(2, 3); ReducedEdge ed2(2, 4); ReducedEdge ed3(3, 2); BOOST_CHECK_EQUAL(ed, ed); BOOST_CHECK_EQUAL(ed, ed3); BOOST_CHECK_EQUAL((ed == ed2), false); ReducedEdge ed4(vector{2, 3, 4}); ReducedEdge ed5(vector{4, 3, 2}); BOOST_CHECK_EQUAL(ed4, ed5); BOOST_CHECK_EQUAL((ed4 == ed), false); ReducedEdge ed6(vector{2, 6, 3, 1}); ReducedEdge ed7(vector{1, 3, 6, 2}); auto chain = ed6.getChain(); BOOST_CHECK_EQUAL(ed6, ed7); // Both are loops they get rearranged internally so the smallest vertex // appears as EndPoint1 and EndPoint2 ReducedEdge ed8(vector{1, 2, 4, 1}); ReducedEdge ed9(vector{2, 4, 1, 2}); BOOST_CHECK_EQUAL(ed8, ed9); } BOOST_AUTO_TEST_CASE(nequivalence_test) { ReducedEdge ed(2, 3); ReducedEdge ed2(2, 4); BOOST_CHECK_EQUAL(ed != ed2, true); BOOST_CHECK_EQUAL((ed != ed), false); } BOOST_AUTO_TEST_CASE(getter_test) { ReducedEdge ed(2, 3); BOOST_CHECK_EQUAL(ed.getEndPoint1(), 2); BOOST_CHECK_EQUAL(ed.getEndPoint2(), 3); ReducedEdge ed2(3, 2); BOOST_CHECK_EQUAL(ed.getEndPoint1(), 2); BOOST_CHECK_EQUAL(ed.getEndPoint2(), 3); ReducedEdge ed3(vector{2, 6, 3, 1}); BOOST_CHECK_EQUAL(ed3.getEndPoint1(), 1); BOOST_CHECK_EQUAL(ed3.getEndPoint2(), 2); ReducedEdge ed4(vector{1, 3, 6, 2}); BOOST_CHECK_EQUAL(ed4.getEndPoint1(), 1); BOOST_CHECK_EQUAL(ed4.getEndPoint2(), 2); ReducedEdge ed5(vector{1, 2, 4, 1}); BOOST_CHECK_EQUAL(ed5.getEndPoint1(), 1); BOOST_CHECK_EQUAL(ed5.getEndPoint2(), 1); ReducedEdge ed6(vector{2, 4, 1, 2}); BOOST_CHECK_EQUAL(ed6.getEndPoint1(), 1); BOOST_CHECK_EQUAL(ed6.getEndPoint2(), 1); } BOOST_AUTO_TEST_CASE(getchain_test) { vector vertices{4, 1, 6, 7, 0}; ReducedEdge ed(vertices); auto chain = ed.getChain(); BOOST_CHECK_EQUAL(chain.at(0), 0); BOOST_CHECK_EQUAL(chain.at(1), 7); BOOST_CHECK_EQUAL(chain.at(2), 6); BOOST_CHECK_EQUAL(chain.at(3), 1); BOOST_CHECK_EQUAL(chain.at(4), 4); } BOOST_AUTO_TEST_CASE(vertexwithinchain_test) { vector vertices{1, 3, 4, 5}; ReducedEdge ed(vertices); BOOST_CHECK(ed.vertexExistInChain(1)); BOOST_CHECK(ed.vertexExistInChain(2) == false); BOOST_CHECK(ed.vertexExistInChain(3)); BOOST_CHECK(ed.vertexExistInChain(4)); BOOST_CHECK(ed.vertexExistInChain(5)); } BOOST_AUTO_TEST_CASE(less_test) { ReducedEdge ed1(1, 2); ReducedEdge ed2(2, 1); BOOST_CHECK_EQUAL((ed1 < ed2), false); ReducedEdge ed3(3, 0); BOOST_CHECK_EQUAL(ed3 < ed1, true); ReducedEdge ed4(1, 5); BOOST_CHECK_EQUAL(ed1 < ed4, true); ReducedEdge ed5(2, 2); BOOST_CHECK_EQUAL(ed4 < ed5, true); ReducedEdge ed6(vector{1, 2, 3}); BOOST_CHECK_EQUAL(ed1 < ed6, true); ReducedEdge ed7(vector{1, 2, 3, 4, 1}); ReducedEdge ed8(vector{1, 4, 3, 2, 1}); BOOST_CHECK_EQUAL((ed7 < ed8), false); // Equal ReducedEdge ed9(vector{1, 4, 5, 2, 1}); BOOST_CHECK_EQUAL((ed7 < ed9), true); ReducedEdge ed10(vector{1, 4, 5, 0, 1}); BOOST_CHECK_EQUAL((ed10 < ed9), true); ReducedEdge ed11(vector{1, 0, 5, 2, 1}); BOOST_CHECK_EQUAL((ed11 < ed9), true); } BOOST_AUTO_TEST_CASE(greater_test) { ReducedEdge ed1(1, 2); ReducedEdge ed2(2, 1); BOOST_CHECK_EQUAL(!(ed1 > ed2), true); ReducedEdge ed3(3, 0); BOOST_CHECK_EQUAL(!(ed3 > ed1), true); } BOOST_AUTO_TEST_CASE(hash_key_test) { set e_set; ReducedEdge ed(23, 43); e_set.insert(ed); unordered_map e_map; e_map[2] = ed; } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_reducedgraph.cc000066400000000000000000000510261412152065700207030ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE reducedgraph_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/graphnode.h" #include "votca/tools/reducededge.h" #include "votca/tools/reducedgraph.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(reducedgraph_test) BOOST_AUTO_TEST_CASE(constructors_test) { ReducedGraph g; } /** * \brief Test on isolated nodes method * * The isolated nodes method is meant to grab any nodes that have no edges, as * in they exist as islands within the context of the graph. */ BOOST_AUTO_TEST_CASE(isolatednodes_test) { { /// Here gn is a single node as is thus isolated vector vec_ed; GraphNode gn; unordered_map m_gn; m_gn[0] = gn; ReducedGraph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); BOOST_CHECK_EQUAL(iso_gn.at(0).first, 0); } { /// In this test case gn, gn1 and gn2 are all islands no edges have been /// specified to connect them. Calling getIsolatedNodes() thus returns all /// three of them. vector vec_ed; GraphNode gn; GraphNode gn1; GraphNode gn2; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; ReducedGraph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); bool node0 = false; bool node1 = false; bool node2 = false; for (auto n_pr : iso_gn) { if (n_pr.first == 0) { node0 = true; } if (n_pr.first == 1) { node1 = true; } if (n_pr.first == 2) { node2 = true; } } BOOST_CHECK(node0); BOOST_CHECK(node1); BOOST_CHECK(node2); } { /// In this test both node 0 and 1 share an edge and are no longer isolated /// however node 2 is isolated, a call getIsolatedNodes() only returns node /// 2 vector vec_ed; ReducedEdge ed(0, 1); vec_ed.push_back(ed); GraphNode gn; GraphNode gn1; GraphNode gn2; unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; ReducedGraph g(vec_ed, m_gn); auto iso_gn = g.getIsolatedNodes(); bool node0 = false; bool node1 = false; bool node2 = false; for (auto n_pr : iso_gn) { if (n_pr.first == 0) { node0 = true; } if (n_pr.first == 1) { node1 = true; } if (n_pr.first == 2) { node2 = true; } } BOOST_CHECK(!node0); BOOST_CHECK(!node1); BOOST_CHECK(node2); } } BOOST_AUTO_TEST_CASE(get_edges_test) { { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; ReducedGraph g(vec_ed, m_gn); auto edges = g.getEdges(); bool ed0_found = false; bool ed2_found = false; bool ed3_found = false; for (auto ed_temp : edges) { if (ed_temp == ed) { ed0_found = true; } if (ed_temp == ed2) { ed2_found = true; } if (ed_temp == ed3) { ed3_found = true; } } BOOST_CHECK(ed0_found); BOOST_CHECK(ed2_found); BOOST_CHECK(ed3_found); } { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map int_vals5 = {{"f", 5}}; unordered_map int_vals6 = {{"g", 6}}; unordered_map int_vals7 = {{"h", 7}}; unordered_map double_vals; unordered_map str_vals; // Full Graph // // 0 - 1 - 2 - 3 - 5 - 6 // | | // 7 - 4 // // Reduced Graph // // 0 - 1 - 2 - 6 // | _ | // vector vec_ed; ReducedEdge ed(0, 1); ReducedEdge ed2(1, 2); ReducedEdge ed3(vector{2, 3, 4, 5, 6}); ReducedEdge ed4(vector{1, 7, 4, 2}); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); vec_ed.push_back(ed4); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); GraphNode gn5(int_vals5, double_vals, str_vals); GraphNode gn6(int_vals6, double_vals, str_vals); GraphNode gn7(int_vals7, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; m_gn[5] = gn5; m_gn[6] = gn6; m_gn[7] = gn7; ReducedGraph g(vec_ed, m_gn); auto edges = g.getEdges(); // Reduced Graph // // 0 - 1 - 2 - 6 // | _ | // votca::Index ed0_1count = 0; votca::Index ed1_2count = 0; votca::Index ed2_6count = 0; Edge ed0_1(0, 1); Edge ed1_2(1, 2); Edge ed2_6(2, 6); for (auto ed_temp : edges) { if (ed_temp == ed0_1) { ++ed0_1count; } if (ed_temp == ed1_2) { ++ed1_2count; } if (ed_temp == ed2_6) { ++ed2_6count; } } BOOST_CHECK_EQUAL(ed0_1count, 1); BOOST_CHECK_EQUAL(ed1_2count, 2); BOOST_CHECK_EQUAL(ed2_6count, 1); } } BOOST_AUTO_TEST_CASE(get_vertices_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; ReducedGraph g(vec_ed, m_gn); vector vertices = g.getVertices(); for (auto vertex : vertices) { cout << vertex << endl; } BOOST_CHECK_EQUAL(vertices.size(), 4); vector vertices_found(4, false); for (auto vertex : vertices) { if (vertex == 0) { vertices_found.at(0) = true; } if (vertex == 2) { vertices_found.at(1) = true; } if (vertex == 3) { vertices_found.at(2) = true; } if (vertex == 4) { vertices_found.at(3) = true; } } for (auto found : vertices_found) { BOOST_CHECK(found); } // Lets add a redundant edge, this should not change the output of the // getVertices method // // 0 - 1 - 2 - 3 // | _ | // 4 vec_ed.push_back(ed); ReducedGraph g2(vec_ed, m_gn); vertices = g2.getVertices(); BOOST_CHECK_EQUAL(vertices.size(), 4); vector vertices_found2(4, false); for (auto vertex : vertices) { if (vertex == 0) { vertices_found2.at(0) = true; } if (vertex == 2) { vertices_found2.at(1) = true; } if (vertex == 3) { vertices_found2.at(2) = true; } if (vertex == 4) { vertices_found2.at(3) = true; } } for (auto found : vertices_found2) { BOOST_CHECK(found); } } BOOST_AUTO_TEST_CASE(compare_test) { { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; m_gn[0] = gn; m_gn[1] = gn1; m_gn[2] = gn2; m_gn[3] = gn3; m_gn[4] = gn4; ReducedGraph g(vec_ed, m_gn); auto vec_pr = g.getNodes(); sort(vec_pr.begin(), vec_pr.end(), cmpVertNodePair); BOOST_CHECK_EQUAL(vec_pr.at(0).first, 0); BOOST_CHECK_EQUAL(vec_pr.at(1).first, 2); BOOST_CHECK_EQUAL(vec_pr.at(2).first, 3); BOOST_CHECK_EQUAL(vec_pr.at(3).first, 4); } { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); /// Only difference is here where we have rearanged the nodes unordered_map m_gn; m_gn[4] = gn; m_gn[1] = gn1; m_gn[3] = gn2; m_gn[2] = gn3; m_gn[0] = gn4; ReducedGraph g(vec_ed, m_gn); auto vec_pr = g.getNodes(); sort(vec_pr.begin(), vec_pr.end(), cmpVertNodePair); BOOST_CHECK_EQUAL(vec_pr.at(0).first, 4); BOOST_CHECK_EQUAL(vec_pr.at(1).first, 3); BOOST_CHECK_EQUAL(vec_pr.at(2).first, 2); BOOST_CHECK_EQUAL(vec_pr.at(3).first, 0); } } BOOST_AUTO_TEST_CASE(neighbornode_test) { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; // 0 - 1 - 2 - 3 // | // 4 vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; /// Here the graph nodes are assigne to different vertices m_gn[0] = gn4; m_gn[1] = gn1; m_gn[2] = gn3; m_gn[3] = gn2; m_gn[4] = gn; ReducedGraph g(vec_ed, m_gn); auto neigh1 = g.getNeighNodes(0); BOOST_CHECK_EQUAL(neigh1.size(), 1); bool neigh1_found1 = neigh1.at(0).second == gn3; BOOST_CHECK(neigh1_found1); auto neigh3 = g.getNeighNodes(2); BOOST_CHECK_EQUAL(neigh3.size(), 3); bool neigh3_found1 = false; bool neigh3_found2 = false; bool neigh3_found3 = false; for (auto neigh_pr : neigh3) { if (neigh_pr.second == gn) { neigh3_found1 = true; } if (neigh_pr.second == gn2) { neigh3_found2 = true; } if (neigh_pr.second == gn) { neigh3_found3 = true; } } BOOST_CHECK(neigh3_found1); BOOST_CHECK(neigh3_found2); BOOST_CHECK(neigh3_found3); auto neigh4 = g.getNeighNodes(3); BOOST_CHECK_EQUAL(neigh4.size(), 1); bool neigh4_found1 = neigh4.at(0).second == gn3; BOOST_CHECK(neigh4_found1); auto neigh5 = g.getNeighNodes(4); BOOST_CHECK_EQUAL(neigh5.size(), 1); bool neigh5_found1 = neigh5.at(0).second == gn3; BOOST_CHECK(neigh5_found1); } BOOST_AUTO_TEST_CASE(expandedge_test) { // 0 - 1 - 2 - 3 -4 -5 // | | // 6 - 7 - 8 // ReducedEdge ed0(vector{0, 1}); ReducedEdge ed1(vector{1, 2, 3}); ReducedEdge ed2(vector{3, 4, 5}); ReducedEdge ed3(vector{1, 6, 7, 8, 3}); vector vec_ed{ed0, ed1, ed2, ed3}; ReducedGraph g(vec_ed); vector> edges = g.expandEdge(Edge(0, 1)); BOOST_CHECK_EQUAL(edges.size(), 1); BOOST_CHECK_EQUAL(edges.at(0).size(), 1); edges = g.expandEdge(Edge(1, 3)); BOOST_CHECK_EQUAL(edges.size(), 2); // Two separate chains if (edges.at(0).size() == 2) { bool found_ed1_2 = false; bool found_ed2_3 = false; Edge ed1_2(1, 2); Edge ed2_3(2, 3); for (auto e1 : edges.at(0)) { if (e1 == ed1_2) { found_ed1_2 = true; } if (e1 == ed2_3) { found_ed2_3 = true; } } BOOST_CHECK(found_ed1_2); BOOST_CHECK(found_ed2_3); Edge ed1_6(1, 6); Edge ed6_7(6, 7); Edge ed7_8(7, 8); Edge ed8_3(3, 8); bool found_ed1_6 = false; bool found_ed6_7 = false; bool found_ed7_8 = false; bool found_ed8_3 = false; for (auto e1 : edges.at(1)) { if (e1 == ed1_6) { found_ed1_6 = true; } if (e1 == ed6_7) { found_ed6_7 = true; } if (e1 == ed7_8) { found_ed7_8 = true; } if (e1 == ed8_3) { found_ed8_3 = true; } } BOOST_CHECK(found_ed1_6); BOOST_CHECK(found_ed6_7); BOOST_CHECK(found_ed7_8); BOOST_CHECK(found_ed8_3); } else if (edges.at(0).size() == 4) { bool found_ed1_2 = false; bool found_ed2_3 = false; Edge ed1_2(1, 2); Edge ed2_3(2, 3); for (auto e1 : edges.at(1)) { if (e1 == ed1_2) { found_ed1_2 = true; } if (e1 == ed2_3) { found_ed2_3 = true; } } BOOST_CHECK(found_ed1_2); BOOST_CHECK(found_ed2_3); Edge ed1_6(1, 6); Edge ed6_7(6, 7); Edge ed7_8(7, 8); Edge ed8_3(3, 8); bool found_ed1_6 = false; bool found_ed6_7 = false; bool found_ed7_8 = false; bool found_ed8_3 = false; for (auto e1 : edges.at(0)) { if (e1 == ed1_6) { found_ed1_6 = true; } if (e1 == ed6_7) { found_ed6_7 = true; } if (e1 == ed7_8) { found_ed7_8 = true; } if (e1 == ed8_3) { found_ed8_3 = true; } } BOOST_CHECK(found_ed1_6); BOOST_CHECK(found_ed6_7); BOOST_CHECK(found_ed7_8); BOOST_CHECK(found_ed8_3); } else { // ONe of the two options above should have been triggered BOOST_CHECK(false); } } BOOST_AUTO_TEST_CASE(getdegree_test) { // 9 // | // 0 - 1 - 2 - 3 -4 -5 // | | // 6 - 7 - 8 // ReducedEdge ed0(vector{0, 1}); ReducedEdge ed1(vector{1, 2, 3}); ReducedEdge ed2(vector{3, 4, 5}); ReducedEdge ed3(vector{1, 6, 7, 8, 3}); ReducedEdge ed4(3, 9); vector vec_ed{ed0, ed1, ed2, ed3, ed4}; ReducedGraph g(vec_ed); BOOST_CHECK_EQUAL(g.getMaxDegree(), 4); BOOST_CHECK_EQUAL(g.getDegree(0), 1); BOOST_CHECK_EQUAL(g.getDegree(1), 3); BOOST_CHECK_EQUAL(g.getDegree(3), 4); BOOST_CHECK_EQUAL(g.getDegree(5), 1); BOOST_CHECK_EQUAL(g.getDegree(9), 1); votca::Index degree = 0; auto vertices_w_degree = g.getVerticesDegree(degree); BOOST_CHECK_EQUAL(vertices_w_degree.size(), 0); degree = 1; vertices_w_degree = g.getVerticesDegree(degree); BOOST_CHECK_EQUAL(vertices_w_degree.size(), 3); degree = 2; vertices_w_degree = g.getVerticesDegree(degree); BOOST_CHECK_EQUAL(vertices_w_degree.size(), 0); degree = 3; vertices_w_degree = g.getVerticesDegree(degree); BOOST_CHECK_EQUAL(vertices_w_degree.size(), 1); degree = 4; vertices_w_degree = g.getVerticesDegree(degree); BOOST_CHECK_EQUAL(vertices_w_degree.size(), 1); } /** * \brief Equivalence test * * Here we demonstrate how the equivalence test works it is purely dependendent * on whether the contents of the graphnodes in the graph contain the same * information. */ BOOST_AUTO_TEST_CASE(id_test) { { unordered_map int_vals0 = {{"a", 0}}; unordered_map int_vals1 = {{"b", 1}}; unordered_map int_vals2 = {{"c", 2}}; unordered_map int_vals3 = {{"d", 3}}; unordered_map int_vals4 = {{"e", 4}}; unordered_map double_vals; unordered_map str_vals; vector vec_ed; ReducedEdge ed(std::vector{0, 1, 2}); ReducedEdge ed2(2, 3); ReducedEdge ed3(2, 4); vec_ed.push_back(ed); vec_ed.push_back(ed2); vec_ed.push_back(ed3); GraphNode gn(int_vals0, double_vals, str_vals); GraphNode gn1(int_vals1, double_vals, str_vals); GraphNode gn2(int_vals2, double_vals, str_vals); GraphNode gn3(int_vals3, double_vals, str_vals); GraphNode gn4(int_vals4, double_vals, str_vals); unordered_map m_gn; /// Here the graph nodes are assigne to different vertices m_gn[4] = gn; m_gn[1] = gn1; m_gn[3] = gn2; m_gn[2] = gn3; m_gn[0] = gn4; ReducedGraph g(vec_ed, m_gn); /// Here is what the string id of the graph should look like string str = "a0c2d3e4"; string s_id = g.getId(); BOOST_CHECK_EQUAL(s_id, str); ReducedGraph g2(vec_ed, m_gn); BOOST_CHECK(g == g2); /// Here we switch up which vertices contain which graphnodes and show that /// the graph id is the same. This is because the vertex ids are not used to /// create the id and neither the edges. Only the contens in the graphnodes m_gn[1] = gn3; m_gn[2] = gn1; ReducedGraph g3(vec_ed, m_gn); BOOST_CHECK(g != g3); string str2 = "a0b1c2e4"; string s_id2 = g3.getId(); BOOST_CHECK_EQUAL(s_id2, str2); GraphNode gn5(int_vals3, double_vals, str_vals); m_gn[5] = gn5; ReducedGraph g4(vec_ed, m_gn); BOOST_CHECK(g != g4); } } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_structureparameters.cc000066400000000000000000000041321412152065700223660ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE structureparameters_test // Standard includes #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/structureparameters.h" #include "votca/tools/types.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(structureparameters_test) BOOST_AUTO_TEST_CASE(constructors_test) { StructureParameters parameters; } BOOST_AUTO_TEST_CASE(set_test) { StructureParameters parameters; double mass = 2.0; parameters.set(StructureParameter::Mass, mass); string element_type = "C"; parameters.set(StructureParameter::Element, element_type); } BOOST_AUTO_TEST_CASE(get_test) { StructureParameters parameters; double mass = 2.0; parameters.set(StructureParameter::Mass, mass); double mass_check = parameters.get(StructureParameter::Mass); BOOST_CHECK_EQUAL(mass, mass_check); string element_type = "C"; parameters.set(StructureParameter::Element, element_type); string element_type_check = parameters.get(StructureParameter::Element); BOOST_CHECK_EQUAL(element_type, element_type_check); votca::Index molecule_id = 201; parameters.set(StructureParameter::MoleculeId, molecule_id); votca::Index molecule_id_check = parameters.get(StructureParameter::MoleculeId); BOOST_CHECK_EQUAL(molecule_id, molecule_id_check); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_table.cc000066400000000000000000000102421412152065700173300ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE table_test // Standard includes #include #include // Third party includes #include #include // Local VOTCA includes #include "votca/tools/table.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(table_test) BOOST_AUTO_TEST_CASE(create_test) { Table tb; Table tb2(tb); } BOOST_AUTO_TEST_CASE(size_test) { Table tb; BOOST_CHECK_EQUAL(tb.size(), 0); } BOOST_AUTO_TEST_CASE(pushback_test) { Table tb; for (double x = 0; x < 10; ++x) { double y = 2 * x; tb.push_back(x, y); } BOOST_CHECK_EQUAL(tb.size(), 10); } BOOST_AUTO_TEST_CASE(resize_test) { Table tb; tb.resize(0); tb.resize(10); bool error_thrown = false; try { tb.resize(-5); } catch (...) { error_thrown = true; } BOOST_CHECK(error_thrown); } BOOST_AUTO_TEST_CASE(xy_test) { Table tb; for (double x = 0; x < 10; ++x) { double y = 2 * x; tb.push_back(x, y); } auto x_v = tb.x(); auto y_v = tb.y(); for (votca::Index i = 0; i < 10; ++i) { votca::Index x = i; votca::Index y = 2 * x; BOOST_CHECK_EQUAL(static_cast(x_v(i)), static_cast(tb.x(i))); BOOST_CHECK_EQUAL(static_cast(y_v(i)), static_cast(tb.y(i))); BOOST_CHECK_EQUAL(x, static_cast(tb.x(i))); BOOST_CHECK_EQUAL(y, static_cast(tb.y(i))); BOOST_CHECK_EQUAL(x, static_cast(x_v(i))); BOOST_CHECK_EQUAL(y, static_cast(y_v(i))); } } BOOST_AUTO_TEST_CASE(getMinMax_test) { Table tb; for (double x = 0; x < 10; ++x) { double y = 2 * x; tb.push_back(x, y); } BOOST_CHECK_EQUAL(static_cast(tb.getMinX()), 0); BOOST_CHECK_EQUAL(static_cast(tb.getMaxX()), 9); BOOST_CHECK_EQUAL(static_cast(tb.getMinY()), 0); BOOST_CHECK_EQUAL(static_cast(tb.getMaxY()), 18); } BOOST_AUTO_TEST_CASE(generate_grid_spacing_test) { Table tb; double min_v = 1.2; double max_v = 2.0; tb.GenerateGridSpacing(min_v, max_v, 0.2); BOOST_CHECK_EQUAL(tb.size(), 5); BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5); BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5); } BOOST_AUTO_TEST_CASE(generate_grid_spacing_test_low) { Table tb; double min_v = 1.2; double max_v = 2.0; tb.GenerateGridSpacing(min_v, max_v, 0.3); BOOST_CHECK_EQUAL(tb.size(), 3); BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5); BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5); } BOOST_AUTO_TEST_CASE(generate_grid_spacing_test_high) { Table tb; double min_v = 1.2; double max_v = 2.0; tb.GenerateGridSpacing(min_v, max_v, 0.15); BOOST_CHECK_EQUAL(tb.size(), 6); BOOST_CHECK_CLOSE(tb.getMinX(), 1.2, 1e-5); BOOST_CHECK_CLOSE(tb.getMaxX(), 2.0, 1e-5); } BOOST_AUTO_TEST_CASE(smoothing_test) { Table tb; double min_v = 1.2; double max_v = 2.0; tb.GenerateGridSpacing(min_v, max_v, 0.1); BOOST_CHECK_EQUAL(tb.size(), 9); tb.y() = tb.x().array().sinh(); tb.Smooth(2); Eigen::VectorXd refy = Eigen::VectorXd::Zero(9); refy << 1.50946, 1.70595, 1.91384, 2.13995, 2.38747, 2.65889, 2.95692, 3.28227, 3.62686; bool equal = tb.y().isApprox(refy, 1e-5); if (!equal) { std::cout << "result value" << std::endl; std::cout << tb.y().transpose() << std::endl; std::cout << "ref value" << std::endl; std::cout << refy.transpose() << std::endl; } BOOST_CHECK_EQUAL(equal, true); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_thread.cc000066400000000000000000000053161412152065700175160ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE thread_test // Standard includes #include #include #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/thread.h" #include "votca/tools/types.h" using namespace std; using namespace votca::tools; class ThreadTest : public Thread { private: votca::Index factorial_; votca::Index sum_; public: votca::Index getFactorial() const { return sum_; } void setFactorial(votca::Index factorial) { factorial_ = factorial; } protected: void Run(void) override { sum_ = 1; for (votca::Index val = 2; val <= factorial_; ++val) { sum_ *= val; } } }; BOOST_AUTO_TEST_SUITE(thread_test) BOOST_AUTO_TEST_CASE(constructors_test) { ThreadTest threadtest; } BOOST_AUTO_TEST_CASE(start_to_finish_test) { ThreadTest threadtest; threadtest.setFactorial(3); threadtest.Start(); threadtest.WaitDone(); assert(threadtest.IsFinished()); assert(threadtest.getFactorial() == 6); } BOOST_AUTO_TEST_CASE(multiple_start_to_finish_test) { vector> threads; votca::Index numberThreads = 6; // Placing threads in a vector and initializing them for (votca::Index count = 0; count < numberThreads; ++count) { votca::Index factorial_value = count + 1; auto threadtest = make_shared(); threadtest->setFactorial(factorial_value); threads.push_back(threadtest); } // Running the threads for (votca::Index count = 0; count < numberThreads; ++count) { threads.at(count)->Start(); } // Wait until each of the threads is done for (votca::Index count = (numberThreads - 1); count >= 0; --count) { threads.at(count)->WaitDone(); } // Check the factorials assert(threads.at(0)->getFactorial() == 1); assert(threads.at(1)->getFactorial() == 2); assert(threads.at(2)->getFactorial() == 6); assert(threads.at(3)->getFactorial() == 24); assert(threads.at(4)->getFactorial() == 120); assert(threads.at(5)->getFactorial() == 720); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_tokenizer.cc000066400000000000000000000067711412152065700202670ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE tokenizer_test // Standard includes #include #include // Third party includes #include // Local VOTCA includes #include "votca/tools/tokenizer.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(tokenizer_test) BOOST_AUTO_TEST_CASE(constructors_test) { string str1 = "blah,ya"; string separators = ","; Tokenizer tok(str1, separators.c_str()); Tokenizer tok2(str1, separators); } BOOST_AUTO_TEST_CASE(tokenizer_test) { string str1 = "blah,ya"; string separators = ","; Tokenizer tok(str1, separators); std::vector result = tok.ToVector(); BOOST_CHECK_EQUAL(result[0], "blah"); BOOST_CHECK_EQUAL(result[1], "ya"); string str2 = ""; Tokenizer tok2(str2, separators); BOOST_CHECK_EQUAL(tok2.begin() == tok2.end(), true); std::vector result2 = tok2.ToVector(); BOOST_CHECK_EQUAL(result2.size(), 0); string str3 = "hello"; Tokenizer tok3(str3, separators); BOOST_CHECK_EQUAL(tok3.begin() == tok3.end(), false); std::vector result3 = tok3.ToVector(); BOOST_CHECK_EQUAL(result3[0], "hello"); } BOOST_AUTO_TEST_CASE(wildcmp_test) { string wildcard = ""; string potential_match = ""; auto out = wildcmp(wildcard.c_str(), potential_match.c_str()); BOOST_CHECK_EQUAL(out, 1); string wildcard2 = "file"; out = wildcmp(wildcard2.c_str(), potential_match.c_str()); BOOST_CHECK_EQUAL(out, 0); string potential_match2 = "file2"; out = wildcmp(wildcard.c_str(), potential_match2.c_str()); BOOST_CHECK_EQUAL(out, 0); out = wildcmp(wildcard2.c_str(), potential_match2.c_str()); BOOST_CHECK_EQUAL(out, 0); string wildcard3 = "file*"; out = wildcmp(wildcard3.c_str(), potential_match2.c_str()); BOOST_CHECK_EQUAL(out, 1); string wildcard4 = "file*.txt"; out = wildcmp(wildcard4.c_str(), potential_match2.c_str()); BOOST_CHECK_EQUAL(out, 0); string potential_match3 = "file1.txt"; out = wildcmp(wildcard4.c_str(), potential_match3.c_str()); BOOST_CHECK_EQUAL(out, 1); } BOOST_AUTO_TEST_CASE(wildcmp_test2) { string wildcard = ""; string potential_match = ""; auto out = wildcmp(wildcard, potential_match); BOOST_CHECK_EQUAL(out, 1); string wildcard2 = "file"; out = wildcmp(wildcard2, potential_match); BOOST_CHECK_EQUAL(out, 0); string potential_match2 = "file2"; out = wildcmp(wildcard, potential_match2); BOOST_CHECK_EQUAL(out, 0); out = wildcmp(wildcard2, potential_match2); BOOST_CHECK_EQUAL(out, 0); string wildcard3 = "file*"; out = wildcmp(wildcard3, potential_match2); BOOST_CHECK_EQUAL(out, 1); string wildcard4 = "file*.txt"; out = wildcmp(wildcard4, potential_match2); BOOST_CHECK_EQUAL(out, 0); string potential_match3 = "file1.txt"; out = wildcmp(wildcard4, potential_match3); BOOST_CHECK_EQUAL(out, 1); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tests/test_unitconverter.cc000066400000000000000000000223071412152065700211550ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE unitconverter_test // Standard includes #include // Third party includes #include // Local VOTCA includes #include "votca/tools/unitconverter.h" using namespace std; using namespace votca::tools; BOOST_AUTO_TEST_SUITE(unitconverter_test) BOOST_AUTO_TEST_CASE(unitconverter_test_distance) { UnitConverter converter; double distance = 1; // Assuming in meters double distance_new = converter.convert(DistanceUnit::meters, DistanceUnit::nanometers) * distance; BOOST_CHECK_EQUAL(1E9, distance_new); distance_new = converter.convert(DistanceUnit::meters, DistanceUnit::centimeters) * distance; BOOST_CHECK_EQUAL(100, distance_new); distance_new = converter.convert(DistanceUnit::meters, DistanceUnit::angstroms) * distance; BOOST_CHECK_EQUAL(1E10, distance_new); distance_new = converter.convert(DistanceUnit::meters, DistanceUnit::bohr) * distance; BOOST_CHECK_CLOSE(1.8897e+10, distance_new, 0.01); // Now assuming distance in angstroms distance_new = converter.convert(DistanceUnit::angstroms, DistanceUnit::nanometers) * distance; BOOST_CHECK_CLOSE(0.1, distance_new, 0.01); distance_new = converter.convert(DistanceUnit::angstroms, DistanceUnit::meters) * distance; BOOST_CHECK_CLOSE(1.E-10, distance_new, 0.01); // Now assuming distance in Bohr distance_new = converter.convert(DistanceUnit::nanometers, DistanceUnit::bohr) * distance; BOOST_CHECK_CLOSE(18.8973, distance_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_time) { UnitConverter converter; double time = 1; // Assuming in seconds double time_new = converter.convert(TimeUnit::seconds, TimeUnit::microseconds) * time; BOOST_CHECK_CLOSE(1E6, time_new, 0.01); time_new = converter.convert(TimeUnit::seconds, TimeUnit::nanoseconds) * time; BOOST_CHECK_CLOSE(1E9, time_new, 0.01); time_new = converter.convert(TimeUnit::seconds, TimeUnit::picoseconds) * time; BOOST_CHECK_CLOSE(1E12, time_new, 0.01); time_new = converter.convert(TimeUnit::seconds, TimeUnit::femtoseconds) * time; BOOST_CHECK_CLOSE(1E15, time_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_mass) { UnitConverter converter; double mass = 1; // Assuming in kilograms double mass_new = converter.convert(MassUnit::kilograms, MassUnit::grams) * mass; BOOST_CHECK_CLOSE(1E3, mass_new, 0.01); mass_new = converter.convert(MassUnit::kilograms, MassUnit::picograms) * mass; BOOST_CHECK_CLOSE(1E15, mass_new, 0.01); mass_new = converter.convert(MassUnit::kilograms, MassUnit::femtograms) * mass; BOOST_CHECK_CLOSE(1E18, mass_new, 0.01); mass_new = converter.convert(MassUnit::kilograms, MassUnit::attograms) * mass; BOOST_CHECK_CLOSE(1E21, mass_new, 0.01); mass_new = converter.convert(MassUnit::kilograms, MassUnit::atomic_mass_units) * mass; BOOST_CHECK_CLOSE(6.02213665E26, mass_new, 0.01); mass_new = converter.convert(MassUnit::kilograms, MassUnit::grams_per_mole) * mass; BOOST_CHECK_CLOSE(6.02213665E26, mass_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_energy) { UnitConverter converter; double energy = 1; // Assuming in electron volts double energy_new = converter.convert(EnergyUnit::electron_volts, EnergyUnit::electron_volts) * energy; BOOST_CHECK_CLOSE(1, energy_new, 0.01); energy_new = converter.convert(EnergyUnit::electron_volts, EnergyUnit::kilocalories) * energy; BOOST_CHECK_CLOSE(3.82929E-23, energy_new, 0.01); energy_new = converter.convert(EnergyUnit::electron_volts, EnergyUnit::joules) * energy; BOOST_CHECK_CLOSE(1.60218E-19, energy_new, 0.01); energy_new = converter.convert(EnergyUnit::electron_volts, EnergyUnit::hartrees) * energy; BOOST_CHECK_CLOSE(0.0367493, energy_new, 0.01); energy_new = converter.convert(EnergyUnit::electron_volts, EnergyUnit::kilojoules) * energy; BOOST_CHECK_CLOSE(1.602176E-22, energy_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_molar_energy) { UnitConverter converter; double energy = 1; // Assuming in electron volts double energy_new = converter.convert(MolarEnergyUnit::electron_volts_per_mole, MolarEnergyUnit::electron_volts_per_mole) * energy; BOOST_CHECK_CLOSE(1, energy_new, 0.01); energy_new = converter.convert(MolarEnergyUnit::electron_volts_per_mole, MolarEnergyUnit::kilocalories_per_mole) * energy; BOOST_CHECK_CLOSE(3.82929E-23, energy_new, 0.01); energy_new = converter.convert(MolarEnergyUnit::electron_volts_per_mole, MolarEnergyUnit::joules_per_mole) * energy; BOOST_CHECK_CLOSE(1.60218E-19, energy_new, 0.01); energy_new = converter.convert(MolarEnergyUnit::electron_volts_per_mole, MolarEnergyUnit::hartrees_per_mole) * energy; BOOST_CHECK_CLOSE(0.0367493, energy_new, 0.01); energy_new = converter.convert(MolarEnergyUnit::electron_volts_per_mole, MolarEnergyUnit::kilojoules_per_mole) * energy; BOOST_CHECK_CLOSE(1.602176E-22, energy_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_charge) { UnitConverter converter; double charge = 1.602176565E-19; // Assuming in units of coulombs double charge_new = converter.convert(ChargeUnit::coulombs, ChargeUnit::e) * charge; BOOST_CHECK_CLOSE(1.000, charge_new, 0.01); charge = 1; // Assuming in eV charge_new = converter.convert(ChargeUnit::e, ChargeUnit::coulombs) * charge; BOOST_CHECK_CLOSE(1.60217656E-19, charge_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_velocity) { UnitConverter converter; double velocity = 1; // Assuming in units of angstroms_per_femtosecond double velocity_new = converter.convert(VelocityUnit::angstroms_per_femtosecond, VelocityUnit::angstroms_per_picosecond) * velocity; BOOST_CHECK_CLOSE(1000, velocity_new, 0.01); velocity_new = converter.convert(VelocityUnit::angstroms_per_femtosecond, VelocityUnit::nanometers_per_picosecond) * velocity; BOOST_CHECK_CLOSE(100, velocity_new, 0.01); // Assuming in units of nanometers_per_picosecond velocity_new = converter.convert(VelocityUnit::nanometers_per_picosecond, VelocityUnit::angstroms_per_femtosecond) * velocity; BOOST_CHECK_CLOSE(0.01, velocity_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_force) { UnitConverter converter; double force = 1; // Assuming kilojoules_per_nanometer double force_new = converter.convert(ForceUnit::kilojoules_per_nanometer, ForceUnit::kilocalories_per_angstrom) * force; BOOST_CHECK_CLOSE(0.0239006, force_new, 0.01); force_new = converter.convert(ForceUnit::kilojoules_per_nanometer, ForceUnit::kilojoules_per_angstrom) * force; BOOST_CHECK_CLOSE(0.1, force_new, 0.01); force_new = converter.convert(ForceUnit::kilojoules_per_nanometer, ForceUnit::hatree_per_bohr) * force; BOOST_CHECK_CLOSE(1.2138E19, force_new, 0.01); force_new = converter.convert(ForceUnit::kilojoules_per_nanometer, ForceUnit::newtons) * force; BOOST_CHECK_CLOSE(1E12, force_new, 0.01); } BOOST_AUTO_TEST_CASE(unitconverter_test_molar_force) { UnitConverter converter; double force = 1; // Assuming kilojoules_per_mole_nanometer double force_new = converter.convert(MolarForceUnit::kilojoules_per_mole_nanometer, MolarForceUnit::kilocalories_per_mole_angstrom) * force; BOOST_CHECK_CLOSE(0.0239006, force_new, 0.01); force_new = converter.convert(MolarForceUnit::kilojoules_per_mole_nanometer, MolarForceUnit::kilojoules_per_mole_angstrom) * force; BOOST_CHECK_CLOSE(0.1, force_new, 0.01); force_new = converter.convert(MolarForceUnit::kilojoules_per_mole_nanometer, MolarForceUnit::hatree_per_mole_bohr) * force; BOOST_CHECK_CLOSE(1.2138E19, force_new, 0.01); force_new = converter.convert(MolarForceUnit::kilojoules_per_mole_nanometer, MolarForceUnit::newtons_per_mole) * force; BOOST_CHECK_CLOSE(1E12, force_new, 0.01); } BOOST_AUTO_TEST_SUITE_END() tools-2021.2/src/tools/000077500000000000000000000000001412152065700146725ustar00rootroot00000000000000tools-2021.2/src/tools/CMakeLists.txt000066400000000000000000000017131412152065700174340ustar00rootroot00000000000000foreach(PROG votca_property) file(GLOB ${PROG}_SOURCES ${PROG}*.cc) add_executable(${PROG} ${${PROG}_SOURCES}) target_link_libraries(${PROG} votca_tools) #not realy useful, re-enable whenever it is ready to replace csg_property install(TARGETS ${PROG} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) if (BUILD_MANPAGES) add_custom_command(OUTPUT ${PROG}.man COMMAND ${CMAKE_CURRENT_BINARY_DIR}/${PROG} --man > ${PROG}.man COMMENT "Building ${PROG} manpage" DEPENDS ${PROG}) add_custom_target(${PROG}_manpage DEPENDS ${PROG}.man) add_dependencies(manpages ${PROG}_manpage) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROG}.man DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 RENAME ${PROG}.1) endif (BUILD_MANPAGES) if(ENABLE_TESTING) add_test(integration_${PROG}Help ${PROG} --help) set_tests_properties(integration_${PROG}Help PROPERTIES LABELS "tools;votca;integration") endif(ENABLE_TESTING) endforeach(PROG) tools-2021.2/src/tools/votca_property.cc000066400000000000000000000055751412152065700202750ustar00rootroot00000000000000/* * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) * * 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. * */ // Standard includes #include // Third party includes #include #include #include // Local VOTCA includes #include "votca/tools/application.h" #include "votca/tools/globals.h" #include "votca/tools/property.h" #include "votca/tools/propertyiomanipulator.h" #include "votca/tools/version.h" using namespace std; using namespace votca::tools; namespace po = boost::program_options; class VotcaProperty : public Application { public: VotcaProperty(); ~VotcaProperty() override; string ProgramName() override { return "votca_property"; } void HelpText(ostream& out) override { out << "Helper for parsing XML files"; } void Initialize() override { format = "XML"; level = 1; AddProgramOptions()("file", po::value(), "xml file to parse")( "format", po::value(), "output format [XML TXT TEX]")( "level", po::value(), "output from this level "); }; bool EvaluateOptions() override { CheckRequired("file", "Missing XML file"); return true; }; void Run() override { file = _op_vm["file"].as(); if (_op_vm.count("format")) { format = _op_vm["format"].as(); } if (_op_vm.count("level")) { level = _op_vm["level"].as(); } try { Property p; map _mformat; _mformat["XML"] = &XML; _mformat["TXT"] = &TXT; _mformat["TEX"] = &TEX; _mformat["HLP"] = &HLP; p.LoadFromXML(file); if (_mformat.find(format) != _mformat.end()) { PropertyIOManipulator* piom = _mformat.find(format)->second; piom->setLevel(level); piom->setIndentation(""); piom->setColorScheme(); cout << *piom << p; } else { cout << "format " << format << " not supported \n"; } } catch (std::exception& error) { cerr << "an error occurred:\n" << error.what() << endl; } }; private: string file; string format; votca::Index level; }; VotcaProperty::VotcaProperty(void) = default; VotcaProperty::~VotcaProperty(void) = default; int main(int argc, char** argv) { VotcaProperty vp; return vp.Exec(argc, argv); }