From c2b5d43942f3b196725bb4138b1bb2e8b9a0fa48 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 26 Aug 2017 13:48:20 +0200 Subject: [PATCH 01/28] Use labelling to dispatch Green's functions --- doc/code-reference/greens-functions.rst | 14 ++++++++++ src/green/AnisotropicLiquid.hpp | 6 ++++ src/green/Green.hpp | 37 +++++++++++++++++++++---- src/green/IonicLiquid.hpp | 5 ++++ src/green/SphericalDiffuse.hpp | 6 ++++ src/green/UniformDielectric.hpp | 5 ++++ src/green/Vacuum.hpp | 5 ++++ src/interface/Input.cpp | 20 +++++++++---- 8 files changed, 88 insertions(+), 10 deletions(-) diff --git a/doc/code-reference/greens-functions.rst b/doc/code-reference/greens-functions.rst index 45f534eca..b94ee8cd4 100644 --- a/doc/code-reference/greens-functions.rst +++ b/doc/code-reference/greens-functions.rst @@ -7,6 +7,20 @@ Green's functions objects relies on the Factory Method pattern :cite:`Gamma1994,Alexandrescu2001`, implemented through the generic Factory class. +The top-level header, _i.e._ to be included in client code, is `Green.hpp`. +The common interface to all Green's function classes is specified by the `IGreensFunction` class, +this is non-templated. +All other classes are templated. TODO: explain template parameters. +The Green's functions are registered to the factory based on a label encoding: type, derivative, and dielectric profile. +The only allowed labels are: +- `VACUUM_NUMERICAL` +- `VACUUM_DERIVATIVE` +- `VACUMM_GRADIENT` +- `VACUUM_HESSIAN` + +- `SPHERICALDIFFUSE_TANH` +- `SPHERICALDIFFUSE_ERF` + .. image:: ../gfx/green.png :scale: 70 % :align: center diff --git a/src/green/AnisotropicLiquid.hpp b/src/green/AnisotropicLiquid.hpp index 2b0d0ce10..83fa24b7e 100644 --- a/src/green/AnisotropicLiquid.hpp +++ b/src/green/AnisotropicLiquid.hpp @@ -97,5 +97,11 @@ struct buildAnisotropicLiquid { } // namespace detail IGreensFunction * createAnisotropicLiquid(const GreenData & data); + +template +IGreensFunction * createAnisotropicLiquid(const GreenData & data) { + return new AnisotropicLiquid(data.epsilonTensor, + data.eulerAngles); +} } // namespace green } // namespace pcm diff --git a/src/green/Green.hpp b/src/green/Green.hpp index d0c41d848..d0187138f 100644 --- a/src/green/Green.hpp +++ b/src/green/Green.hpp @@ -53,11 +53,38 @@ typedef pcm::function CreateGreensFunction inline Factory bootstrapFactory() { Factory factory_; - factory_.subscribe("VACUUM", createVacuum); - factory_.subscribe("UNIFORMDIELECTRIC", createUniformDielectric); - factory_.subscribe("SPHERICALDIFFUSE", createSphericalDiffuse); - factory_.subscribe("IONICLIQUID", createIonicLiquid); - factory_.subscribe("ANISOTROPICLIQUID", createAnisotropicLiquid); + factory_.subscribe("VACUUM_NUMERICAL", createVacuum); + factory_.subscribe("VACUUM_DERIVATIVE", createVacuum); + factory_.subscribe("VACUUM_GRADIENT", createVacuum); + factory_.subscribe("VACUUM_HESSIAN", createVacuum); + + factory_.subscribe("UNIFORMDIELECTRIC_NUMERICAL", + createUniformDielectric); + factory_.subscribe("UNIFORMDIELECTRIC_DERIVATIVE", + createUniformDielectric); + factory_.subscribe("UNIFORMDIELECTRIC_GRADIENT", + createUniformDielectric); + factory_.subscribe("UNIFORMDIELECTRIC_HESSIAN", + createUniformDielectric); + + factory_.subscribe("IONICLIQUID_NUMERICAL", createIonicLiquid); + factory_.subscribe("IONICLIQUID_DERIVATIVE", createIonicLiquid); + factory_.subscribe("IONICLIQUID_GRADIENT", createIonicLiquid); + factory_.subscribe("IONICLIQUID_HESSIAN", createIonicLiquid); + + factory_.subscribe("ANISOTROPICLIQUID_NUMERICAL", + createAnisotropicLiquid); + factory_.subscribe("ANISOTROPICLIQUID_DERIVATIVE", + createAnisotropicLiquid); + factory_.subscribe("ANISOTROPICLIQUID_GRADIENT", + createAnisotropicLiquid); + factory_.subscribe("ANISOTROPICLIQUID_HESSIAN", + createAnisotropicLiquid); + + factory_.subscribe("SPHERICALDIFFUSE_NUMERICAL_TANH", + createSphericalDiffuse); + factory_.subscribe("SPHERICALDIFFUSE_NUMERICAL_ERF", + createSphericalDiffuse); return factory_; } diff --git a/src/green/IonicLiquid.hpp b/src/green/IonicLiquid.hpp index e31a2e55a..ede91574b 100644 --- a/src/green/IonicLiquid.hpp +++ b/src/green/IonicLiquid.hpp @@ -93,5 +93,10 @@ struct buildIonicLiquid { } // namespace detail IGreensFunction * createIonicLiquid(const GreenData & data); + +template +IGreensFunction * createIonicLiquid(const GreenData & data) { + return new IonicLiquid(data.epsilon, data.kappa); +} } // namespace green } // namespace pcm diff --git a/src/green/SphericalDiffuse.hpp b/src/green/SphericalDiffuse.hpp index d44c914d2..d4df86e13 100644 --- a/src/green/SphericalDiffuse.hpp +++ b/src/green/SphericalDiffuse.hpp @@ -272,5 +272,11 @@ struct buildSphericalDiffuse { } // namespace detail IGreensFunction * createSphericalDiffuse(const GreenData & data); + +template +IGreensFunction * createSphericalDiffuse(const GreenData & data) { + return new SphericalDiffuse( + data.epsilon1, data.epsilon2, data.width, data.center, data.origin, data.maxL); +} } // namespace green } // namespace pcm diff --git a/src/green/UniformDielectric.hpp b/src/green/UniformDielectric.hpp index 3dc4dd00c..23bba672e 100644 --- a/src/green/UniformDielectric.hpp +++ b/src/green/UniformDielectric.hpp @@ -92,5 +92,10 @@ struct buildUniformDielectric { } // namespace detail IGreensFunction * createUniformDielectric(const GreenData & data); + +template +IGreensFunction * createUniformDielectric(const GreenData & data) { + return new UniformDielectric(data.epsilon); +} } // namespace green } // namespace pcm diff --git a/src/green/Vacuum.hpp b/src/green/Vacuum.hpp index d76640683..202e9bc5f 100644 --- a/src/green/Vacuum.hpp +++ b/src/green/Vacuum.hpp @@ -93,5 +93,10 @@ struct buildVacuum { } // namespace detail IGreensFunction * createVacuum(const GreenData & data); + +template +IGreensFunction * createVacuum(const GreenData & /* data */) { + return new Vacuum(); +} } // namespace green } // namespace pcm diff --git a/src/interface/Input.cpp b/src/interface/Input.cpp index 6bc64909c..fc12e5aba 100644 --- a/src/interface/Input.cpp +++ b/src/interface/Input.cpp @@ -119,18 +119,20 @@ void Input::reader(const std::string & filename) { // Get the contents of the Green section... const Section & inside = medium.getSect("GREEN"); // ...and initialize the data members - greenInsideType_ = inside.getStr("TYPE"); + greenInsideType_ = inside.getStr("TYPE") + "_" + inside.getStr("DER"); + // TODO Clean up derivative determination derivativeInsideType_ = detail::derivativeTraits(inside.getStr("DER")); epsilonInside_ = inside.getDbl("EPS"); // Get the contents of the Green section... const Section & outside = medium.getSect("GREEN"); // ...and initialize the data members - greenOutsideType_ = outside.getStr("TYPE"); + greenOutsideType_ = outside.getStr("TYPE") + "_" + outside.getStr("DER"); + // TODO Clean up derivative determination derivativeOutsideType_ = detail::derivativeTraits(outside.getStr("DER")); epsilonStaticOutside_ = outside.getDbl("EPS"); epsilonDynamicOutside_ = outside.getDbl("EPSDYN"); // This will be needed for the metal sphere only - if (greenOutsideType_ == "METALSPHERE") { + if (outside.getStr("TYPE") == "METALSPHERE") { epsilonReal_ = outside.getDbl("EPSRE"); epsilonImaginary_ = outside.getDbl("EPSIMG"); spherePosition_ = outside.getDblVec("SPHEREPOSITION"); @@ -143,6 +145,10 @@ void Input::reader(const std::string & filename) { center_ = outside.getDbl("CENTER"); width_ = outside.getDbl("WIDTH"); origin_ = outside.getDblVec("INTERFACEORIGIN"); + if (outside.getStr("TYPE") == "SPHERICALDIFFUSE") { + greenOutsideType_ += "_" + outside.getStr("PROFILE"); + } + // TODO Clean up profile determination profileType_ = detail::profilePolicy(outside.getStr("PROFILE")); maxL_ = outside.getInt("MAXL"); } else { // This part must be reviewed!! Some data members are not initialized... @@ -157,10 +163,10 @@ void Input::reader(const std::string & filename) { // Specification of the solvent by name means isotropic PCM // We have to initialize the Green's functions data here, Solvent class // is an helper class and should not be used in the core classes. - greenInsideType_ = "VACUUM"; + greenInsideType_ = "VACUUM_DERIVATIVE"; derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonInside_ = 1.0; - greenOutsideType_ = "UNIFORMDIELECTRIC"; + greenOutsideType_ = "UNIFORMDIELECTRIC_DERIVATIVE"; derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonStaticOutside_ = solvent_.epsStatic; epsilonDynamicOutside_ = solvent_.epsDynamic; @@ -244,11 +250,13 @@ void Input::reader(const PCMInput & host_input) { // Get the contents of the Green section... // ...and initialize the data members greenInsideType_ = detail::trim_and_upper(host_input.inside_type); + greenInsideType_ += "_DERIVATIVE"; derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonInside_ = 1.0; // Get the contents of the Green section... // ...and initialize the data members greenOutsideType_ = detail::trim_and_upper(host_input.outside_type); + greenOutsideType_ += "_DERIVATIVE"; derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonStaticOutside_ = host_input.outside_epsilon; epsilonDynamicOutside_ = host_input.outside_epsilon; @@ -271,9 +279,11 @@ void Input::reader(const PCMInput & host_input) { // We have to initialize the Green's functions data here, Solvent class // is an helper class and should not be used in the core classes. greenInsideType_ = std::string("VACUUM"); + greenInsideType_ += "_DERIVATIVE"; derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonInside_ = 1.0; greenOutsideType_ = std::string("UNIFORMDIELECTRIC"); + greenOutsideType_ += "_DERIVATIVE"; derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonStaticOutside_ = solvent_.epsStatic; epsilonDynamicOutside_ = solvent_.epsDynamic; From b46dd66922636551907886f28eaf1805e2d5a476 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 00:07:47 +0100 Subject: [PATCH 02/28] Clean up, MPL almost completely out --- src/bi_operators/BIOperatorData.hpp | 7 +- src/cavity/CavityData.hpp | 8 +- src/green/AnisotropicLiquid.cpp | 7 - src/green/AnisotropicLiquid.hpp | 11 - src/green/CMakeLists.txt | 2 +- src/green/DerivativeTypes.hpp | 20 +- src/green/DerivativeUtils.hpp | 41 -- src/green/Green.hpp | 1 + src/green/GreenData.hpp | 16 +- src/green/IonicLiquid.cpp | 7 - src/green/IonicLiquid.hpp | 11 - src/green/SphericalDiffuse.cpp | 9 - src/green/SphericalDiffuse.hpp | 15 - src/green/SphericalSharp.hpp | 1 - src/green/UniformDielectric.cpp | 7 - src/green/UniformDielectric.hpp | 16 +- src/green/Vacuum.cpp | 7 - src/green/Vacuum.hpp | 10 - src/green/dielectric_profile/ProfileTypes.hpp | 31 +- src/interface/Input.cpp | 68 +-- src/interface/Input.hpp | 32 +- src/interface/Meddle.cpp | 26 +- src/solver/SolverData.hpp | 11 +- src/utils/CMakeLists.txt | 9 +- src/utils/ForId.hpp | 533 ------------------ tests/input/input_diffuse.cpp | 20 +- tests/input/input_multipoles.cpp | 20 +- tests/input/input_restart.cpp | 20 +- tests/input/input_tsless.cpp | 20 +- tests/input/input_wavelet.cpp | 20 +- 30 files changed, 140 insertions(+), 866 deletions(-) delete mode 100644 src/green/DerivativeUtils.hpp delete mode 100644 src/utils/ForId.hpp diff --git a/src/bi_operators/BIOperatorData.hpp b/src/bi_operators/BIOperatorData.hpp index f9e56545c..b76a0df76 100644 --- a/src/bi_operators/BIOperatorData.hpp +++ b/src/bi_operators/BIOperatorData.hpp @@ -32,12 +32,17 @@ namespace pcm { * \brief Contains all data defined from user input to set up the bi_operators */ struct BIOperatorData { + /*! Type of boundary integral operator */ + std::string integratorType; /*! Scaling for the diagonal of the approximate collocation matrices */ double scaling; /*! Whether the structure was initialized with user input or not */ bool empty; BIOperatorData() { empty = true; } - BIOperatorData(double s) : scaling(s) { empty = false; } + BIOperatorData(const std::string & type, double s) + : integratorType(type), scaling(s) { + empty = false; + } }; } // namespace pcm diff --git a/src/cavity/CavityData.hpp b/src/cavity/CavityData.hpp index ce7514128..af12559ba 100644 --- a/src/cavity/CavityData.hpp +++ b/src/cavity/CavityData.hpp @@ -35,6 +35,8 @@ namespace pcm { struct CavityData { + /*! The type of cavity */ + std::string cavityType; /*! Molecule object with the relevant data for cavity generation */ Molecule molecule; /*! The average tesserae area. Relevant for GePolCavity */ @@ -62,7 +64,8 @@ struct CavityData { bool empty; CavityData() { empty = true; } - CavityData(const Molecule & _molec, + CavityData(const std::string & type, + const Molecule & _molec, double _area, double _probeRadius, double _minDistance, @@ -72,7 +75,8 @@ struct CavityData { double _coarsity, const std::string & _fname, const std::string & _dyad) - : molecule(_molec), + : cavityType(type), + molecule(_molec), area(_area), probeRadius(_probeRadius), minDistance(_minDistance), diff --git a/src/green/AnisotropicLiquid.cpp b/src/green/AnisotropicLiquid.cpp index 789e00890..1e1702d17 100644 --- a/src/green/AnisotropicLiquid.cpp +++ b/src/green/AnisotropicLiquid.cpp @@ -30,12 +30,10 @@ #include #include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" #include "dielectric_profile/Anisotropic.hpp" -#include "utils/ForId.hpp" namespace pcm { using cavity::Element; @@ -130,10 +128,5 @@ template class AnisotropicLiquid; template class AnisotropicLiquid; template class AnisotropicLiquid; template class AnisotropicLiquid; - -IGreensFunction * createAnisotropicLiquid(const GreenData & data) { - detail::buildAnisotropicLiquid build; - return for_id(build, data, data.howDerivative); -} } // namespace green } // namespace pcm diff --git a/src/green/AnisotropicLiquid.hpp b/src/green/AnisotropicLiquid.hpp index 83fa24b7e..13bb4aa81 100644 --- a/src/green/AnisotropicLiquid.hpp +++ b/src/green/AnisotropicLiquid.hpp @@ -41,7 +41,6 @@ class Anisotropic; } // namespace dielectric_profile } // namespace pcm -#include "DerivativeTypes.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" @@ -88,16 +87,6 @@ class AnisotropicLiquid __final virtual std::ostream & printObject(std::ostream & os) __override; }; -namespace detail { -struct buildAnisotropicLiquid { - template IGreensFunction * operator()(const GreenData & data) { - return new AnisotropicLiquid(data.epsilonTensor, data.eulerAngles); - } -}; -} // namespace detail - -IGreensFunction * createAnisotropicLiquid(const GreenData & data); - template IGreensFunction * createAnisotropicLiquid(const GreenData & data) { return new AnisotropicLiquid(data.epsilonTensor, diff --git a/src/green/CMakeLists.txt b/src/green/CMakeLists.txt index ec91551dd..20ff8a85e 100644 --- a/src/green/CMakeLists.txt +++ b/src/green/CMakeLists.txt @@ -1,5 +1,5 @@ # List of headers -list(APPEND headers_list Green.hpp AnisotropicLiquid.hpp DerivativeTypes.hpp DerivativeUtils.hpp GreenData.hpp GreenUtils.hpp GreensFunction.hpp +list(APPEND headers_list Green.hpp AnisotropicLiquid.hpp DerivativeTypes.hpp GreenData.hpp GreenUtils.hpp GreensFunction.hpp IGreensFunction.hpp InterfacesImpl.hpp IonicLiquid.hpp SphericalDiffuse.hpp SphericalSharp.hpp UniformDielectric.hpp Vacuum.hpp) diff --git a/src/green/DerivativeTypes.hpp b/src/green/DerivativeTypes.hpp index 7f9fdb955..f7937fff0 100644 --- a/src/green/DerivativeTypes.hpp +++ b/src/green/DerivativeTypes.hpp @@ -27,16 +27,24 @@ #include "taylor.hpp" -#include - namespace pcm { typedef double Stencil; typedef taylor AD_directional; typedef taylor AD_gradient; typedef taylor AD_hessian; -namespace green { -typedef boost::mpl::vector - derivative_types; -} // namespace green +template +inline DerivativeTraits distance(DerivativeTraits u[3], DerivativeTraits v[3]) { + return sqrt(pow(u[0] - v[0], 2) + pow(u[1] - v[1], 2) + pow(u[2] - v[2], 2)); +} + +template +inline DerivativeTraits norm(DerivativeTraits u[3]) { + return sqrt(pow(u[0], 2) + pow(u[1], 2) + pow(u[2], 2)); +} + +template +inline DerivativeTraits dot_product(DerivativeTraits u[3], DerivativeTraits v[3]) { + return (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]); +} } // namespace pcm diff --git a/src/green/DerivativeUtils.hpp b/src/green/DerivativeUtils.hpp deleted file mode 100644 index 012ed8721..000000000 --- a/src/green/DerivativeUtils.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * PCMSolver, an API for the Polarizable Continuum Model - * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. - * - * This file is part of PCMSolver. - * - * PCMSolver is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PCMSolver is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with PCMSolver. If not, see . - * - * For information on the complete list of contributors to the - * PCMSolver API, see: - */ - -#pragma once - -#include "Config.hpp" - -template -inline DerivativeTraits distance(DerivativeTraits u[3], DerivativeTraits v[3]) { - return sqrt(pow(u[0] - v[0], 2) + pow(u[1] - v[1], 2) + pow(u[2] - v[2], 2)); -} - -template -inline DerivativeTraits norm(DerivativeTraits u[3]) { - return sqrt(pow(u[0], 2) + pow(u[1], 2) + pow(u[2], 2)); -} - -template -inline DerivativeTraits dot_product(DerivativeTraits u[3], DerivativeTraits v[3]) { - return (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]); -} diff --git a/src/green/Green.hpp b/src/green/Green.hpp index d0187138f..d601d7302 100644 --- a/src/green/Green.hpp +++ b/src/green/Green.hpp @@ -26,6 +26,7 @@ #include "Config.hpp" #include "AnisotropicLiquid.hpp" +#include "DerivativeTypes.hpp" #include "GreenData.hpp" #include "IGreensFunction.hpp" #include "IonicLiquid.hpp" diff --git a/src/green/GreenData.hpp b/src/green/GreenData.hpp index 6f4e5b685..9dccc9c87 100644 --- a/src/green/GreenData.hpp +++ b/src/green/GreenData.hpp @@ -23,6 +23,7 @@ #pragma once +#include #include #include "Config.hpp" @@ -35,10 +36,11 @@ namespace pcm { struct GreenData { - /*! The way the derivatives of the Green's function are evaluated */ - int howDerivative; - /*! Dielectric profile type */ - int howProfile; + /*! The Green's function type inside the cavity. + * It encodes the Green's function type, derivative calculation strategy and + * dielectric profile: TYPE_DERIVATIVE_PROFILE + */ + std::string greensFunctionType; /*! The permittivity */ double epsilon; /*! Inverse of the Debye length */ @@ -72,8 +74,7 @@ struct GreenData { bool empty; GreenData() { empty = true; } - GreenData(int how_d, - int how_p, + GreenData(const std::string & type, double _epsilon = 1.0, double _kappa = 0.0, const Eigen::Vector3d & epstens = Eigen::Vector3d::Zero(), @@ -88,8 +89,7 @@ struct GreenData { double _w = 5.0, const Eigen::Vector3d & _o = Eigen::Vector3d::Zero(), int l = 30) - : howDerivative(how_d), - howProfile(how_p), + : greensFunctionType(type), epsilon(_epsilon), kappa(_kappa), epsilonTensor(epstens), diff --git a/src/green/IonicLiquid.cpp b/src/green/IonicLiquid.cpp index a8a3d9e7e..8ae6b1649 100644 --- a/src/green/IonicLiquid.cpp +++ b/src/green/IonicLiquid.cpp @@ -30,12 +30,10 @@ #include #include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" #include "dielectric_profile/Yukawa.hpp" -#include "utils/ForId.hpp" namespace pcm { using cavity::Element; @@ -109,10 +107,5 @@ template class IonicLiquid; template class IonicLiquid; template class IonicLiquid; template class IonicLiquid; - -IGreensFunction * createIonicLiquid(const GreenData & data) { - detail::buildIonicLiquid build; - return for_id(build, data, data.howDerivative); -} } // namespace green } // namespace pcm diff --git a/src/green/IonicLiquid.hpp b/src/green/IonicLiquid.hpp index ede91574b..537122e39 100644 --- a/src/green/IonicLiquid.hpp +++ b/src/green/IonicLiquid.hpp @@ -41,7 +41,6 @@ struct Yukawa; } // namespace dielectric_profile } // namespace pcm -#include "DerivativeTypes.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" @@ -84,16 +83,6 @@ class IonicLiquid __final virtual std::ostream & printObject(std::ostream & os) __override; }; -namespace detail { -struct buildIonicLiquid { - template IGreensFunction * operator()(const GreenData & data) { - return new IonicLiquid(data.epsilon, data.kappa); - } -}; -} // namespace detail - -IGreensFunction * createIonicLiquid(const GreenData & data); - template IGreensFunction * createIonicLiquid(const GreenData & data) { return new IonicLiquid(data.epsilon, data.kappa); diff --git a/src/green/SphericalDiffuse.cpp b/src/green/SphericalDiffuse.cpp index c07015208..edb80533f 100644 --- a/src/green/SphericalDiffuse.cpp +++ b/src/green/SphericalDiffuse.cpp @@ -34,13 +34,10 @@ // Boost.Math includes #include -#include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" #include "dielectric_profile/ProfileTypes.hpp" -#include "utils/ForId.hpp" #include "utils/MathUtils.hpp" namespace pcm { @@ -443,11 +440,5 @@ template class SphericalDiffuse; using dielectric_profile::OneLayerErf; template class SphericalDiffuse; - -IGreensFunction * createSphericalDiffuse(const GreenData & data) { - detail::buildSphericalDiffuse build; - return for_id( - build, data, data.howProfile); -} } // namespace green } // namespace pcm diff --git a/src/green/SphericalDiffuse.hpp b/src/green/SphericalDiffuse.hpp index d4df86e13..7e66cc4b7 100644 --- a/src/green/SphericalDiffuse.hpp +++ b/src/green/SphericalDiffuse.hpp @@ -258,21 +258,6 @@ class SphericalDiffuse __final : public GreensFunction { /*! @}*/ }; -namespace detail { -struct buildSphericalDiffuse { - template IGreensFunction * operator()(const GreenData & data) { - return new SphericalDiffuse(data.epsilon1, - data.epsilon2, - data.width, - data.center, - data.origin, - data.maxL); - } -}; -} // namespace detail - -IGreensFunction * createSphericalDiffuse(const GreenData & data); - template IGreensFunction * createSphericalDiffuse(const GreenData & data) { return new SphericalDiffuse( diff --git a/src/green/SphericalSharp.hpp b/src/green/SphericalSharp.hpp index 04ace5cc0..85538b90b 100644 --- a/src/green/SphericalSharp.hpp +++ b/src/green/SphericalSharp.hpp @@ -32,7 +32,6 @@ #include #include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreensFunction.hpp" #include "bi_operators/IntegratorForward.hpp" #include "dielectric_profile/Sharp.hpp" diff --git a/src/green/UniformDielectric.cpp b/src/green/UniformDielectric.cpp index 1bc0482c7..69169477b 100644 --- a/src/green/UniformDielectric.cpp +++ b/src/green/UniformDielectric.cpp @@ -30,12 +30,10 @@ #include #include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" #include "dielectric_profile/Uniform.hpp" -#include "utils/ForId.hpp" namespace pcm { using cavity::Element; @@ -110,10 +108,5 @@ template class UniformDielectric; template class UniformDielectric; template class UniformDielectric; template class UniformDielectric; - -IGreensFunction * createUniformDielectric(const GreenData & data) { - detail::buildUniformDielectric build; - return for_id(build, data, data.howDerivative); -} } // namespace green } // namespace pcm diff --git a/src/green/UniformDielectric.hpp b/src/green/UniformDielectric.hpp index 23bba672e..1f66009d1 100644 --- a/src/green/UniformDielectric.hpp +++ b/src/green/UniformDielectric.hpp @@ -1,4 +1,4 @@ -/* +/** * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -35,25 +35,23 @@ namespace pcm { namespace cavity { class Element; } // namespace cavity - namespace dielectric_profile { struct Uniform; } // namespace dielectric_profile } // namespace pcm -#include "DerivativeTypes.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" namespace pcm { namespace green { -template /*! \class UniformDielectric * \brief Green's function for uniform dielectric. * \author Luca Frediani and Roberto Di Remigio * \date 2012-2016 * \tparam DerivativeTraits evaluation strategy for the function and its derivatives */ +template class UniformDielectric __final : public GreensFunction { public: @@ -83,16 +81,6 @@ class UniformDielectric __final virtual std::ostream & printObject(std::ostream & os) __override; }; -namespace detail { -struct buildUniformDielectric { - template IGreensFunction * operator()(const GreenData & data) { - return new UniformDielectric(data.epsilon); - } -}; -} // namespace detail - -IGreensFunction * createUniformDielectric(const GreenData & data); - template IGreensFunction * createUniformDielectric(const GreenData & data) { return new UniformDielectric(data.epsilon); diff --git a/src/green/Vacuum.cpp b/src/green/Vacuum.cpp index 2abe23a3d..8cfb36c87 100644 --- a/src/green/Vacuum.cpp +++ b/src/green/Vacuum.cpp @@ -30,11 +30,9 @@ #include #include "DerivativeTypes.hpp" -#include "DerivativeUtils.hpp" #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" -#include "utils/ForId.hpp" namespace pcm { using cavity::Element; @@ -97,10 +95,5 @@ template class Vacuum; template class Vacuum; template class Vacuum; template class Vacuum; - -IGreensFunction * createVacuum(const GreenData & data) { - detail::buildVacuum build; - return for_id(build, data, data.howDerivative); -} } // namespace green } // namespace pcm diff --git a/src/green/Vacuum.hpp b/src/green/Vacuum.hpp index 202e9bc5f..afa7d7d27 100644 --- a/src/green/Vacuum.hpp +++ b/src/green/Vacuum.hpp @@ -84,16 +84,6 @@ class Vacuum __final virtual std::ostream & printObject(std::ostream & os) __override; }; -namespace detail { -struct buildVacuum { - template IGreensFunction * operator()(const GreenData & /* data */) { - return new Vacuum(); - } -}; -} // namespace detail - -IGreensFunction * createVacuum(const GreenData & data); - template IGreensFunction * createVacuum(const GreenData & /* data */) { return new Vacuum(); diff --git a/src/green/dielectric_profile/ProfileTypes.hpp b/src/green/dielectric_profile/ProfileTypes.hpp index 61b806bc2..345919070 100644 --- a/src/green/dielectric_profile/ProfileTypes.hpp +++ b/src/green/dielectric_profile/ProfileTypes.hpp @@ -26,7 +26,6 @@ #include "Config.hpp" #include -#include #include #include "Anisotropic.hpp" @@ -40,26 +39,16 @@ namespace pcm { namespace dielectric_profile { -/*! All possible profile types */ -typedef boost::mpl::vector - profile_types; - -/*! One-layer diffuse profile types */ -typedef boost::mpl::vector onelayer_diffuse_profile_types; - -/*! Two-layer (aka membrane-like) diffuse profile types */ -typedef boost::mpl::vector membrane_diffuse_profile_types; - -/*! An object of Permittivity type can have one of the types in the type sequence - * profile_types */ -typedef boost::make_variant_over::type Permittivity; +/*! An object of Permittivity type can have one of the dielectric_profile types */ +typedef boost::variant + Permittivity; class isUniform : public boost::static_visitor { public: diff --git a/src/interface/Input.cpp b/src/interface/Input.cpp index fc12e5aba..f1767e9f1 100644 --- a/src/interface/Input.cpp +++ b/src/interface/Input.cpp @@ -71,13 +71,13 @@ void Input::reader(const std::string & filename) { const Section & cavity = input_.getSect("CAVITY"); - type_ = cavity.getStr("TYPE"); + cavityType_ = cavity.getStr("TYPE"); area_ = cavity.getDbl("AREA"); patchLevel_ = cavity.getInt("PATCHLEVEL"); coarsity_ = cavity.getDbl("COARSITY"); minDistance_ = cavity.getDbl("MINDISTANCE"); derOrder_ = cavity.getInt("DERORDER"); - if (type_ == "RESTART") { + if (cavityType_ == "RESTART") { cavFilename_ = cavity.getStr("NPZFILE"); } dyadicFilename_ = cavity.getStr("DYADICFILE"); @@ -120,15 +120,11 @@ void Input::reader(const std::string & filename) { const Section & inside = medium.getSect("GREEN"); // ...and initialize the data members greenInsideType_ = inside.getStr("TYPE") + "_" + inside.getStr("DER"); - // TODO Clean up derivative determination - derivativeInsideType_ = detail::derivativeTraits(inside.getStr("DER")); epsilonInside_ = inside.getDbl("EPS"); // Get the contents of the Green section... const Section & outside = medium.getSect("GREEN"); // ...and initialize the data members greenOutsideType_ = outside.getStr("TYPE") + "_" + outside.getStr("DER"); - // TODO Clean up derivative determination - derivativeOutsideType_ = detail::derivativeTraits(outside.getStr("DER")); epsilonStaticOutside_ = outside.getDbl("EPS"); epsilonDynamicOutside_ = outside.getDbl("EPSDYN"); // This will be needed for the metal sphere only @@ -148,8 +144,6 @@ void Input::reader(const std::string & filename) { if (outside.getStr("TYPE") == "SPHERICALDIFFUSE") { greenOutsideType_ += "_" + outside.getStr("PROFILE"); } - // TODO Clean up profile determination - profileType_ = detail::profilePolicy(outside.getStr("PROFILE")); maxL_ = outside.getInt("MAXL"); } else { // This part must be reviewed!! Some data members are not initialized... // Just initialize the solvent object in this class @@ -164,10 +158,8 @@ void Input::reader(const std::string & filename) { // We have to initialize the Green's functions data here, Solvent class // is an helper class and should not be used in the core classes. greenInsideType_ = "VACUUM_DERIVATIVE"; - derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonInside_ = 1.0; greenOutsideType_ = "UNIFORMDIELECTRIC_DERIVATIVE"; - derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); epsilonStaticOutside_ = solvent_.epsStatic; epsilonDynamicOutside_ = solvent_.epsDynamic; } @@ -220,13 +212,13 @@ void Input::reader(const PCMInput & host_input) { CODATAyear_ = 2010; initBohrToAngstrom(bohrToAngstrom, CODATAyear_); - type_ = detail::trim_and_upper(host_input.cavity_type); + cavityType_ = detail::trim_and_upper(host_input.cavity_type); area_ = host_input.area * angstrom2ToBohr2(); patchLevel_ = host_input.patch_level; coarsity_ = host_input.coarsity * angstromToBohr(); minDistance_ = host_input.min_distance * angstromToBohr(); derOrder_ = host_input.der_order; - if (type_ == "RESTART") { + if (cavityType_ == "RESTART") { cavFilename_ = detail::trim(host_input.restart_name); // No case conversion here! } @@ -249,15 +241,13 @@ void Input::reader(const PCMInput & host_input) { probeRadius_ = host_input.probe_radius * angstromToBohr(); // Get the contents of the Green section... // ...and initialize the data members - greenInsideType_ = detail::trim_and_upper(host_input.inside_type); - greenInsideType_ += "_DERIVATIVE"; - derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); + greenInsideType_ = + detail::trim_and_upper(host_input.inside_type) + "_DERIVATIVE"; epsilonInside_ = 1.0; // Get the contents of the Green section... // ...and initialize the data members - greenOutsideType_ = detail::trim_and_upper(host_input.outside_type); - greenOutsideType_ += "_DERIVATIVE"; - derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); + greenOutsideType_ = + detail::trim_and_upper(host_input.outside_type) + "_DERIVATIVE"; epsilonStaticOutside_ = host_input.outside_epsilon; epsilonDynamicOutside_ = host_input.outside_epsilon; // Initialize interface parameters with bogus values @@ -268,7 +258,6 @@ void Input::reader(const PCMInput & host_input) { center_ = 0.0; width_ = 0.0; origin_ = std::vector(3, 0.0); - profileType_ = 0; maxL_ = 0; } else { // This part must be reviewed!! Some data members are not initialized... // Just initialize the solvent object in this class @@ -278,13 +267,9 @@ void Input::reader(const PCMInput & host_input) { // Specification of the solvent by name means isotropic PCM // We have to initialize the Green's functions data here, Solvent class // is an helper class and should not be used in the core classes. - greenInsideType_ = std::string("VACUUM"); - greenInsideType_ += "_DERIVATIVE"; - derivativeInsideType_ = detail::derivativeTraits("DERIVATIVE"); + greenInsideType_ = std::string("VACUUM_DERIVATIVE"); epsilonInside_ = 1.0; - greenOutsideType_ = std::string("UNIFORMDIELECTRIC"); - greenOutsideType_ += "_DERIVATIVE"; - derivativeOutsideType_ = detail::derivativeTraits("DERIVATIVE"); + greenOutsideType_ = std::string("UNIFORMDIELECTRIC_DERIVATIVE"); epsilonStaticOutside_ = solvent_.epsStatic; epsilonDynamicOutside_ = solvent_.epsDynamic; } @@ -373,7 +358,8 @@ void Input::initMolecule() { } CavityData Input::cavityParams() const { - return CavityData(molecule_, + return CavityData(cavityType_, + molecule_, area_, probeRadius_, minDistance_, @@ -386,13 +372,12 @@ CavityData Input::cavityParams() const { } GreenData Input::insideGreenParams() const { - return GreenData(derivativeInsideType_, profileType_, epsilonInside_); + return GreenData(greenInsideType_, epsilonInside_); } GreenData Input::outsideStaticGreenParams() const { - GreenData retval(derivativeOutsideType_, profileType_, epsilonStaticOutside_); + GreenData retval(greenOutsideType_, epsilonStaticOutside_); if (not hasSolvent_) { - retval.howProfile = profileType_; retval.epsilon1 = epsilonStatic1_; retval.epsilon2 = epsilonStatic2_; retval.center = center_; @@ -405,9 +390,8 @@ GreenData Input::outsideStaticGreenParams() const { } GreenData Input::outsideDynamicGreenParams() const { - GreenData retval(derivativeOutsideType_, profileType_, epsilonDynamicOutside_); + GreenData retval(greenOutsideType_, epsilonDynamicOutside_); if (not hasSolvent_) { - retval.howProfile = profileType_; retval.epsilon1 = epsilonDynamic1_; retval.epsilon2 = epsilonDynamic2_; retval.center = center_; @@ -420,32 +404,14 @@ GreenData Input::outsideDynamicGreenParams() const { } SolverData Input::solverParams() const { - return SolverData(correction_, equationType_, hermitivitize_); + return SolverData(solverType_, correction_, equationType_, hermitivitize_); } BIOperatorData Input::integratorParams() const { - return BIOperatorData(integratorScaling_); + return BIOperatorData(integratorType_, integratorScaling_); } namespace detail { -int derivativeTraits(const std::string & name) { - static std::map mapStringToInt; - mapStringToInt.insert(std::map::value_type("NUMERICAL", 0)); - mapStringToInt.insert(std::map::value_type("DERIVATIVE", 1)); - mapStringToInt.insert(std::map::value_type("GRADIENT", 2)); - mapStringToInt.insert(std::map::value_type("HESSIAN", 3)); - - return mapStringToInt.find(name)->second; -} - -int profilePolicy(const std::string & name) { - static std::map mapStringToInt; - mapStringToInt.insert(std::map::value_type("TANH", 0)); - mapStringToInt.insert(std::map::value_type("ERF", 1)); - - return mapStringToInt.find(name)->second; -} - int integralEquation(const std::string & name) { static std::map mapStringToInt; mapStringToInt.insert(std::map::value_type("FIRSTKIND", 0)); diff --git a/src/interface/Input.hpp b/src/interface/Input.hpp index 6332f50c7..a75faf70c 100644 --- a/src/interface/Input.hpp +++ b/src/interface/Input.hpp @@ -89,7 +89,6 @@ class Input { /// @} /// Cavity section input - std::string cavityType() const { return type_; } bool scaling() const { return scaling_; } std::string radiiSet() const { return radiiSet_; } std::string radiiSetName() const { return radiiSetName_; } @@ -112,20 +111,13 @@ class Input { /// Medium section input Solvent solvent() const { return solvent_; } bool fromSolvent() const { return hasSolvent_; } - std::string solverType() const { return solverType_; } int equationType() const { return equationType_; } double correction() const { return correction_; } bool hermitivitize() const { return hermitivitize_; } bool isDynamic() const { return isDynamic_; } - std::string integratorType() const { return integratorType_; } double integratorScaling() const { return integratorScaling_; } /// @} - /// Green's function section input - std::string greenInsideType() const { return greenInsideType_; } - std::string greenOutsideType() const { return greenOutsideType_; } - /// @} - /// Keeps track of who did the parsing: the API or the host program std::string providedBy() const { return providedBy_; } @@ -175,7 +167,7 @@ class Input { /// Year of the CODATA set to be used int CODATAyear_; /// The type of cavity - std::string type_; + std::string cavityType_; /// Filename for the .npz cavity restart file std::string cavFilename_; /// Filename for the wavelet cavity dyadic file @@ -229,14 +221,14 @@ class Input { /// Scaling factor for the diagonal of the approximate collocation boundary /// integral operators double integratorScaling_; - /// The Green's function type inside the cavity + /// The Green's function type inside the cavity. + /// It encodes the Green's function type, derivative calculation strategy and + /// dielectric profile: TYPE_DERIVATIVE_PROFILE std::string greenInsideType_; /// The Green's function type outside the cavity + /// It encodes the Green's function type, derivative calculation strategy and + /// dielectric profile: TYPE_DERIVATIVE_PROFILE std::string greenOutsideType_; - /// How to calculate Green's function derivatives inside the cavity - int derivativeInsideType_; - /// How to calculate Green's function derivatives outside the cavity - int derivativeOutsideType_; /// Permittivity inside the cavity double epsilonInside_; /// Static permittivity outside the cavity @@ -263,8 +255,6 @@ class Input { double center_; /// Width of the diffuse interface double width_; - /// Profile chosen for the diffuse interface - int profileType_; /// Maximum angular momentum int maxL_; /// Center of the dielectric sphere @@ -280,16 +270,6 @@ class Input { }; namespace detail { -/*! A useful map to convert the Der string to an integer which will be passed to the - * Green's function CTOR. */ -int derivativeTraits(const std::string & name); - -/*! A useful map to convert from a string specifying the dielectric profile to an - * integer - * which will be passed to the Green's function CTOR. - */ -int profilePolicy(const std::string & name); - /*! A useful map to convert the EquationType string to an integer which will be * passed to the Solver CTOR. */ int integralEquation(const std::string & name); diff --git a/src/interface/Meddle.cpp b/src/interface/Meddle.cpp index 399befed2..9271fea1e 100644 --- a/src/interface/Meddle.cpp +++ b/src/interface/Meddle.cpp @@ -412,8 +412,8 @@ void Meddle::initInput(pcmsolver_reader_t input_reading, } void Meddle::initCavity() { - cavity_ = - cavity::bootstrapFactory().create(input_.cavityType(), input_.cavityParams()); + cavity_ = cavity::bootstrapFactory().create(input_.cavityParams().cavityType, + input_.cavityParams()); cavity_->saveCavity(); infoStream_ << "========== Cavity " << std::endl; @@ -423,15 +423,16 @@ void Meddle::initCavity() { void Meddle::initStaticSolver() { IGreensFunction * gf_i = green::bootstrapFactory().create( - input_.greenInsideType(), input_.insideGreenParams()); + input_.insideGreenParams().greensFunctionType, input_.insideGreenParams()); IGreensFunction * gf_o = green::bootstrapFactory().create( - input_.greenOutsideType(), input_.outsideStaticGreenParams()); + input_.outsideStaticGreenParams().greensFunctionType, + input_.outsideStaticGreenParams()); - K_0_ = - solver::bootstrapFactory().create(input_.solverType(), input_.solverParams()); + K_0_ = solver::bootstrapFactory().create(input_.solverParams().solverType, + input_.solverParams()); IBoundaryIntegralOperator * biop = bi_operators::bootstrapFactory().create( - input_.integratorType(), input_.integratorParams()); + input_.integratorParams().integratorType, input_.integratorParams()); K_0_->buildSystemMatrix(*cavity_, *gf_i, *gf_o, *biop); delete biop; @@ -444,15 +445,16 @@ void Meddle::initStaticSolver() { void Meddle::initDynamicSolver() { IGreensFunction * gf_i = green::bootstrapFactory().create( - input_.greenInsideType(), input_.insideGreenParams()); + input_.insideGreenParams().greensFunctionType, input_.insideGreenParams()); IGreensFunction * gf_o = green::bootstrapFactory().create( - input_.greenOutsideType(), input_.outsideDynamicGreenParams()); + input_.outsideDynamicGreenParams().greensFunctionType, + input_.outsideDynamicGreenParams()); - K_d_ = - solver::bootstrapFactory().create(input_.solverType(), input_.solverParams()); + K_d_ = solver::bootstrapFactory().create(input_.solverParams().solverType, + input_.solverParams()); IBoundaryIntegralOperator * biop = bi_operators::bootstrapFactory().create( - input_.integratorType(), input_.integratorParams()); + input_.integratorParams().integratorType, input_.integratorParams()); K_d_->buildSystemMatrix(*cavity_, *gf_i, *gf_o, *biop); hasDynamic_ = true; delete biop; diff --git a/src/solver/SolverData.hpp b/src/solver/SolverData.hpp index 75df8b634..d4fad2c13 100644 --- a/src/solver/SolverData.hpp +++ b/src/solver/SolverData.hpp @@ -23,6 +23,8 @@ #pragma once +#include + #include "Config.hpp" /*! @struct SolverData @@ -31,6 +33,8 @@ namespace pcm { struct SolverData { + /*! The type of solver */ + std::string solverType; /*! The correction factor to be use in a CPCM calculation */ double correction; /*! The type of integral equation to solve, relevant only for wavelet solvers */ @@ -41,8 +45,11 @@ struct SolverData { bool empty; SolverData() { empty = true; } - SolverData(double corr, int int_eq = 1, bool symm = true) - : correction(corr), integralEquation(int_eq), hermitivitize(symm) { + SolverData(const std::string & type, double corr, int int_eq = 1, bool symm = true) + : solverType(type), + correction(corr), + integralEquation(int_eq), + hermitivitize(symm) { empty = false; } }; diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index 00ae2c667..aeb7ddbbd 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,6 +1,11 @@ # List of headers -list(APPEND headers_list Atom.hpp ChargeDistribution.hpp Factory.hpp ForId.hpp - Logger.hpp LoggerImpl.hpp MathUtils.hpp Molecule.hpp +list(APPEND headers_list Atom.hpp +ChargeDistribution.hpp +Factory.hpp +Logger.hpp +LoggerImpl.hpp +MathUtils.hpp +Molecule.hpp QuadratureRules.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp Stencils.hpp Symmetry.hpp Timer.hpp cnpy.hpp) set_source_files_properties(cnpy.hpp PROPERTIES COMPILE_FLAGS -w) diff --git a/src/utils/ForId.hpp b/src/utils/ForId.hpp deleted file mode 100644 index 7205a9cec..000000000 --- a/src/utils/ForId.hpp +++ /dev/null @@ -1,533 +0,0 @@ -/* - * PCMSolver, an API for the Polarizable Continuum Model - * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. - * - * This file is part of PCMSolver. - * - * PCMSolver is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PCMSolver is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with PCMSolver. If not, see . - * - * For information on the complete list of contributors to the - * PCMSolver API, see: - */ - -#pragma once - -#include -#include - -#include "Config.hpp" - -#include -#include -#include -#include -#include -#include - -/*! \file ForId.hpp - * Metafunction for fake run-time selection of template arguments. - * D. Langr, P.Tvrdik, T. Dytrych and J. P. Draayer - * "Fake Run-Time Selection of Template Arguments in C++" - * in "Objects, Models, Components, Patterns" - * DOI: 10.1007/978-3-642-30561-0_11 - * http://arxiv.org/abs/1306.5142 - * - * The idea is to iterate over sequences of types, S, beginning - * at type B and ending at type E. This heavily relies on the Boost - * MetaProgramming Library (Boost.MPL) - * We provide here an implementation covering the case were up to - * three template parameters have to be selected. - * According to the original reference, if D is the maximum number - * of template parameters to be selected at run-time, then the metaprogramming - * technique here described requires coding of (2D + 1) structs: - * - one primary template. The primary template has (4D + 1) - * template parameters, 4D of which type template. - * The primary template exhausts the first type sequence; - * - a first partial specialization, exhausting the second - * type sequence. This partial specialization has 4D template parameters, - * (4D - 1) of which type template; - * - a second partial specialization, exhausting the third type - * sequence. This partial specialization has (4D - 1) template parameters, - * (4D - 2) of which type templates; - * - a third partial specialization, never reached at run-time. - * This is needed to stop recursive instantiation at compile-time. - * It has (4D - 2) template parameters, (4D - 3) of which type template. - * - D ApplyFunctor helper structs, needed to wrap the functor. - * Once the template parameter has been resolved, a functor is - * applied. The return value of the functor is the time-dependent solver - * we want to create with the template parameters resolved. - * - * MPL metafunctions used: - * - boost::mpl::distance - * - boost::mpl::begin - * - boost::mpl::end - * - boost::mpl::find - * - boost::mpl::deref - * - boost::mpl::next - */ - -namespace mpl = boost::mpl; - -/*! \brief Returns a zero-based index of a type within a type sequence - * \tparam S type sequence - * \tparam T the type whose index will be returned - */ -template -struct position : mpl::distance::type, - typename mpl::find::type>::type {}; - -/*! Convenience wrapper to the functor - * \tparam D dimension of the problem, i.e. the maximum number of type sequences - * allowed - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - */ -template struct ApplyFunctor; - -/*! \brief Iterates over type sequences either until the position of the actual type - *matches the - * desired id or until the end of the sequences is reached. - * \tparam D dimension of the problem, i.e. the maximum number of type sequences - *allowed - * \tparam S1 type sequence number 1 - * \tparam S2 type sequence number 2, by default empty - * \tparam S3 type sequence number 3, by default empty - * \tparam B1 type of the first element in S1 - * \tparam B2 type of the first element in S2 - * \tparam B3 type of the first element in S3 - * \tparam E1 type of the last element in S1 - * \tparam E2 type of the last element in S2 - * \tparam E3 type of the last element in S3 - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - * - * This is the primary template. As such, it has (4D + 1) template parameters, 4D - * of which type template parameters. - * - * \note The mechanics of the code is also documented, since this is quite an - *intricate piece of code! - */ -template , - typename S3 = mpl::vector<>, - typename B1 = typename mpl::begin::type, - typename B2 = typename mpl::begin::type, - typename B3 = typename mpl::begin::type, - typename E1 = typename mpl::end::type, - typename E2 = typename mpl::end::type, - typename E3 = typename mpl::end::type, - typename T1 = typename mpl::deref::type, - typename T2 = typename mpl::deref::type, - typename T3 = typename mpl::deref::type> -struct for_id_impl { - /*! Executes given functor with selected template arguments - * \param[in] f the creational functor to be applied - * \param[in] data the data needed to create the correct time-dependent solver - * \param[in] id1 the type of derivative - * \param[in] id2 index for the second type - * \param[in] id3 index for the third type - * \tparam ReturnType type of the object returned - * \tparam T the type of the functor - * \tparam InputType type of the input data - */ - template - static ReturnType * execute(T & f, - const InputType & data, - int id1, - int id2 = 0, - int id3 = 0) { - if (position::type>::value == - id1) { // Desired type in S1 found - if (1 == D) { // One-dimensional, we're done! - return ApplyFunctor::type, T2, T3>:: - template apply(f, data); - } else { // Resolve second and third dimensions - // Call first partial specialization of for_id_impl - // B1 is not "passed", since the type desired from S1 has been resolved - // The resolved type is "saved" into T1 and "passed" to the first partial - // specialization - return ( - for_id_impl::type, - T2>::template execute(f, data, id1, id2, id3)); - } - } else if (1 == mpl::distance::value) { // Desired type NOT found in S1 - throw std::invalid_argument("Invalid derivative type (id1 = " + - pcm::to_string(id1) + ") in for_id metafunction."); - } else { // First type not resolved, but S1 type sequence not exhausted - // Call for_id_impl primary template with type of B1 moved to the next type in - // S1 - return (for_id_impl::type, - B2, - B3, - E1, - E2, - E3, - T1, - T2, - T3>::template execute(f, data, id1, id2, id3)); - } - } -}; - -/*! \brief Iterates over type sequences either until the position of the actual type - *matches the - * desired id or until the end of the sequences is reached. - * \tparam D dimension of the problem, i.e. the maximum number of type sequences - *allowed - * \tparam S1 type sequence number 1 - * \tparam S2 type sequence number 2 - * \tparam S3 type sequence number 3 - * \tparam B2 type of the first element in S2 - * \tparam B3 type of the first element in S3 - * \tparam E1 type of the last element in S1 - * \tparam E2 type of the last element in S2 - * \tparam E3 type of the last element in S3 - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - * - * This is the fist partial specialization. As such, it has 4D template parameters, - *(4D - 1) - * of which type template parameters. - * - * \note The mechanics of the code is also documented, since this is quite an - *intricate piece of code! - */ -template -struct for_id_impl { - /*! Executes given functor with selected template arguments - * \param[in] f the creational functor to be applied - * \param[in] data the data needed to create the correct time-dependent solver - * \param[in] id1 the type of derivative - * \param[in] id2 index for the second type - * \param[in] id3 index for the third type - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * execute(T & f, - const InputType & data, - int id1, - int id2 = 0, - int id3 = 0) { - if (position::type>::value == - id2) { // Desired type in S2 found - if (2 == D) { // Two-dimensional, we're done! - return ApplyFunctor::type, T3>:: - template apply(f, data); - } else { // Resolve third dimension - // Call second partial specialization of for_id_impl - // B2 is not "passed", since the type desired from S2 has been resolved - // The resolved type is "saved" into T2 and "passed" to the first partial - // specialization - return (for_id_impl::type>:: - template execute(f, data, id1, id2, id3)); - } - } else if (1 == mpl::distance::value) { // Desired type NOT found in S2 - throw std::invalid_argument("Invalid integrator policy (id2 = " + - pcm::to_string(id2) + ") in for_id metafunction."); - } else { // Second type not resolved, but S2 type sequence not exhausted - // Call for_id_impl first partial specialization with type of B2 moved to the - // next type in S2 - return (for_id_impl::type, - B3, - E1, - E2, - E3, - T1, - T2, - T3>::template execute(f, data, id1, id2, id3)); - } - } -}; - -/*! \brief Iterates over type sequences either until the position of the actual type - *matches the - * desired id or until the end of the sequences is reached. - * \tparam D dimension of the problem, i.e. the maximum number of type sequences - *allowed - * \tparam S1 type sequence number 1 - * \tparam S2 type sequence number 2 - * \tparam S3 type sequence number 3 - * \tparam B3 type of the first element in S3 - * \tparam E1 type of the last element in S1 - * \tparam E2 type of the last element in S2 - * \tparam E3 type of the last element in S3 - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - * - * This is the second partial specialization. As such, it has (4D - 1) template - *parameters, (4D - 2) - * of which type template parameters. - * - * \note The mechanics of the code is also documented, since this is quite an - *intricate piece of code! - */ -template -struct for_id_impl { - /*! Executes given functor with selected template arguments - * \param[in] f the creational functor to be applied - * \param[in] data the data needed to create the correct time-dependent solver - * \param[in] id1 the type of derivative - * \param[in] id2 index for the second type - * \param[in] id3 index for the third type - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * execute(T & f, - const InputType & data, - int id1, - int id2 = 0, - int id3 = 0) { - if (position::type>::value == - id3) { // Desired type in S3 found, we're done! - return ApplyFunctor::type>::template apply< - ReturnType>(f, data); - } else if (1 == mpl::distance::value) { // Desired type NOT found in S3 - throw std::invalid_argument("Invalid permittivity profile (id3 = " + - pcm::to_string(id3) + ") in for_id metafunction."); - } else { // Third type not resolved, but S3 type sequence not exhausted - // Call for_id_impl second partial specialization with type of B3 moved to the - // next type in S3 - return (for_id_impl::type, - E1, - E2, - E3, - T1, - T2, - T3>::template execute(f, data, id1, id2, id3)); - } - } -}; - -/*! \brief Iterates over type sequences either until the position of the actual type - *matches the - * desired id or until the end of the sequences is reached. - * \tparam D dimension of the problem, i.e. the maximum number of type sequences - *allowed - * \tparam S1 type sequence number 1 - * \tparam S2 type sequence number 2 - * \tparam S3 type sequence number 3 - * \tparam E1 type of the last element in S1 - * \tparam E2 type of the last element in S2 - * \tparam E3 type of the last element in S3 - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - * - * This is the third partial specialization. As such, it has (4D - 2) template - *parameters, (4D - 3) - * of which type template parameters. - * It is never reached at run-time, it is needed to stop the recursive instantiation - *at compile-time. - */ -template -struct for_id_impl { - /*! Executes given functor with selected template arguments - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * execute(T & /* f */, - const InputType & /* data */, - int /* id1 */, - int /* id2 */ = 0, - int /* id3 */ = 0) { - return __nullptr; - } -}; - -/*! @{ Wrappers to the functor */ -/*! Wrapper to the three-dimensional case - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - */ -template struct ApplyFunctor<3, T1, T2, T3> { - /*! Executes given functor with selected template arguments - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * apply(T & f, const InputType & data) { - return (f.template operator()(data)); - } -}; - -/*! Wrapper to the two-dimensional case - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - */ -template struct ApplyFunctor<2, T1, T2, T3> { - /*! Executes given functor with selected template arguments - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * apply(T & f, const InputType & data) { - return (f.template operator()(data)); - } -}; - -/*! Wrapper to the one-dimensional case - * \tparam T1 type selected from S1 - * \tparam T2 type selected from S2 - * \tparam T3 type selected from S3 - */ -template struct ApplyFunctor<1, T1, T2, T3> { - /*! Executes given functor with selected template arguments - * \tparam ReturnType type of the object returned - * \tparam T the type of the time-dependent solver - * \tparam InputType type of the input data - */ - template - static ReturnType * apply(T & f, const InputType & data) { - return (f.template operator()(data)); - } -}; -/*! @}*/ - -/*! @{ Wrappers to the primary template for the metafunction */ -/*! Wrapper for the three-dimensional case. - * \tparam S1 type sequence 1 - * \tparam S2 type sequence 2 - * \tparam S3 type sequence 3 - * \tparam ReturnType type of the object returned - * \tparam T type of the functor - * \tparam InputType type of the input data - * \param[in,out] f functor - * \param[in] data input arguments for functor - * \param[in] id1 index of the first template argument, selected in S1 - * \param[in] id2 index of the second template argument, selected in S2 - * \param[in] id3 index of the third template argument, selected in S3 - */ -template -ReturnType * for_id(T & f, const InputType & data, int id1, int id2, int id3) { - return for_id_impl<3, S1, S2, S3>::template execute( - f, data, id1, id2, id3); -} - -/*! Wrapper for the two-dimensional case. - * \tparam S1 type sequence 1 - * \tparam S2 type sequence 2 - * \tparam ReturnType type of the object returned - * \tparam T type of the functor - * \tparam InputType type of the input data - * \param[in,out] f functor - * \param[in] data input arguments for functor - * \param[in] id1 index of the first template argument, selected in S1 - * \param[in] id2 index of the second template argument, selected in S2 - */ -template -ReturnType * for_id(T & f, const InputType & data, int id1, int id2) { - return for_id_impl<2, S1, S2>::template execute(f, data, id1, id2); -} - -/*! Wrapper for the one-dimensional case. - * \tparam S1 type sequence 1 - * \tparam ReturnType type of the object returned - * \tparam T type of the functor - * \tparam InputType type of the input data - * \param[in,out] f functor - * \param[in] data input arguments for functor - * \param[in] id1 index of the first template argument, selected in S1 - */ -template -ReturnType * for_id(T & f, const InputType & data, int id1) { - return for_id_impl<1, S1>::template execute(f, data, id1); -} -/*! @}*/ diff --git a/tests/input/input_diffuse.cpp b/tests/input/input_diffuse.cpp index 817b169fd..a4d72a0e4 100644 --- a/tests/input/input_diffuse.cpp +++ b/tests/input/input_diffuse.cpp @@ -72,10 +72,8 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment std::string solverType = "WAVELET"; int equationType = 0; double probeRadius = 1.385 * angstromToBohr(); // The value for water - std::string greenInsideType = "VACUUM"; - std::string greenOutsideType = "SPHERICALDIFFUSE"; - int derivativeInsideType = 0; - int derivativeOutsideType = 0; + std::string greenInsideType = "VACUUM_NUMERICAL"; + std::string greenOutsideType = "SPHERICALDIFFUSE_NUMERICAL_ERF"; double epsilonInside = 1.0; double epsilonStatic1 = 78.39; double epsilonDynamic1 = 10.423; @@ -83,13 +81,12 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment double epsilonDynamic2 = 4.0; double center = 100.0 * angstromToBohr(); double width = 5.0 * angstromToBohr(); - int profile = 1; Eigen::Vector3d origin = (Eigen::Vector3d() << 70.0, 1.0, 23.0).finished(); origin *= angstromToBohr(); REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityType()); + REQUIRE(type == parsedInput.cavityParams().cavityType); REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); REQUIRE(scaling == parsedInput.scaling()); @@ -102,14 +99,12 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment } REQUIRE(spheres[i].radius == Approx(parsedInput.spheres(i).radius)); } - REQUIRE(solverType == parsedInput.solverType()); + REQUIRE(solverType == parsedInput.solverParams().solverType); REQUIRE(equationType == parsedInput.equationType()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); - REQUIRE(greenInsideType == parsedInput.greenInsideType()); - REQUIRE(greenOutsideType == parsedInput.greenOutsideType()); - REQUIRE(derivativeInsideType == parsedInput.insideGreenParams().howDerivative); - REQUIRE(derivativeOutsideType == - parsedInput.outsideStaticGreenParams().howDerivative); + REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); + REQUIRE(greenOutsideType == + parsedInput.outsideStaticGreenParams().greensFunctionType); REQUIRE(epsilonInside == Approx(parsedInput.insideGreenParams().epsilon)); REQUIRE(epsilonStatic1 == Approx(parsedInput.outsideStaticGreenParams().epsilon1)); REQUIRE(epsilonStatic2 == Approx(parsedInput.outsideStaticGreenParams().epsilon2)); @@ -119,7 +114,6 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment Approx(parsedInput.outsideDynamicGreenParams().epsilon2)); REQUIRE(center == Approx(parsedInput.outsideDynamicGreenParams().center)); REQUIRE(width == Approx(parsedInput.outsideDynamicGreenParams().width)); - REQUIRE(profile == parsedInput.outsideDynamicGreenParams().howProfile); for (int i = 0; i < 3; ++i) { REQUIRE(origin(i) == Approx(parsedInput.outsideStaticGreenParams().origin(i))); REQUIRE(origin(i) == Approx(parsedInput.outsideDynamicGreenParams().origin(i))); diff --git a/tests/input/input_multipoles.cpp b/tests/input/input_multipoles.cpp index ceac51e4e..1ed208fd6 100644 --- a/tests/input/input_multipoles.cpp +++ b/tests/input/input_multipoles.cpp @@ -54,27 +54,23 @@ TEST_CASE("Input reading using GetKw for an input file for a classical point " Input parsedInput("@multipoles.inp"); std::string units = "ANGSTROM"; int CODATAyear = 2002; - std::string type = "GEPOL"; + std::string cavityType = "GEPOL"; std::string radiiSet = "BONDI"; std::string mode = "IMPLICIT"; std::string solverType = "IEFPCM"; - std::string greenInsideType = "VACUUM"; - std::string greenOutsideType = "UNIFORMDIELECTRIC"; - int derivativeInsideType = 1; - int derivativeOutsideType = 1; + std::string greenInsideType = "VACUUM_DERIVATIVE"; + std::string greenOutsideType = "UNIFORMDIELECTRIC_DERIVATIVE"; double area = 10.0 * angstrom2ToBohr2(); std::string solvent = "Acetonitrile"; // Name in the Solvent object REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityType()); + REQUIRE(cavityType == parsedInput.cavityParams().cavityType); REQUIRE(radiiSet == parsedInput.radiiSet()); REQUIRE(mode == parsedInput.mode()); - REQUIRE(solverType == parsedInput.solverType()); - REQUIRE(greenInsideType == parsedInput.greenInsideType()); - REQUIRE(greenOutsideType == parsedInput.greenOutsideType()); - REQUIRE(derivativeInsideType == parsedInput.insideGreenParams().howDerivative); - REQUIRE(derivativeOutsideType == - parsedInput.outsideStaticGreenParams().howDerivative); + REQUIRE(solverType == parsedInput.solverParams().solverType); + REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); + REQUIRE(greenOutsideType == + parsedInput.outsideStaticGreenParams().greensFunctionType); REQUIRE(area == Approx(parsedInput.cavityParams().area)); REQUIRE(solvent == parsedInput.solvent().name); for (size_t j = 0; j < 3; ++j) { diff --git a/tests/input/input_restart.cpp b/tests/input/input_restart.cpp index 13c598575..c08965219 100644 --- a/tests/input/input_restart.cpp +++ b/tests/input/input_restart.cpp @@ -49,7 +49,7 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", Input parsedInput = Input(filename); std::string units = "AU"; int CODATAyear = 2010; - std::string type = "RESTART"; + std::string cavityType = "RESTART"; std::string cavFilename = "cavity.npz"; int patchLevel = 2; double coarsity = 0.5; @@ -67,14 +67,12 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", double correction = 0.0; bool hermitivitize = true; double probeRadius = 1.385 * angstromToBohr(); // The value for water - std::string greenInsideType = "VACUUM"; - std::string greenOutsideType = "UNIFORMDIELECTRIC"; - int derivativeInsideType = 1; - int derivativeOutsideType = 1; + std::string greenInsideType = "VACUUM_DERIVATIVE"; + std::string greenOutsideType = "UNIFORMDIELECTRIC_DERIVATIVE"; REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityType()); + REQUIRE(cavityType == parsedInput.cavityParams().cavityType); REQUIRE(cavFilename == parsedInput.cavityParams().filename); REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); @@ -87,14 +85,12 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", REQUIRE(minimalRadius == Approx(parsedInput.cavityParams().minimalRadius)); REQUIRE(mode == parsedInput.mode()); REQUIRE(solvent == parsedInput.solvent().name); - REQUIRE(solverType == parsedInput.solverType()); + REQUIRE(solverType == parsedInput.solverParams().solverType); REQUIRE(equationType == parsedInput.equationType()); REQUIRE(correction == Approx(parsedInput.correction())); REQUIRE(hermitivitize == parsedInput.hermitivitize()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); - REQUIRE(greenInsideType == parsedInput.greenInsideType()); - REQUIRE(greenOutsideType == parsedInput.greenOutsideType()); - REQUIRE(derivativeInsideType == parsedInput.insideGreenParams().howDerivative); - REQUIRE(derivativeOutsideType == - parsedInput.outsideStaticGreenParams().howDerivative); + REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); + REQUIRE(greenOutsideType == + parsedInput.outsideStaticGreenParams().greensFunctionType); } diff --git a/tests/input/input_tsless.cpp b/tests/input/input_tsless.cpp index b63967bf5..fa453a1c5 100644 --- a/tests/input/input_tsless.cpp +++ b/tests/input/input_tsless.cpp @@ -48,7 +48,7 @@ TEST_CASE("Input reading using GetKw for an input file for a TsLess cavity", Input parsedInput = Input(filename); std::string units = "ANGSTROM"; int CODATAyear = 2002; - std::string type = "TSLESS"; + std::string cavityType = "TSLESS"; double area = 0.6 * angstrom2ToBohr2(); double minDistance = 5.0 * angstromToBohr(); int derOrder = 25; @@ -70,14 +70,12 @@ TEST_CASE("Input reading using GetKw for an input file for a TsLess cavity", double correction = 0.5; bool hermitivitize = false; double probeRadius = 2.815 * angstromToBohr(); // The value for water - std::string greenInsideType = "VACUUM"; - std::string greenOutsideType = "UNIFORMDIELECTRIC"; - int derivativeInsideType = 1; - int derivativeOutsideType = 1; + std::string greenInsideType = "VACUUM_DERIVATIVE"; + std::string greenOutsideType = "UNIFORMDIELECTRIC_DERIVATIVE"; REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityType()); + REQUIRE(cavityType == parsedInput.cavityParams().cavityType); REQUIRE(area == Approx(parsedInput.cavityParams().area)); REQUIRE(minDistance == Approx(parsedInput.cavityParams().minDistance)); REQUIRE(derOrder == parsedInput.cavityParams().derOrder); @@ -91,13 +89,11 @@ TEST_CASE("Input reading using GetKw for an input file for a TsLess cavity", REQUIRE(radii[i] == Approx(parsedInput.radii(i))); } REQUIRE(solvent == parsedInput.solvent().name); - REQUIRE(solverType == parsedInput.solverType()); + REQUIRE(solverType == parsedInput.solverParams().solverType); REQUIRE(correction == Approx(parsedInput.correction())); REQUIRE(hermitivitize == parsedInput.hermitivitize()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); - REQUIRE(greenInsideType == parsedInput.greenInsideType()); - REQUIRE(greenOutsideType == parsedInput.greenOutsideType()); - REQUIRE(derivativeInsideType == parsedInput.insideGreenParams().howDerivative); - REQUIRE(derivativeOutsideType == - parsedInput.outsideStaticGreenParams().howDerivative); + REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); + REQUIRE(greenOutsideType == + parsedInput.outsideStaticGreenParams().greensFunctionType); } diff --git a/tests/input/input_wavelet.cpp b/tests/input/input_wavelet.cpp index 9df3e593e..f9dc742a0 100644 --- a/tests/input/input_wavelet.cpp +++ b/tests/input/input_wavelet.cpp @@ -49,7 +49,7 @@ TEST_CASE("Input reading using GetKw for an input file for a wavelet cavity", Input parsedInput = Input(filename); std::string units = "ANGSTROM"; int CODATAyear = 1998; - std::string type = "WAVELET"; + std::string cavityType = "WAVELET"; int patchLevel = 1; double coarsity = 0.3; bool scaling = true; @@ -72,17 +72,15 @@ TEST_CASE("Input reading using GetKw for an input file for a wavelet cavity", std::string solverType = "WAVELET"; int equationType = 0; double probeRadius = 1.385 * angstromToBohr(); // The value for water - std::string greenInsideType = "VACUUM"; - std::string greenOutsideType = "UNIFORMDIELECTRIC"; - int derivativeInsideType = 0; - int derivativeOutsideType = 2; + std::string greenInsideType = "VACUUM_NUMERICAL"; + std::string greenOutsideType = "UNIFORMDIELECTRIC_GRADIENT"; double epsilonInside = 1.0; double epsilonStaticOutside = 78.39; double epsilonDynamicOutside = 10.423; REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityType()); + REQUIRE(cavityType == parsedInput.cavityParams().cavityType); REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); REQUIRE(scaling == parsedInput.scaling()); @@ -95,14 +93,12 @@ TEST_CASE("Input reading using GetKw for an input file for a wavelet cavity", } REQUIRE(spheres[i].radius == Approx(parsedInput.spheres(i).radius)); } - REQUIRE(solverType == parsedInput.solverType()); + REQUIRE(solverType == parsedInput.solverParams().solverType); REQUIRE(equationType == parsedInput.equationType()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); - REQUIRE(greenInsideType == parsedInput.greenInsideType()); - REQUIRE(greenOutsideType == parsedInput.greenOutsideType()); - REQUIRE(derivativeInsideType == parsedInput.insideGreenParams().howDerivative); - REQUIRE(derivativeOutsideType == - parsedInput.outsideStaticGreenParams().howDerivative); + REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); + REQUIRE(greenOutsideType == + parsedInput.outsideStaticGreenParams().greensFunctionType); REQUIRE(epsilonInside == Approx(parsedInput.insideGreenParams().epsilon)); REQUIRE(epsilonStaticOutside == Approx(parsedInput.outsideStaticGreenParams().epsilon)); From 63af6f5e62c0d1410a61d50a3cd6ec180f5bb24a Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Wed, 9 Aug 2017 16:19:18 +0200 Subject: [PATCH 03/28] Trim and uppercase strings w/o Boost --- src/interface/Input.cpp | 73 +++++++++++++++++++++++++++++++++++------ src/interface/Input.hpp | 10 ++++++ 2 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/interface/Input.cpp b/src/interface/Input.cpp index f1767e9f1..70d898419 100644 --- a/src/interface/Input.cpp +++ b/src/interface/Input.cpp @@ -23,6 +23,8 @@ #include "Input.hpp" +#include +#include #include #include #include @@ -30,10 +32,8 @@ #include "Config.hpp" -#include "utils/getkw/Getkw.h" #include - -#include +#include "utils/getkw/Getkw.h" #include "PCMInput.h" #include "bi_operators/BIOperatorData.hpp" @@ -83,9 +83,9 @@ void Input::reader(const std::string & filename) { dyadicFilename_ = cavity.getStr("DYADICFILE"); scaling_ = cavity.getBool("SCALING"); - radiiSet_ = boost::algorithm::to_upper_copy(cavity.getStr("RADIISET")); + radiiSet_ = detail::uppercase(cavity.getStr("RADIISET")); minimalRadius_ = cavity.getDbl("MINRADIUS"); - mode_ = boost::algorithm::to_upper_copy(cavity.getStr("MODE")); + mode_ = detail::uppercase(cavity.getStr("MODE")); if (mode_ == "EXPLICIT") { std::vector spheresInput = cavity.getDblVec("SPHERES"); int j = 0; @@ -94,8 +94,7 @@ void Input::reader(const std::string & filename) { Eigen::Vector3d center; center = (Eigen::Vector3d() << spheresInput[j], spheresInput[j + 1], - spheresInput[j + 2]) - .finished(); + spheresInput[j + 2]).finished(); Sphere sph(center, spheresInput[j + 3]); spheres_.push_back(sph); j += 4; @@ -421,14 +420,68 @@ int integralEquation(const std::string & name) { return mapStringToInt.find(name)->second; } +#ifndef HAS_CXX11_LAMBDA +std::string left_trim(std::string s) { + s.erase(s.begin(), std::find_if(s.begin(), s.end(), + std::not1(std::ptr_fun(std::isspace)))); + return s; +} + +std::string right_trim(std::string s) { + s.erase(std::find_if(s.rbegin(), s.rend(), + std::not1(std::ptr_fun(std::isspace))).base(), s.end()); + return s; +} +#else /* HAS_CXX11_LAMBDA */ +std::string left_trim(std::string s) { + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { + return !std::isspace(ch); + })); + return s; +} + +std::string right_trim(std::string s) { + s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { + return !std::isspace(ch); + }).base(), s.end()); + return s; +} +#endif /* HAS_CXX11_LAMBDA */ + +std::string left_trim(const char * src) { + std::string tmp(src); + return left_trim(tmp); +} + +std::string right_trim(const char * src) { + std::string tmp(src); + return right_trim(tmp); +} + +std::string trim(std::string s) { + left_trim(s); + right_trim(s); + return s; +} + std::string trim(const char * src) { std::string tmp(src); - boost::algorithm::trim(tmp); - return tmp; + return trim(tmp); +} + +std::string uppercase(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun(std::toupper)); + return s; +} + +std::string uppercase(const char * src) { + std::string tmp(src); + return uppercase(tmp); } std::string trim_and_upper(const char * src) { - return boost::algorithm::to_upper_copy(trim(src)); + std::string tmp(src); + return uppercase(trim(tmp)); } } // namespace detail } // namespace pcm diff --git a/src/interface/Input.hpp b/src/interface/Input.hpp index a75faf70c..75c891da7 100644 --- a/src/interface/Input.hpp +++ b/src/interface/Input.hpp @@ -274,8 +274,18 @@ namespace detail { * passed to the Solver CTOR. */ int integralEquation(const std::string & name); +std::string left_trim(std::string s); +std::string left_trim(const char * src); + +std::string right_trim(std::string s); +std::string right_trim(const char * src); + +std::string trim(std::string s); std::string trim(const char * src); +std::string uppercase(std::string s); +std::string uppercase(const char * src); + std::string trim_and_upper(const char * src); } // namespace detail } // namespace pcm From 72bb63c21f6ea89884522707852e5d752cda6d1a Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 18:09:33 +0100 Subject: [PATCH 04/28] Further clean-up, MPL fully out --- CHANGELOG.md | 37 ++++- doc/programmers/cmake-usage.rst | 2 +- doc/programmers/general-structure.rst | 13 +- src/bi_operators/Numerical.cpp | 22 +-- src/utils/CMakeLists.txt | 12 +- src/utils/QuadratureRules.cpp | 162 +++++++++++++++++++++ src/utils/QuadratureRules.hpp | 200 ++++---------------------- 7 files changed, 239 insertions(+), 209 deletions(-) create mode 100644 src/utils/QuadratureRules.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d7e5697b..8fc4298dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,13 +11,26 @@ ### Changed +- Dispatching of Green’s functions in the factory is purely label-based. The + input reader generates a string that holds the type of the Green’s function, + the strategy for calculating its normal derivatives and the dielectric + profile (if needed): `TYPE_DERIVATIVE_PROFILE`. The Green’s functions are + subscribed to the factory using this label, which is then also the one used + for their creation. Iteration over _lists of types_ to dispatch the correct + template parameters is thus completely avoided. This removes the dependency + on the metafunctions in `ForId.hpp` and the dependency on Boost.MPL, the + Boost metaprogramming library. +- Dispatching of quadrature rules for the numerical boundary integral operator + has been rewritten, removing the dependency on Boost.MPL. +- The input wrapping data `struct`-s have been modified to include the string + defining the type of object and to remove now unused information. - Documentation building is fully handled _via_ `sphinx-build`: CMake will no longer generate a `doc` build target. - Simplified `.travis.yml` and got rid of Conda to handle multiple Python versions. ### Fixed -- Documentation building on ReadTheDocs is fully functional again, thanks @arnfinn :tada: - The build had been failing for a while since docs were generated for all files, including +- Documentation building on ReadTheDocs is fully functional again, thanks @arnfinn :tada: + The build had been failing for a while since docs were generated for all files, including documentation files from previous build. Besides, source code doxygen blocks were not exctracted when inside namespaces. @@ -26,6 +39,24 @@ - `FortranCUtils` header and source files were removed. The `pcmsolver_f2c_string` and `pcmsolver_c2f_string` functions are thus gone. For the former, use the replacement `pcmsolver_fstring_to_carray` function provided in the Fortran bindings to the library. +- Some unused files have been removed: + * `Interpolation.hpp` + * `Interpolation.cpp` + * `Vector2.hpp` + * `Vector3.hpp` + * `ForId.hpp` + * `DerivativeUtils.hpp` +- The `cavityType()`, `solverType()`, `greenInsideType()`, `greenOutsideType()` + and `integratorType()` functions in the `Input` object have been removed. + This information is now wrapped into the corresponding input-wrapping + `struct`-s: `CavityData`, `SolverData`, `GreenData` and `BIOperatorData`. + +### Deprecated + +- We are in the process of removing the dependency on the Boost libraries. The + only dependency on Boost allowed in the 1.Y.Z release series will be for + replacing C++11 functionality that is missing from the C++98 standard. For + such code, we will require a pure C++11 counterpart. ## [Version 1.1.11] - 2017-10-25 @@ -378,7 +409,7 @@ ## v1.0.0 - 2014-09-30 [YANKED] -[Unreleased]: https://github.com/PCMSolver/pcmsolver/compare/v1.1.11..HEAD +[Unreleased]: https://github.com/PCMSolver/pcmsolver/compare/v1.1.11...HEAD [Version 1.1.11]: https://github.com/PCMSolver/pcmsolver/compare/v1.1.10...v1.1.11 [Version 1.1.10]: https://github.com/PCMSolver/pcmsolver/compare/v1.1.9...v1.1.10 [Version 1.1.9]: https://github.com/PCMSolver/pcmsolver/compare/v1.1.8...v1.1.9 diff --git a/doc/programmers/cmake-usage.rst b/doc/programmers/cmake-usage.rst index 10d7be10a..b6ce451ef 100644 --- a/doc/programmers/cmake-usage.rst +++ b/doc/programmers/cmake-usage.rst @@ -6,7 +6,7 @@ This is a brief guide to our CMake infrastructure which is managed .. warning:: - The minimum required CMake version is 2.8.8 + The minimum required CMake version is 2.8.10 Adding new source subdirectories and/or files --------------------------------------------- diff --git a/doc/programmers/general-structure.rst b/doc/programmers/general-structure.rst index c303e965b..77ac65075 100644 --- a/doc/programmers/general-structure.rst +++ b/doc/programmers/general-structure.rst @@ -8,15 +8,18 @@ General Structure External libraries: + parts of the C++ `Boost `_ libraries are used to provide - various functionality, like timing and metaprogramming. + various functionality, like ordinary differential equations integrators. The source for the 1.54.0 release is shipped with the module's source code. Some of the libraries used need to be compiled. Boost is released under the terms of the `Boost Software License, v1.0 `_ (see also - http://www.boost.org/users/license.html) We encourage the use of - Boost whenever some functionality has already been coded within those - libraries. However, consider **carefully** the introduction of functionality - depending on compiler Boost libraries. + http://www.boost.org/users/license.html) + + .. warning:: + + As of v1.1.11 we have started removing the dependency from Boost. + The use of Boost is thus deprecated. + + the `Eigen `_ template library for linear algebra. Almost every operation involving matrices and vectors is performed through Eigen. Eigen provides convenient type diff --git a/src/bi_operators/Numerical.cpp b/src/bi_operators/Numerical.cpp index 255e744cc..fcdebc2ea 100644 --- a/src/bi_operators/Numerical.cpp +++ b/src/bi_operators/Numerical.cpp @@ -30,10 +30,6 @@ #include -#include -#include -#include - #include "BIOperatorData.hpp" #include "cavity/Element.hpp" #include "green/IGreensFunction.hpp" @@ -81,16 +77,14 @@ IBoundaryIntegralOperator * createNumerical(const BIOperatorData & /* data */) { return new Numerical(); } +using utils::GaussLegendreRule; + template double integrateS(const KernelS & F, const Element & e) { double result = 0.0; - // Get the quadrature rules for azimuthal and polar integrations - namespace mpl = boost::mpl; - typedef typename mpl::at >::type PhiPolicy; - typedef typename mpl::at >::type ThetaPolicy; - QuadratureRule phiRule; - QuadratureRule thetaRule; + GaussLegendreRule phiRule; + GaussLegendreRule thetaRule; int upper_phi = PhiPoints / 2; // Upper limit for loop on phi points int upper_theta = ThetaPoints / 2; // Upper limit for loop on theta points @@ -197,12 +191,8 @@ template double integrateD(const KernelD & F, const Element & e) { double result = 0.0; - // Get the quadrature rules for azimuthal and polar integrations - namespace mpl = boost::mpl; - typedef typename mpl::at >::type PhiPolicy; - typedef typename mpl::at >::type ThetaPolicy; - QuadratureRule phiRule; - QuadratureRule thetaRule; + GaussLegendreRule phiRule; + GaussLegendreRule thetaRule; int upper_phi = PhiPoints / 2; // Upper limit for loop on phi points int upper_theta = ThetaPoints / 2; // Upper limit for loop on theta points diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index aeb7ddbbd..d4c78bf9a 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,17 +1,13 @@ # List of headers -list(APPEND headers_list Atom.hpp -ChargeDistribution.hpp -Factory.hpp -Logger.hpp -LoggerImpl.hpp -MathUtils.hpp -Molecule.hpp +list(APPEND headers_list Atom.hpp ChargeDistribution.hpp Factory.hpp + Logger.hpp LoggerImpl.hpp MathUtils.hpp Molecule.hpp QuadratureRules.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp Stencils.hpp Symmetry.hpp Timer.hpp cnpy.hpp) set_source_files_properties(cnpy.hpp PROPERTIES COMPILE_FLAGS -w) # List of sources -list(APPEND sources_list Atom.cpp ChargeDistribution.cpp Molecule.cpp Solvent.cpp Sphere.cpp Symmetry.cpp cnpy.cpp) +list(APPEND sources_list Atom.cpp ChargeDistribution.cpp + Molecule.cpp QuadratureRules.cpp Solvent.cpp Sphere.cpp Symmetry.cpp cnpy.cpp) set_source_files_properties(cnpy.cpp PROPERTIES COMPILE_FLAGS -w) add_library(utils OBJECT ${sources_list} ${headers_list}) diff --git a/src/utils/QuadratureRules.cpp b/src/utils/QuadratureRules.cpp new file mode 100644 index 000000000..275831eb0 --- /dev/null +++ b/src/utils/QuadratureRules.cpp @@ -0,0 +1,162 @@ +#include "QuadratureRules.hpp" + +#include + +#include "Config.hpp" + +namespace pcm { +namespace utils { +namespace detail { +QuadratureRule initializeRule(int nNodes) { + switch (nNodes) { + case 16: + return GaussLegendre16(); + case 32: + return GaussLegendre32(); + case 64: + return GaussLegendre64(); + default: + return GaussLegendre16(); + } +} + +QuadratureRule GaussLegendre16() { + std::vector x16(8, 0); + x16[0] = 0.9894009349916499325961542; + x16[1] = 0.9445750230732325760779884; + x16[2] = 0.8656312023878317438804679; + x16[3] = 0.7554044083550030338951012; + x16[4] = 0.6178762444026437484466718; + x16[5] = 0.4580167776572273863424194; + x16[6] = 0.2816035507792589132304605; + x16[7] = 0.0950125098376374401853193; + + std::vector w16(8, 0); + w16[0] = 0.0271524594117540948517806; + w16[1] = 0.0622535239386478928628438; + w16[2] = 0.0951585116824927848099251; + w16[3] = 0.1246289712555338720524763; + w16[4] = 0.1495959888165767320815017; + w16[5] = 0.1691565193950025381893121; + w16[6] = 0.1826034150449235888667637; + w16[7] = 0.1894506104550684962853967; + + return pcm::make_tuple(x16, w16); +} + +QuadratureRule GaussLegendre32() { + std::vector x32(16, 0); + x32[0] = 0.9972638618494815635449811; + x32[1] = 0.9856115115452683354001750; + x32[2] = 0.9647622555875064307738119; + x32[3] = 0.9349060759377396891709191; + x32[4] = 0.8963211557660521239653072; + x32[5] = 0.8493676137325699701336930; + x32[6] = 0.7944837959679424069630973; + x32[7] = 0.7321821187402896803874267; + x32[8] = 0.6630442669302152009751152; + x32[9] = 0.5877157572407623290407455; + x32[10] = 0.5068999089322293900237475; + x32[11] = 0.4213512761306353453641194; + x32[12] = 0.3318686022821276497799168; + x32[13] = 0.2392873622521370745446032; + x32[14] = 0.1444719615827964934851864; + x32[15] = 0.0483076656877383162348126; + + std::vector w32(16, 0); + w32[0] = 0.0070186100094700966004071; + w32[1] = 0.0162743947309056706051706; + w32[2] = 0.0253920653092620594557526; + w32[3] = 0.0342738629130214331026877; + w32[4] = 0.0428358980222266806568786; + w32[5] = 0.0509980592623761761961632; + w32[6] = 0.0586840934785355471452836; + w32[7] = 0.0658222227763618468376501; + w32[8] = 0.0723457941088485062253994; + w32[9] = 0.0781938957870703064717409; + w32[10] = 0.0833119242269467552221991; + w32[11] = 0.0876520930044038111427715; + w32[12] = 0.0911738786957638847128686; + w32[13] = 0.0938443990808045656391802; + w32[14] = 0.0956387200792748594190820; + w32[15] = 0.0965400885147278005667648; + + return pcm::make_tuple(x32, w32); +} + +QuadratureRule GaussLegendre64() { + std::vector x64(32, 0); + + x64[0] = 0.9993050417357721394569056; + x64[1] = 0.9963401167719552793469245; + x64[2] = 0.9910133714767443207393824; + x64[3] = 0.9833362538846259569312993; + x64[4] = 0.9733268277899109637418535; + x64[5] = 0.9610087996520537189186141; + x64[6] = 0.9464113748584028160624815; + x64[7] = 0.9295691721319395758214902; + x64[8] = 0.9105221370785028057563807; + x64[9] = 0.8893154459951141058534040; + x64[10] = 0.8659993981540928197607834; + x64[11] = 0.8406292962525803627516915; + x64[12] = 0.8132653151227975597419233; + x64[13] = 0.7839723589433414076102205; + x64[14] = 0.7528199072605318966118638; + x64[15] = 0.7198818501716108268489402; + x64[16] = 0.6852363130542332425635584; + x64[17] = 0.6489654712546573398577612; + x64[18] = 0.6111553551723932502488530; + x64[19] = 0.5718956462026340342838781; + x64[20] = 0.5312794640198945456580139; + x64[21] = 0.4894031457070529574785263; + x64[22] = 0.4463660172534640879849477; + x64[23] = 0.4022701579639916036957668; + x64[24] = 0.3572201583376681159504426; + x64[25] = 0.3113228719902109561575127; + x64[26] = 0.2646871622087674163739642; + x64[27] = 0.2174236437400070841496487; + x64[28] = 0.1696444204239928180373136; + x64[29] = 0.1214628192961205544703765; + x64[30] = 0.0729931217877990394495429; + x64[31] = 0.0243502926634244325089558; + + std::vector w64(32, 0); + + w64[0] = 0.0017832807216964329472961; + w64[1] = 0.0041470332605624676352875; + w64[2] = 0.0065044579689783628561174; + w64[3] = 0.0088467598263639477230309; + w64[4] = 0.0111681394601311288185905; + w64[5] = 0.0134630478967186425980608; + w64[6] = 0.0157260304760247193219660; + w64[7] = 0.0179517157756973430850453; + w64[8] = 0.0201348231535302093723403; + w64[9] = 0.0222701738083832541592983; + w64[10] = 0.0243527025687108733381776; + w64[11] = 0.0263774697150546586716918; + w64[12] = 0.0283396726142594832275113; + w64[13] = 0.0302346570724024788679741; + w64[14] = 0.0320579283548515535854675; + w64[15] = 0.0338051618371416093915655; + w64[16] = 0.0354722132568823838106931; + w64[17] = 0.0370551285402400460404151; + w64[18] = 0.0385501531786156291289625; + w64[19] = 0.0399537411327203413866569; + w64[20] = 0.0412625632426235286101563; + w64[21] = 0.0424735151236535890073398; + w64[22] = 0.0435837245293234533768279; + w64[23] = 0.0445905581637565630601347; + w64[24] = 0.0454916279274181444797710; + w64[25] = 0.0462847965813144172959532; + w64[26] = 0.0469681828162100173253263; + w64[27] = 0.0475401657148303086622822; + w64[28] = 0.0479993885964583077281262; + w64[29] = 0.0483447622348029571697695; + w64[30] = 0.0485754674415034269347991; + w64[31] = 0.0486909570091397203833654; + + return pcm::make_tuple(x64, w64); +} +} // namespace detail +} // namespace utils +} // namespace pcm diff --git a/src/utils/QuadratureRules.hpp b/src/utils/QuadratureRules.hpp index 094aaf9da..aaac485c0 100644 --- a/src/utils/QuadratureRules.hpp +++ b/src/utils/QuadratureRules.hpp @@ -27,186 +27,34 @@ #include "Config.hpp" -#include -#include +namespace pcm { +namespace utils { +namespace detail { +typedef pcm::tuple, std::vector > QuadratureRule; -template struct QuadratureRule { - int nPoints() { return PointsPolicy::nPoints(); } - double abscissa(int i) { return PointsPolicy::gaussAbscissa(i); } - double weight(int i) { return PointsPolicy::gaussWeight(i); } -}; - -struct gauss16 { - int nPoints() { return 16; } - /*! Abscissae for 16-point Gaussian quadrature rule */ - static double gaussAbscissa(int i) { - static std::vector x16(8); - - x16[0] = 0.9894009349916499325961542; - x16[1] = 0.9445750230732325760779884; - x16[2] = 0.8656312023878317438804679; - x16[3] = 0.7554044083550030338951012; - x16[4] = 0.6178762444026437484466718; - x16[5] = 0.4580167776572273863424194; - x16[6] = 0.2816035507792589132304605; - x16[7] = 0.0950125098376374401853193; - - return x16[i]; - } - /*! Weights for 16-point Gaussian quadrature rule */ - static double gaussWeight(int i) { - static std::vector w16(8); - - w16[0] = 0.0271524594117540948517806; - w16[1] = 0.0622535239386478928628438; - w16[2] = 0.0951585116824927848099251; - w16[3] = 0.1246289712555338720524763; - w16[4] = 0.1495959888165767320815017; - w16[5] = 0.1691565193950025381893121; - w16[6] = 0.1826034150449235888667637; - w16[7] = 0.1894506104550684962853967; +QuadratureRule initializeRule(int nNodes); - return w16[i]; - } -}; - -struct gauss32 { - int nPoints() { return 32; } - /*! Abscissae for 32-point Gaussian quadrature rule */ - static double gaussAbscissa(int i) { - static std::vector x32(16); - - x32[0] = 0.9972638618494815635449811; - x32[1] = 0.9856115115452683354001750; - x32[2] = 0.9647622555875064307738119; - x32[3] = 0.9349060759377396891709191; - x32[4] = 0.8963211557660521239653072; - x32[5] = 0.8493676137325699701336930; - x32[6] = 0.7944837959679424069630973; - x32[7] = 0.7321821187402896803874267; - x32[8] = 0.6630442669302152009751152; - x32[9] = 0.5877157572407623290407455; - x32[10] = 0.5068999089322293900237475; - x32[11] = 0.4213512761306353453641194; - x32[12] = 0.3318686022821276497799168; - x32[13] = 0.2392873622521370745446032; - x32[14] = 0.1444719615827964934851864; - x32[15] = 0.0483076656877383162348126; - - return x32[i]; - } +QuadratureRule GaussLegendre16(); - /*! Weights for 32-point Gaussian quadrature rule */ - static double gaussWeight(int i) { - static std::vector w32(16); +QuadratureRule GaussLegendre32(); - w32[0] = 0.0070186100094700966004071; - w32[1] = 0.0162743947309056706051706; - w32[2] = 0.0253920653092620594557526; - w32[3] = 0.0342738629130214331026877; - w32[4] = 0.0428358980222266806568786; - w32[5] = 0.0509980592623761761961632; - w32[6] = 0.0586840934785355471452836; - w32[7] = 0.0658222227763618468376501; - w32[8] = 0.0723457941088485062253994; - w32[9] = 0.0781938957870703064717409; - w32[10] = 0.0833119242269467552221991; - w32[11] = 0.0876520930044038111427715; - w32[12] = 0.0911738786957638847128686; - w32[13] = 0.0938443990808045656391802; - w32[14] = 0.0956387200792748594190820; - w32[15] = 0.0965400885147278005667648; +QuadratureRule GaussLegendre64(); +} // namespace detail - return w32[i]; +template class GaussLegendreRule { +public: + GaussLegendreRule() + : nPoints_(nNodes), abscissa_((nPoints_ / 2), 0), weight_((nPoints_ / 2), 0) { + pcm::tie(abscissa_, weight_) = detail::initializeRule(nPoints_); } + int nPoints() const { return nPoints_; } + double abscissa(int i) const { return abscissa_[i]; } + double weight(int i) const { return weight_[i]; } + +protected: + int nPoints_; + std::vector abscissa_; + std::vector weight_; }; - -struct gauss64 { - int nPoints() { return 64; } - /*! Abscissae for 64-point Gaussian quadrature rule */ - static double gaussAbscissa(int i) { - static std::vector x64(32); - - x64[0] = 0.9993050417357721394569056; - x64[1] = 0.9963401167719552793469245; - x64[2] = 0.9910133714767443207393824; - x64[3] = 0.9833362538846259569312993; - x64[4] = 0.9733268277899109637418535; - x64[5] = 0.9610087996520537189186141; - x64[6] = 0.9464113748584028160624815; - x64[7] = 0.9295691721319395758214902; - x64[8] = 0.9105221370785028057563807; - x64[9] = 0.8893154459951141058534040; - x64[10] = 0.8659993981540928197607834; - x64[11] = 0.8406292962525803627516915; - x64[12] = 0.8132653151227975597419233; - x64[13] = 0.7839723589433414076102205; - x64[14] = 0.7528199072605318966118638; - x64[15] = 0.7198818501716108268489402; - x64[16] = 0.6852363130542332425635584; - x64[17] = 0.6489654712546573398577612; - x64[18] = 0.6111553551723932502488530; - x64[19] = 0.5718956462026340342838781; - x64[20] = 0.5312794640198945456580139; - x64[21] = 0.4894031457070529574785263; - x64[22] = 0.4463660172534640879849477; - x64[23] = 0.4022701579639916036957668; - x64[24] = 0.3572201583376681159504426; - x64[25] = 0.3113228719902109561575127; - x64[26] = 0.2646871622087674163739642; - x64[27] = 0.2174236437400070841496487; - x64[28] = 0.1696444204239928180373136; - x64[29] = 0.1214628192961205544703765; - x64[30] = 0.0729931217877990394495429; - x64[31] = 0.0243502926634244325089558; - - return x64[i]; - } - - /*! Weights for 64-point Gaussian quadrature rule */ - static double gaussWeight(int i) { - static std::vector w64(32); - - w64[0] = 0.0017832807216964329472961; - w64[1] = 0.0041470332605624676352875; - w64[2] = 0.0065044579689783628561174; - w64[3] = 0.0088467598263639477230309; - w64[4] = 0.0111681394601311288185905; - w64[5] = 0.0134630478967186425980608; - w64[6] = 0.0157260304760247193219660; - w64[7] = 0.0179517157756973430850453; - w64[8] = 0.0201348231535302093723403; - w64[9] = 0.0222701738083832541592983; - w64[10] = 0.0243527025687108733381776; - w64[11] = 0.0263774697150546586716918; - w64[12] = 0.0283396726142594832275113; - w64[13] = 0.0302346570724024788679741; - w64[14] = 0.0320579283548515535854675; - w64[15] = 0.0338051618371416093915655; - w64[16] = 0.0354722132568823838106931; - w64[17] = 0.0370551285402400460404151; - w64[18] = 0.0385501531786156291289625; - w64[19] = 0.0399537411327203413866569; - w64[20] = 0.0412625632426235286101563; - w64[21] = 0.0424735151236535890073398; - w64[22] = 0.0435837245293234533768279; - w64[23] = 0.0445905581637565630601347; - w64[24] = 0.0454916279274181444797710; - w64[25] = 0.0462847965813144172959532; - w64[26] = 0.0469681828162100173253263; - w64[27] = 0.0475401657148303086622822; - w64[28] = 0.0479993885964583077281262; - w64[29] = 0.0483447622348029571697695; - w64[30] = 0.0485754674415034269347991; - w64[31] = 0.0486909570091397203833654; - - return w64[i]; - } -}; - -namespace mpl = boost::mpl; - -typedef mpl::map, gauss16>, - mpl::pair, gauss32>, - mpl::pair, gauss64> > - rules_map; +} // namespace utils +} // namespace pcm From 9304b48a1cabcb2e4eb755260d52af19d54a92aa Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 18:10:10 +0100 Subject: [PATCH 05/28] License header added to utils/QuadratureRules.cpp --- src/utils/QuadratureRules.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/utils/QuadratureRules.cpp b/src/utils/QuadratureRules.cpp index 275831eb0..e79ccbc66 100644 --- a/src/utils/QuadratureRules.cpp +++ b/src/utils/QuadratureRules.cpp @@ -1,3 +1,26 @@ +/* + * PCMSolver, an API for the Polarizable Continuum Model + * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. + * + * This file is part of PCMSolver. + * + * PCMSolver is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * PCMSolver is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with PCMSolver. If not, see . + * + * For information on the complete list of contributors to the + * PCMSolver API, see: + */ + #include "QuadratureRules.hpp" #include From 6b4427cc9a3416b60958c0022c9feb87654ad2c8 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 18:15:58 +0100 Subject: [PATCH 06/28] Remove unused headers --- src/bin/run_pcm.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/bin/run_pcm.cpp b/src/bin/run_pcm.cpp index ab352f5bd..043b96488 100644 --- a/src/bin/run_pcm.cpp +++ b/src/bin/run_pcm.cpp @@ -34,10 +34,6 @@ #include -// Include Boost headers here -#include -#include - #include "interface/Input.hpp" #include "interface/Meddle.hpp" #include "utils/ChargeDistribution.hpp" From 5c094d6eee2a9ac349f2bcd26082c3cf0301ad15 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 18:29:05 +0100 Subject: [PATCH 07/28] Fix comments from @MinazoBot --- src/interface/Input.cpp | 44 +++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/interface/Input.cpp b/src/interface/Input.cpp index 70d898419..7f7331f7b 100644 --- a/src/interface/Input.cpp +++ b/src/interface/Input.cpp @@ -24,7 +24,7 @@ #include "Input.hpp" #include -#include +#include #include #include #include @@ -32,8 +32,8 @@ #include "Config.hpp" -#include #include "utils/getkw/Getkw.h" +#include #include "PCMInput.h" #include "bi_operators/BIOperatorData.hpp" @@ -94,7 +94,8 @@ void Input::reader(const std::string & filename) { Eigen::Vector3d center; center = (Eigen::Vector3d() << spheresInput[j], spheresInput[j + 1], - spheresInput[j + 2]).finished(); + spheresInput[j + 2]) + .finished(); Sphere sph(center, spheresInput[j + 3]); spheres_.push_back(sph); j += 4; @@ -422,29 +423,33 @@ int integralEquation(const std::string & name) { #ifndef HAS_CXX11_LAMBDA std::string left_trim(std::string s) { - s.erase(s.begin(), std::find_if(s.begin(), s.end(), - std::not1(std::ptr_fun(std::isspace)))); - return s; + s.erase(s.begin(), + std::find_if( + s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace)))); + return s; } std::string right_trim(std::string s) { - s.erase(std::find_if(s.rbegin(), s.rend(), - std::not1(std::ptr_fun(std::isspace))).base(), s.end()); - return s; + s.erase(std::find_if( + s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))) + .base(), + s.end()); + return s; } -#else /* HAS_CXX11_LAMBDA */ +#else /* HAS_CXX11_LAMBDA */ std::string left_trim(std::string s) { - s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { - return !std::isspace(ch); - })); - return s; + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { + return !std::isspace(ch); + })); + return s; } std::string right_trim(std::string s) { - s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { - return !std::isspace(ch); - }).base(), s.end()); - return s; + s.erase( + std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }) + .base(), + s.end()); + return s; } #endif /* HAS_CXX11_LAMBDA */ @@ -470,7 +475,8 @@ std::string trim(const char * src) { } std::string uppercase(std::string s) { - std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun(std::toupper)); + std::transform( + s.begin(), s.end(), s.begin(), std::ptr_fun(std::toupper)); return s; } From 277b7ba495f903e1bdc18b655ef9f19cf2be5a4f Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 23 Nov 2017 19:20:34 +0100 Subject: [PATCH 08/28] Clean up input from unreleased functionality Supersedes #81 by @ilfreddy --- doc/users/input.rst | 3 +- src/cavity/CavityData.hpp | 26 +--- src/interface/Input.cpp | 36 +---- src/interface/Input.hpp | 19 +-- src/solver/SolverData.hpp | 9 +- tests/input/CMakeLists.txt | 20 +-- tests/input/cpcm.inp | 22 +++ tests/input/diffuse.inp | 13 +- .../{input_tsless.cpp => input_cpcm.cpp} | 21 ++- tests/input/input_diffuse.cpp | 16 +-- tests/input/input_restart.cpp | 10 -- tests/input/input_wavelet.cpp | 107 -------------- tests/input/tsless.inp | 24 ---- tests/input/wavelet.inp | 33 ----- tools/pcmsolver.py.in | 130 +++--------------- 15 files changed, 75 insertions(+), 414 deletions(-) create mode 100644 tests/input/cpcm.inp rename tests/input/{input_tsless.cpp => input_cpcm.cpp} (84%) delete mode 100644 tests/input/input_wavelet.cpp delete mode 100644 tests/input/tsless.inp delete mode 100644 tests/input/wavelet.inp diff --git a/doc/users/input.rst b/doc/users/input.rst index 642691f4d..cac3d1001 100644 --- a/doc/users/input.rst +++ b/doc/users/input.rst @@ -128,8 +128,7 @@ Cavity section keywords * **Default**: empty string Area - Average area (weight) of the surface partition for the GePol (TsLess) - cavity. + Average area (weight) of the surface partition for the GePol cavity. * **Type**: double * **Valid values**: :math:`d \geq 0.01\,\text{a.u.}^2` diff --git a/src/cavity/CavityData.hpp b/src/cavity/CavityData.hpp index af12559ba..760a0b871 100644 --- a/src/cavity/CavityData.hpp +++ b/src/cavity/CavityData.hpp @@ -43,23 +43,11 @@ struct CavityData { double area; /*! The radius of the spherical probe representing the solvent */ double probeRadius; - /*! The minimal distance between two sampling points on different spheres. Relevant - * for TsLessCavity */ - double minDistance; - /*! The maximum derivative order to be used in the definition of the smoothing - * function. Relevant for TsLessCavity */ - int derOrder; /*! Triggers the addition of spheres not centered on atoms, relevant for * GePolCavity */ double minimalRadius; - /*! Patch level, relevant for WaveletCavity */ - int patchLevel; - /*! Relevant for WaveletCavity */ - double coarsity; /*! Name of the .npz file containing the cavity specification for a restart */ std::string filename; - /*! Name of the text file with list of points for a wavelet cavityr restart */ - std::string dyadicFile; /*! Whether the structure was initialized with user input or not */ bool empty; @@ -68,24 +56,14 @@ struct CavityData { const Molecule & _molec, double _area, double _probeRadius, - double _minDistance, - int _derOrder, double _minRadius, - int _patchLevel, - double _coarsity, - const std::string & _fname, - const std::string & _dyad) + const std::string & _fname) : cavityType(type), molecule(_molec), area(_area), probeRadius(_probeRadius), - minDistance(_minDistance), - derOrder(_derOrder), minimalRadius(_minRadius), - patchLevel(_patchLevel), - coarsity(_coarsity), - filename(_fname), - dyadicFile(_dyad) { + filename(_fname) { empty = false; } }; diff --git a/src/interface/Input.cpp b/src/interface/Input.cpp index 7f7331f7b..8d0176958 100644 --- a/src/interface/Input.cpp +++ b/src/interface/Input.cpp @@ -73,14 +73,9 @@ void Input::reader(const std::string & filename) { cavityType_ = cavity.getStr("TYPE"); area_ = cavity.getDbl("AREA"); - patchLevel_ = cavity.getInt("PATCHLEVEL"); - coarsity_ = cavity.getDbl("COARSITY"); - minDistance_ = cavity.getDbl("MINDISTANCE"); - derOrder_ = cavity.getInt("DERORDER"); if (cavityType_ == "RESTART") { cavFilename_ = cavity.getStr("NPZFILE"); } - dyadicFilename_ = cavity.getStr("DYADICFILE"); scaling_ = cavity.getBool("SCALING"); radiiSet_ = detail::uppercase(cavity.getStr("RADIISET")); @@ -167,7 +162,6 @@ void Input::reader(const std::string & filename) { integratorScaling_ = medium.getDbl("DIAGONALSCALING"); solverType_ = medium.getStr("SOLVERTYPE"); - equationType_ = detail::integralEquation(medium.getStr("EQUATIONTYPE")); correction_ = medium.getDbl("CORRECTION"); hermitivitize_ = medium.getBool("MATRIXSYMM"); isDynamic_ = medium.getBool("NONEQUILIBRIUM"); @@ -214,10 +208,6 @@ void Input::reader(const PCMInput & host_input) { cavityType_ = detail::trim_and_upper(host_input.cavity_type); area_ = host_input.area * angstrom2ToBohr2(); - patchLevel_ = host_input.patch_level; - coarsity_ = host_input.coarsity * angstromToBohr(); - minDistance_ = host_input.min_distance * angstromToBohr(); - derOrder_ = host_input.der_order; if (cavityType_ == "RESTART") { cavFilename_ = detail::trim(host_input.restart_name); // No case conversion here! } @@ -278,8 +268,6 @@ void Input::reader(const PCMInput & host_input) { integratorScaling_ = 1.07; solverType_ = detail::trim_and_upper(host_input.solver_type); - std::string inteq = detail::trim_and_upper(host_input.equation_type); - equationType_ = detail::integralEquation(inteq); correction_ = host_input.correction; hermitivitize_ = true; isDynamic_ = false; @@ -358,17 +346,8 @@ void Input::initMolecule() { } CavityData Input::cavityParams() const { - return CavityData(cavityType_, - molecule_, - area_, - probeRadius_, - minDistance_, - derOrder_, - minimalRadius_, - patchLevel_, - coarsity_, - cavFilename_, - dyadicFilename_); + return CavityData( + cavityType_, molecule_, area_, probeRadius_, minimalRadius_, cavFilename_); } GreenData Input::insideGreenParams() const { @@ -404,7 +383,7 @@ GreenData Input::outsideDynamicGreenParams() const { } SolverData Input::solverParams() const { - return SolverData(solverType_, correction_, equationType_, hermitivitize_); + return SolverData(solverType_, correction_, hermitivitize_); } BIOperatorData Input::integratorParams() const { @@ -412,15 +391,6 @@ BIOperatorData Input::integratorParams() const { } namespace detail { -int integralEquation(const std::string & name) { - static std::map mapStringToInt; - mapStringToInt.insert(std::map::value_type("FIRSTKIND", 0)); - mapStringToInt.insert(std::map::value_type("SECONDKIND", 1)); - mapStringToInt.insert(std::map::value_type("FULL", 2)); - - return mapStringToInt.find(name)->second; -} - #ifndef HAS_CXX11_LAMBDA std::string left_trim(std::string s) { s.erase(s.begin(), diff --git a/src/interface/Input.hpp b/src/interface/Input.hpp index 75c891da7..a6dfb5036 100644 --- a/src/interface/Input.hpp +++ b/src/interface/Input.hpp @@ -111,7 +111,6 @@ class Input { /// Medium section input Solvent solvent() const { return solvent_; } bool fromSolvent() const { return hasSolvent_; } - int equationType() const { return equationType_; } double correction() const { return correction_; } bool hermitivitize() const { return hermitivitize_; } bool isDynamic() const { return isDynamic_; } @@ -170,18 +169,8 @@ class Input { std::string cavityType_; /// Filename for the .npz cavity restart file std::string cavFilename_; - /// Filename for the wavelet cavity dyadic file - std::string dyadicFilename_; - /// Wavelet cavity patch level - int patchLevel_; - /// Wavelet cavity coarsity - double coarsity_; - /// GePol and TsLess cavities average element area + /// GePol cavity average element area double area_; - /// TsLess cavity minimal distance between sampling points - double minDistance_; - /// TsLess cavity maximum derivative order of switch function - int derOrder_; /// Whether the radii should be scaled by 1.2 bool scaling_; /// The set of radii to be used @@ -206,8 +195,6 @@ class Input { bool hasSolvent_; /// The solver type std::string solverType_; - /// The integral equation type (wavelet solvers) - int equationType_; /// Correction factor (C-PCM) double correction_; /// Whether the PCM matrix should be hermitivitized (collocation solvers) @@ -270,10 +257,6 @@ class Input { }; namespace detail { -/*! A useful map to convert the EquationType string to an integer which will be - * passed to the Solver CTOR. */ -int integralEquation(const std::string & name); - std::string left_trim(std::string s); std::string left_trim(const char * src); diff --git a/src/solver/SolverData.hpp b/src/solver/SolverData.hpp index d4fad2c13..bcaf500df 100644 --- a/src/solver/SolverData.hpp +++ b/src/solver/SolverData.hpp @@ -37,19 +37,14 @@ struct SolverData { std::string solverType; /*! The correction factor to be use in a CPCM calculation */ double correction; - /*! The type of integral equation to solve, relevant only for wavelet solvers */ - int integralEquation; /*! Triggers hermitivitization of the PCM matrix obtained by collocation */ bool hermitivitize; /*! Whether the structure was initialized with user input or not */ bool empty; SolverData() { empty = true; } - SolverData(const std::string & type, double corr, int int_eq = 1, bool symm = true) - : solverType(type), - correction(corr), - integralEquation(int_eq), - hermitivitize(symm) { + SolverData(const std::string & type, double corr, bool symm = true) + : solverType(type), correction(corr), hermitivitize(symm) { empty = false; } }; diff --git a/tests/input/CMakeLists.txt b/tests/input/CMakeLists.txt index 5926579ef..378eb2058 100644 --- a/tests/input/CMakeLists.txt +++ b/tests/input/CMakeLists.txt @@ -1,12 +1,10 @@ -add_library(input-tests OBJECT input_diffuse.cpp input_restart.cpp input_tsless.cpp input_wavelet.cpp input_multipoles.cpp) +add_library(input-tests OBJECT input_diffuse.cpp input_restart.cpp input_cpcm.cpp input_multipoles.cpp) if(BUILD_CUSTOM_BOOST) add_dependencies(input-tests custom_boost) endif() # Copy input files to ${PROJECT_BINARY_DIR}/tests/input (aka ${CMAKE_CURRENT_BINARY_DIR}) -file(COPY diffuse.inp restart.inp - tsless.inp wavelet.inp - multipoles.inp +file(COPY diffuse.inp restart.inp cpcm.inp multipoles.inp DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) add_test(NAME parser_script-diffuse COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_BINARY_DIR}/${PYMOD_INSTALL_FULLDIR}/pcmsolver.py diffuse.inp @@ -27,14 +25,8 @@ set_tests_properties(parser_script-restart PROPERTIES LABELS "parser;parser_scri add_Catch_test(input_restart "input;input_restart") set_tests_properties(input_restart PROPERTIES DEPENDS parser_script-restart) -add_test(NAME parser_script-tsless COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_BINARY_DIR}/${PYMOD_INSTALL_FULLDIR}/pcmsolver.py tsless.inp +add_test(NAME parser_script-cpcm COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_BINARY_DIR}/${PYMOD_INSTALL_FULLDIR}/pcmsolver.py cpcm.inp WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) -set_tests_properties(parser_script-tsless PROPERTIES LABELS "parser;parser_script" DEPENDS generate-pcmsolver-py) -add_Catch_test(input_tsless "input;input_tsless") -set_tests_properties(input_tsless PROPERTIES DEPENDS parser_script-tsless) - -add_test(NAME parser_script-wavelet COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_BINARY_DIR}/${PYMOD_INSTALL_FULLDIR}/pcmsolver.py wavelet.inp - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) -set_tests_properties(parser_script-wavelet PROPERTIES LABELS "parser;parser_script" DEPENDS generate-pcmsolver-py) -add_Catch_test(input_wavelet "input;input_wavelet") -set_tests_properties(input_wavelet PROPERTIES DEPENDS parser_script-wavelet) +set_tests_properties(parser_script-cpcm PROPERTIES LABELS "parser;parser_script" DEPENDS generate-pcmsolver-py) +add_Catch_test(input_cpcm "input;input_cpcm") +set_tests_properties(input_cpcm PROPERTIES DEPENDS parser_script-cpcm) diff --git a/tests/input/cpcm.inp b/tests/input/cpcm.inp new file mode 100644 index 000000000..21d734830 --- /dev/null +++ b/tests/input/cpcm.inp @@ -0,0 +1,22 @@ +UNITS = ANGSTROM +CODATA = 2002 +MEDIUM +{ + SOLVERTYPE = CPCM + CORRECTION = 0.5 + SOLVENT = CYCLOHEXANE + MATRIXSYMM = False + DIAGONALSCALING = 1.0694 +} + +CAVITY +{ + TYPE = GEPOL + AREA = 0.6 + SCALING = False + MINRADIUS = 0.3 + RADIISET = UFF + MODE = ATOMS + ATOMS = [1, 2, 4] + RADII = [1.4, 4.3, 1.2] +} diff --git a/tests/input/diffuse.inp b/tests/input/diffuse.inp index b734546e1..b29a07314 100644 --- a/tests/input/diffuse.inp +++ b/tests/input/diffuse.inp @@ -3,10 +3,9 @@ CODATA = 1998 MEDIUM { - SOLVERTYPE = WAVELET - EQUATIONTYPE = FIRSTKIND - PROBERADIUS = 1.385 + SOLVERTYPE = IEFPCM SOLVENT = EXPLICIT + PROBERADIUS = 1.5 GREEN { TYPE=VACUUM @@ -27,10 +26,10 @@ MEDIUM CAVITY { - TYPE = WAVELET - DYADICFILE = benzene2.dat - PATCHLEVEL = 1 - COARSITY = 0.3 + TYPE = GEPOL + AREA = 0.3 + SCALING = True + RADIISET = BONDI MODE = EXPLICIT SPHERES = [ 0.00, 0.00, 0.00, 1.80, 0.00, -0.96, 0.00, 1.44, diff --git a/tests/input/input_tsless.cpp b/tests/input/input_cpcm.cpp similarity index 84% rename from tests/input/input_tsless.cpp rename to tests/input/input_cpcm.cpp index fa453a1c5..eccdd7585 100644 --- a/tests/input/input_tsless.cpp +++ b/tests/input/input_cpcm.cpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -40,22 +40,21 @@ using pcm::Input; using pcm::utils::Sphere; /*! \class Input - * \test \b Input_TsLess tests input reading on an input file parsed by pcmsolver.py + * \test \b Input_CPCM tests input reCPCMading on an input file parsed by + * pcmsolver.py */ -TEST_CASE("Input reading using GetKw for an input file for a TsLess cavity", - "[input][input_tsless]") { - std::string filename = "@tsless.inp"; +TEST_CASE("Input reading using GetKw for an input file for a CPCM solver", + "[input][input_cpcm]") { + std::string filename = "@cpcm.inp"; Input parsedInput = Input(filename); std::string units = "ANGSTROM"; int CODATAyear = 2002; - std::string cavityType = "TSLESS"; + std::string type = "GEPOL"; double area = 0.6 * angstrom2ToBohr2(); - double minDistance = 5.0 * angstromToBohr(); - int derOrder = 25; bool scaling = false; double diagonalScaling = 1.0694; std::string radiiSet = "UFF"; - double minimalRadius = 0.1 * angstromToBohr(); + double minimalRadius = 0.3 * angstromToBohr(); std::string mode = "ATOMS"; std::vector atoms; std::vector radii; @@ -75,10 +74,8 @@ TEST_CASE("Input reading using GetKw for an input file for a TsLess cavity", REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(cavityType == parsedInput.cavityParams().cavityType); + REQUIRE(type == parsedInput.cavityParams().cavityType); REQUIRE(area == Approx(parsedInput.cavityParams().area)); - REQUIRE(minDistance == Approx(parsedInput.cavityParams().minDistance)); - REQUIRE(derOrder == parsedInput.cavityParams().derOrder); REQUIRE(scaling == parsedInput.scaling()); REQUIRE(diagonalScaling == Approx(parsedInput.integratorScaling())); REQUIRE(radiiSet == parsedInput.radiiSet()); diff --git a/tests/input/input_diffuse.cpp b/tests/input/input_diffuse.cpp index a4d72a0e4..95d5269a1 100644 --- a/tests/input/input_diffuse.cpp +++ b/tests/input/input_diffuse.cpp @@ -49,9 +49,8 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment Input parsedInput = Input(filename); std::string units = "ANGSTROM"; int CODATAyear = 1998; - std::string type = "WAVELET"; - int patchLevel = 1; - double coarsity = 0.3; + std::string cavityType = "GEPOL"; + double area = 0.3 * angstrom2ToBohr2(); bool scaling = true; double diagonalScaling = 1.07; std::string radiiSet = "BONDI"; @@ -69,9 +68,8 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment spheres.push_back(sph1); spheres.push_back(sph2); spheres.push_back(sph3); - std::string solverType = "WAVELET"; - int equationType = 0; - double probeRadius = 1.385 * angstromToBohr(); // The value for water + std::string solverType = "IEFPCM"; + double probeRadius = 1.5 * angstromToBohr(); // The value for water std::string greenInsideType = "VACUUM_NUMERICAL"; std::string greenOutsideType = "SPHERICALDIFFUSE_NUMERICAL_ERF"; double epsilonInside = 1.0; @@ -86,9 +84,8 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment REQUIRE(units == parsedInput.units()); REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(type == parsedInput.cavityParams().cavityType); - REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); - REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); + REQUIRE(cavityType == parsedInput.cavityParams().cavityType); + REQUIRE(area == Approx(parsedInput.cavityParams().area)); REQUIRE(scaling == parsedInput.scaling()); REQUIRE(radiiSet == parsedInput.radiiSet()); REQUIRE(mode == parsedInput.mode()); @@ -100,7 +97,6 @@ TEST_CASE("Input reading using GetKw for an input file for a diffuse environment REQUIRE(spheres[i].radius == Approx(parsedInput.spheres(i).radius)); } REQUIRE(solverType == parsedInput.solverParams().solverType); - REQUIRE(equationType == parsedInput.equationType()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); REQUIRE(greenOutsideType == diff --git a/tests/input/input_restart.cpp b/tests/input/input_restart.cpp index c08965219..22bc1bb82 100644 --- a/tests/input/input_restart.cpp +++ b/tests/input/input_restart.cpp @@ -51,11 +51,7 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", int CODATAyear = 2010; std::string cavityType = "RESTART"; std::string cavFilename = "cavity.npz"; - int patchLevel = 2; - double coarsity = 0.5; double area = 0.3; - double minDistance = 0.1; - int derOrder = 4; bool scaling = true; std::string radiiSet = "BONDI"; double minimalRadius = 100.0; @@ -63,7 +59,6 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", std::string mode = "IMPLICIT"; std::string solvent = "Water"; // Name in the Solvent object std::string solverType = "IEFPCM"; - int equationType = 1; double correction = 0.0; bool hermitivitize = true; double probeRadius = 1.385 * angstromToBohr(); // The value for water @@ -74,19 +69,14 @@ TEST_CASE("Input reading using GetKw for an input file for a restart cavity", REQUIRE(CODATAyear == parsedInput.CODATAyear()); REQUIRE(cavityType == parsedInput.cavityParams().cavityType); REQUIRE(cavFilename == parsedInput.cavityParams().filename); - REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); - REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); REQUIRE(area == Approx(parsedInput.cavityParams().area)); - REQUIRE(minDistance == Approx(parsedInput.cavityParams().minDistance)); REQUIRE(diagonalScaling == Approx(parsedInput.integratorScaling())); - REQUIRE(derOrder == parsedInput.cavityParams().derOrder); REQUIRE(scaling == parsedInput.scaling()); REQUIRE(radiiSet == parsedInput.radiiSet()); REQUIRE(minimalRadius == Approx(parsedInput.cavityParams().minimalRadius)); REQUIRE(mode == parsedInput.mode()); REQUIRE(solvent == parsedInput.solvent().name); REQUIRE(solverType == parsedInput.solverParams().solverType); - REQUIRE(equationType == parsedInput.equationType()); REQUIRE(correction == Approx(parsedInput.correction())); REQUIRE(hermitivitize == parsedInput.hermitivitize()); REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); diff --git a/tests/input/input_wavelet.cpp b/tests/input/input_wavelet.cpp deleted file mode 100644 index f9dc742a0..000000000 --- a/tests/input/input_wavelet.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * PCMSolver, an API for the Polarizable Continuum Model - * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. - * - * This file is part of PCMSolver. - * - * PCMSolver is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PCMSolver is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with PCMSolver. If not, see . - * - * For information on the complete list of contributors to the - * PCMSolver API, see: - */ - -#include "catch.hpp" - -#include -#include -#include - -#include - -#include "bi_operators/BIOperatorData.hpp" -#include "cavity/CavityData.hpp" -#include "green/GreenData.hpp" -#include "interface/Input.hpp" -#include "solver/SolverData.hpp" -#include "utils/Sphere.hpp" - -using pcm::Input; -using pcm::utils::Sphere; - -/*! \class Input - * \test \b InputWaveletTest_Wavelet tests input reading on an input file parsed by - * pcmsolver.py - */ -TEST_CASE("Input reading using GetKw for an input file for a wavelet cavity", - "[input][input_wavelet]") { - std::string filename = "@wavelet.inp"; - Input parsedInput = Input(filename); - std::string units = "ANGSTROM"; - int CODATAyear = 1998; - std::string cavityType = "WAVELET"; - int patchLevel = 1; - double coarsity = 0.3; - bool scaling = true; - double diagonalScaling = 1.07; - std::string radiiSet = "BONDI"; - std::string mode = "EXPLICIT"; - Eigen::Vector3d c1, c2, c3; - c1 << 0.00, 0.00, 0.00; - c2 << 0.00, -0.96, 0.00; - c3 << -0.905, 0.32, 0.00; - c2 *= angstromToBohr(); - c3 *= angstromToBohr(); - Sphere sph1(c1, 1.80 * angstromToBohr()); - Sphere sph2(c2, 1.44 * angstromToBohr()); - Sphere sph3(c3, 1.44 * angstromToBohr()); - std::vector spheres; - spheres.push_back(sph1); - spheres.push_back(sph2); - spheres.push_back(sph3); - std::string solverType = "WAVELET"; - int equationType = 0; - double probeRadius = 1.385 * angstromToBohr(); // The value for water - std::string greenInsideType = "VACUUM_NUMERICAL"; - std::string greenOutsideType = "UNIFORMDIELECTRIC_GRADIENT"; - double epsilonInside = 1.0; - double epsilonStaticOutside = 78.39; - double epsilonDynamicOutside = 10.423; - - REQUIRE(units == parsedInput.units()); - REQUIRE(CODATAyear == parsedInput.CODATAyear()); - REQUIRE(cavityType == parsedInput.cavityParams().cavityType); - REQUIRE(patchLevel == parsedInput.cavityParams().patchLevel); - REQUIRE(coarsity == Approx(parsedInput.cavityParams().coarsity)); - REQUIRE(scaling == parsedInput.scaling()); - REQUIRE(radiiSet == parsedInput.radiiSet()); - REQUIRE(mode == parsedInput.mode()); - REQUIRE(diagonalScaling == Approx(parsedInput.integratorScaling())); - for (size_t i = 0; i < spheres.size(); ++i) { - for (int j = 0; j < 3; ++j) { - REQUIRE(spheres[i].center(j) == Approx(parsedInput.spheres(i).center(j))); - } - REQUIRE(spheres[i].radius == Approx(parsedInput.spheres(i).radius)); - } - REQUIRE(solverType == parsedInput.solverParams().solverType); - REQUIRE(equationType == parsedInput.equationType()); - REQUIRE(probeRadius == Approx(parsedInput.cavityParams().probeRadius)); - REQUIRE(greenInsideType == parsedInput.insideGreenParams().greensFunctionType); - REQUIRE(greenOutsideType == - parsedInput.outsideStaticGreenParams().greensFunctionType); - REQUIRE(epsilonInside == Approx(parsedInput.insideGreenParams().epsilon)); - REQUIRE(epsilonStaticOutside == - Approx(parsedInput.outsideStaticGreenParams().epsilon)); - REQUIRE(epsilonDynamicOutside == - Approx(parsedInput.outsideDynamicGreenParams().epsilon)); -} diff --git a/tests/input/tsless.inp b/tests/input/tsless.inp deleted file mode 100644 index 7c7f5c140..000000000 --- a/tests/input/tsless.inp +++ /dev/null @@ -1,24 +0,0 @@ -UNITS = ANGSTROM -CODATA = 2002 -MEDIUM -{ - SOLVERTYPE = CPCM - CORRECTION = 0.5 - SOLVENT = CYCLOHEXANE - MATRIXSYMM = False - DIAGONALSCALING = 1.0694 -} - -CAVITY -{ - TYPE = TSLESS - AREA = 0.6 - SCALING = False - MINDISTANCE = 5.0 - MINRADIUS = 0.1 - RADIISET = UFF - DERORDER = 25 - MODE = ATOMS - ATOMS = [1, 2, 4] - RADII = [1.4, 4.3, 1.2] -} diff --git a/tests/input/wavelet.inp b/tests/input/wavelet.inp deleted file mode 100644 index 0da6c65a3..000000000 --- a/tests/input/wavelet.inp +++ /dev/null @@ -1,33 +0,0 @@ -UNITS = ANGSTROM -CODATA = 1998 -MEDIUM -{ - - SOLVERTYPE = WAVELET - EQUATIONTYPE = FIRSTKIND - PROBERADIUS = 1.385 - SOLVENT = EXPLICIT - GREEN - { - TYPE=VACUUM - DER = NUMERICAL - } - GREEN - { - TYPE = UNIFORMDIELECTRIC - EPS = 78.39 - EPSDYN = 10.423 - DER = GRADIENT - } -} - -CAVITY -{ - TYPE = WAVELET - PATCHLEVEL = 1 - COARSITY = 0.3 - MODE = EXPLICIT - SPHERES = [ 0.00, 0.00, 0.00, 1.80, - 0.00, -0.96, 0.00, 1.44, - -0.905, 0.32, 0.00, 1.44] -} diff --git a/tools/pcmsolver.py.in b/tools/pcmsolver.py.in index 3568163db..57c76a408 100644 --- a/tools/pcmsolver.py.in +++ b/tools/pcmsolver.py.in @@ -121,9 +121,8 @@ def convert_to_upper_case(filename): # "restart" should not be touched, whereas the rest of the file # has to be put in uppercase. npz_file = re.compile('NPZFILE', re.IGNORECASE) - dyadic_file = re.compile('DYADICFILE', re.IGNORECASE) for line in contents: - if (npz_file.search(line)) or (dyadic_file.search(line)): + if npz_file.search(line): rst_split = re.split(r"=", line) rst_split = rst_split[0].upper() + ' = ' + rst_split[1] line = ''.join(rst_split) @@ -232,71 +231,47 @@ def setup_keywords(): # Cavity section cavity = getkw.Section('CAVITY', callback=verify_cavity) # Type of the cavity - # Valid values: GEPOL, WAVELET, TSLESS and RESTART + # Valid values: GEPOL and RESTART cavity.add_kw('TYPE', 'STR') # Name of the file containing data for restarting a cavity # Valid for: Restart cavity # Default: empty string cavity.add_kw('NPZFILE', 'STR', '') - # Name of the file containing the list of points for a wavelet cavity - # Valid for: Wavelet cavity - # Default: empty string - cavity.add_kw('DYADICFILE', 'STR', '') - # Patch level - # Valid for: Wavelet cavity - # Valid values: integer strictly greater than 0 - # Default: 2 - cavity.add_kw('PATCHLEVEL', 'INT', 2) - # Coarsity - # Valid for: Wavelet cavity - # Valid values: double in ]0.0, 1.0[ - # Default: 0.5 - cavity.add_kw('COARSITY', 'DBL', 0.5) # Average area (in au^2) - # Valid for: GePol and TsLess cavities + # Valid for: GePol # Valid values: double strictly greater than 0.01 au^2 # Default: 0.3 au^2 cavity.add_kw('AREA', 'DBL', 0.3) - # Minimal distance between sampling points (in au) - # Valid for: TsLess cavity - # Valid values: double - # Default: 0.1 au - cavity.add_kw('MINDISTANCE', 'DBL', 0.1) - # Derivative order for the weight function - # Valid for: TsLess cavity - # Valid values: integer - # Default: 4 - cavity.add_kw('DERORDER', 'INT', 4) # Scaling of the atomic radii - # Valid for: GePol, Wavelet and TsLess + # Valid for: GePol # Valid values: boolean # Default: True cavity.add_kw('SCALING', 'BOOL', True) # Built-in radii set - # Valid for: GePol, Wavelet and TsLess + # Valid for: GePol # Valid values: BONDI, UFF or ALLINGER # Default: BONDI cavity.add_kw('RADIISET', 'STR', 'BONDI') # Minimal radius of added spheres (in au) - # Valid for: GePol and TsLess + # Valid for: GePol # Valid values: double greater than 0.4 au # Default: 100.0 au (no added spheres) cavity.add_kw('MINRADIUS', 'DBL', 100.0) # Spheres geometry creation mode - # Valid for: GePol, TsLess and Wavelet + # Valid for: GePol # Valid values: EXPLICIT, ATOMS or IMPLICIT # Default: IMPLICIT cavity.add_kw('MODE', 'STR', 'IMPLICIT') # List of atoms with custom radius - # Valid for: GePol, TsLess and Wavelet in MODE=ATOMS + # Valid for: GePol in MODE=ATOMS # Valid values: array of integers cavity.add_kw('ATOMS', 'INT_ARRAY') # List of custom radii - # Valid for: GePol, TsLess and Wavelet in MODE=ATOMS + # Valid for: GePol in MODE=ATOMS # Valid values: array of doubles cavity.add_kw('RADII', 'DBL_ARRAY') # List of spheres - # Valid for: GePol, TsLess and Wavelet in MODE=EXPLICIT + # Valid for: GePol in MODE=EXPLICIT # Valid values: array of doubles in format [x, y, z, R] cavity.add_kw('SPHERES', 'DBL_ARRAY', callback=verify_spheres) top.add_sect(cavity) @@ -304,22 +279,18 @@ def setup_keywords(): # Medium section medium = getkw.Section('MEDIUM', callback=verify_medium) # Type of solver - # Valid values: IEFPCM, CPCM, WAVELET or LINEAR + # Valid values: IEFPCM, CPCM medium.add_kw('SOLVERTYPE', 'STR', 'IEFPCM') # Whether nonequilibrium response is to be used - # Valid for: IEFPCM, CPCM, WAVELET or LINEAR + # Valid for: IEFPCM, CPCM # Valid values: boolean # Default: False medium.add_kw('NONEQUILIBRIUM', 'BOOL', False) # Solvent - # Valid for: IEFPCM, CPCM, Wavelet and PWL solvers + # Valid for: IEFPCM, CPCM # Valid values: string # Default: Explicit medium.add_kw('SOLVENT', 'STR', 'EXPLICIT') - # Type of integral equation - # Valid for: Wavelet and PWL - # Valid values: FIRSTKIND, SECONDKIND or FULL - medium.add_kw('EQUATIONTYPE', 'STR', 'SECONDKIND') # Symmetrization of the PCM matrix # Valid for: IEFPCM # Valid values: boolean @@ -342,25 +313,10 @@ def setup_keywords(): # Notes: values commonly used in the literature are 1.07 and 1.0694 medium.add_kw('DIAGONALSCALING', 'DBL', 1.07) # Radius of the solvent probe (in au) - # Valid for: IEFPCM, CPCM, Wavelet and PWL + # Valid for: IEFPCM, CPCM # Valid values: double in [0.1, 100.0] au # Default: 1.0 medium.add_kw('PROBERADIUS', 'DBL', 1.0) - # A priori compression parameter a - # Valid for: wavelet solvers - # Valid values: double greater than 1.0 - # Default: 1.25 - medium.add_kw('A', 'DBL', 1.25) - # A priori compression parameter d' - # Valid for: wavelet solvers - # Valid values: double greater than 1.0 - # Default: 1.25 (PWC) or 2.25 (PWL) - medium.add_kw('DPRIME', 'DBL', 0.0) - # A posteriori compression parameter b - # Valid for: wavelet solvers - # Valid values: double in ]0, 1[ - # Default: 0.001 - medium.add_kw('B', 'DBL', 0.001) top.add_sect(medium) # Green's function section @@ -500,7 +456,7 @@ def verify_top(section): def verify_cavity(section): - allowed = ('GEPOL', 'WAVELET', 'TSLESS', 'RESTART') + allowed = ('GEPOL', 'RESTART') type = section.get('TYPE') if (type.get() not in allowed): print(('Requested {} cavity is not among the allowed types: {}'.format(type, allowed))) @@ -512,8 +468,6 @@ def verify_cavity(section): convert_area_scalar(section['AREA']) if (section['MINRADIUS'].is_set()): convert_length_scalar(section['MINRADIUS']) - if (section['MINDISTANCE'].is_set()): - convert_length_scalar(section['MINDISTANCE']) if (type.get() == 'GEPOL'): area = section.get('AREA') @@ -526,33 +480,6 @@ def verify_cavity(section): if (mr < 0.4): print(('Requested minimal radius for added spheres too small: {}. Minimal value is: 0.4 au'.format(mr))) sys.exit(1) - elif (type.get() == 'WAVELET'): - key = section.get('PATCHLEVEL') - if (key.get() < 1): - print(('Invalid patch level requested: {}. Patch level must be greater than 0'.format(key.get()))) - sys.exit(1) - key = section.get('COARSITY') - if (key.get() < 0.0 or key.get() >= 1.0): - print(('Invalid coarsity requested: {}. Coarsity has to be within ]0, 1['.format(key.get()))) - sys.exit(1) - elif (type.get() == 'TSLESS'): - area = section.get('AREA') - a = area.get() - if (a < 0.01): - print(('Requested area value too small: {}. Minimal value is: 0.01 au^2'.format(a))) - sys.exit(1) - # minDistance = section.get('MINDISTANCE') - # md = minDistance.get() - # Insert a sanity check on minimal distance! - # if ( md < 0.4 ): - # print("Requested minimal distance between sampling points too small: {}. Minimal value is: 0.4 au".format(md)) - # sys.exit(1) - # derOrder = section.get('DERORDER') - # do = derOrder.get() - # Insert a check on derivative order - # if ( do > 4 ): - # print("Invalid derivative order requested: {}. Derivative order has to be within [1, 5]".format(md)) - # sys.exit(1) elif (type.get() == 'RESTART'): npzfile = section.get('NPZFILE') # Restart string is the filename, with extension, where the cavity specs were saved. @@ -641,39 +568,16 @@ def verify_medium(section): print('Probe radius has to be within [0.1,100] Atomic Units') sys.exit(1) - allowed_types = ('IEFPCM', 'CPCM', 'WAVELET', 'LINEAR') + allowed_types = ('IEFPCM', 'CPCM') key = section.get('SOLVERTYPE') val = key.get() if (val not in allowed_types): print(('Allowed types are: {}'.format(allowed_types))) sys.exit(1) - allowed_equations = ('FIRSTKIND', 'SECONDKIND', 'FULL') - key = section.get('EQUATIONTYPE') - val = key.get() - if (val not in allowed_equations): - print(('Allowed equations are: {}'.format(allowed_equations))) - sys.exit(1) - - a = section.get('A') - if (a.get() < 1.0): - print('A priori compression parameter a has to be greater than 1.0') - sys.exit(1) - dprime = section.get('DPRIME') - solver = section.get('SOLVERTYPE') - if (dprime.get() == 0.0): - if (solver.get() == 'WAVELET'): - dprime.set(1.25) - elif (solver.get() == 'LINEAR'): - dprime.set(2.25) - - b = section.get('B') - if (b.get() >= 1.0 and b.get() <= 0.0): - print('A posteriori compression parameter has to be in ]0.0, 1.0[') - sys.exit(1) def verify_green(section): - allowed = ('VACUUM', 'UNIFORMDIELECTRIC', 'SPHERICALDIFFUSE', 'ALTERNATESPHERICALDIFFUSE', 'METALSPHERE', + allowed = ('VACUUM', 'UNIFORMDIELECTRIC', 'SPHERICALDIFFUSE', 'METALSPHERE', 'GREENSFUNCTIONSUM') allowed_der = ('NUMERICAL', 'DERIVATIVE', 'GRADIENT', 'HESSIAN') allowed_profiles = ('TANH', 'ERF') From e6e19d1d93b317fce6a9642e416b8c55babba23b Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 18:37:52 +0100 Subject: [PATCH 09/28] Remove use of boost::math::sign --- src/cavity/Element.cpp | 5 ++--- src/utils/MathUtils.hpp | 9 +++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/cavity/Element.cpp b/src/cavity/Element.cpp index 72e6fc2a8..6719d8aa6 100644 --- a/src/cavity/Element.cpp +++ b/src/cavity/Element.cpp @@ -32,8 +32,7 @@ #include #include -#include - +#include "utils/MathUtils.hpp" #include "utils/Sphere.hpp" namespace pcm { @@ -144,7 +143,7 @@ void tangent_and_bitangent(const Eigen::Vector3d & n_, M.col(0) = n_; M.col(1) = t_; M.col(2) = b_; - if (boost::math::sign(M.determinant()) != 1) { + if (utils::sign(M.determinant()) != 1) { PCMSOLVER_ERROR("Frenet-Serret local frame is not left-handed!"); } } diff --git a/src/utils/MathUtils.hpp b/src/utils/MathUtils.hpp index 8b6aeae97..53f950333 100644 --- a/src/utils/MathUtils.hpp +++ b/src/utils/MathUtils.hpp @@ -104,6 +104,15 @@ inline bool isZero(double value, double threshold) { */ inline bool numericalZero(double value) { return (isZero(value, 1.0e-14)); } +/*! \fn inline int sign(T val) + * \param[in] val value whose sign should be determined + * \tparam type of the parameter val + * + * This function implements the signum function and returns the sign of the passed + * value: -1, 0 or 1 + */ +template inline int sign(T val) { return (T(0) < val) - (val < T(0)); } + /*! \fn inline void symmetryBlocking(Eigen::MatrixXd & matrix, int cavitySize, int * ntsirr, int nr_irrep) * \param[out] matrix the matrix to be block-diagonalized From 9b9804dd0192ab89ea9b656ff3f9ab811ffe8b39 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 18:53:51 +0100 Subject: [PATCH 10/28] Provide workaround for erf and Legendre --- include/Cxx11Workarounds.hpp | 10 ++ src/green/GreensFunction.hpp | 2 +- src/green/SphericalDiffuse.cpp | 5 +- src/green/dielectric_profile/OneLayerErf.hpp | 4 +- src/utils/CMakeLists.txt | 6 +- src/utils/Legendre.hpp | 83 +++++++++++++ src/utils/legendre.h | 124 ------------------- tests/dielectric_profile/one_layer.cpp | 5 +- tests/green/AnalyticEvaluate.hpp | 28 +++-- 9 files changed, 122 insertions(+), 145 deletions(-) create mode 100644 src/utils/Legendre.hpp delete mode 100644 src/utils/legendre.h diff --git a/include/Cxx11Workarounds.hpp b/include/Cxx11Workarounds.hpp index f9eea4a6d..beb1ddfcb 100644 --- a/include/Cxx11Workarounds.hpp +++ b/include/Cxx11Workarounds.hpp @@ -70,6 +70,11 @@ using std::array; namespace pcm { using std::to_string; } /* end namespace pcm */ +/* workarounds */ +#include +namespace pcm { +using std::erf; +} /* end namespace pcm */ #else /* HAS_CXX11*/ /* Smart pointers workarounds */ #include @@ -110,6 +115,11 @@ namespace pcm { template std::string to_string(const Source & arg) { return boost::lexical_cast(arg); } +/* workarounds */ +#include +namespace pcm { +using boost::math::erf; +} /* end namespace pcm */ } /* end namespace pcm */ #endif /* HAS_CXX11 */ diff --git a/src/green/GreensFunction.hpp b/src/green/GreensFunction.hpp index 24c199bca..76e494f8a 100644 --- a/src/green/GreensFunction.hpp +++ b/src/green/GreensFunction.hpp @@ -89,7 +89,7 @@ class GreensFunction : public IGreensFunction { */ virtual double derivativeProbe(const Eigen::Vector3d & normal_p2, const Eigen::Vector3d & p1, - const Eigen::Vector3d & p2) const { + const Eigen::Vector3d & p2) const __final { DerivativeTraits t1[3], t2[3]; t1[0] = p1(0); t1[1] = p1(1); diff --git a/src/green/SphericalDiffuse.cpp b/src/green/SphericalDiffuse.cpp index edb80533f..6b13b95f8 100644 --- a/src/green/SphericalDiffuse.cpp +++ b/src/green/SphericalDiffuse.cpp @@ -31,13 +31,12 @@ // Has to be included here #include "InterfacesImpl.hpp" -// Boost.Math includes -#include #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" #include "dielectric_profile/ProfileTypes.hpp" +#include "utils/Legendre.hpp" #include "utils/MathUtils.hpp" namespace pcm { @@ -346,7 +345,7 @@ double SphericalDiffuse::imagePotentialComponent_impl( cos_gamma = 1.0; if (utils::numericalZero(cos_gamma + 1)) cos_gamma = -1.0; - double pl_x = boost::math::legendre_p(L, cos_gamma); + double pl_x = Legendre::Pn(L, cos_gamma); /* Sample zeta_[L] */ double zeta1 = 0.0, zeta2 = 0.0, d_zeta2 = 0.0; diff --git a/src/green/dielectric_profile/OneLayerErf.hpp b/src/green/dielectric_profile/OneLayerErf.hpp index 2d155776b..0daae6b27 100644 --- a/src/green/dielectric_profile/OneLayerErf.hpp +++ b/src/green/dielectric_profile/OneLayerErf.hpp @@ -28,8 +28,6 @@ #include "Config.hpp" -#include - /*! \file OneLayerErf.hpp */ namespace pcm { @@ -57,7 +55,7 @@ class OneLayerErf { double value(double point) const { double epsPlus = (epsilon1_ + epsilon2_) / 2.0; double epsMinus = (epsilon2_ - epsilon1_) / 2.0; - double val = boost::math::erf((point - center_) / width_); + double val = pcm::erf((point - center_) / width_); return (epsPlus + epsMinus * val); // epsilon(r) } /*! Returns value of derivative of dielectric profile at given point diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index d4c78bf9a..f50fce611 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,8 +1,8 @@ # List of headers list(APPEND headers_list Atom.hpp ChargeDistribution.hpp Factory.hpp - Logger.hpp LoggerImpl.hpp MathUtils.hpp Molecule.hpp - QuadratureRules.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp Stencils.hpp - Symmetry.hpp Timer.hpp cnpy.hpp) + Legendre.hpp Logger.hpp LoggerImpl.hpp MathUtils.hpp Molecule.hpp + QuadratureRules.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp + Stencils.hpp Symmetry.hpp Timer.hpp cnpy.hpp) set_source_files_properties(cnpy.hpp PROPERTIES COMPILE_FLAGS -w) # List of sources diff --git a/src/utils/Legendre.hpp b/src/utils/Legendre.hpp new file mode 100644 index 000000000..2ecc05d5d --- /dev/null +++ b/src/utils/Legendre.hpp @@ -0,0 +1,83 @@ +//================================================================== +/** + * legendre.h -- C++ functions to evaluate Legendre polynomials + * + * Copyright (C) 2014 by James A. Chappell + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * condition: + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ +//================================================================= +/* + * legendre.h: Version 0.02 + * Created by James A. Chappell + * http://www.storage-b.com/math-numerical-analysis/18 + * Created 29 September 2005 + * + * History: + * 29-sep-2005 created + * 14-nov-2014 templates + */ +//============== + +#pragma once + +/* + * Function calculates Legendre Polynomials Pn(x) + */ + +namespace Legendre { +// n = 0 +template inline T P0(const T & /* x */) { return static_cast(1.0); } + +// n = 1 +template inline T P1(const T & x) { return x; } + +// n = 2 +template inline T P2(const T & x) { + return ((static_cast(3.0) * x * x) - static_cast(1.0)) * static_cast(0.5); +} + +/* + * Pn(x) + */ +template inline T Pn(unsigned int n, const T & x) { + if (n == 0) { + return P0(x); + } else if (n == 1) { + return P1(x); + } else if (n == 2) { + return P2(x); + } + + T pnm1(P2(x)); + T pnm2(P1(x)); + T pn(pnm1); + + for (unsigned int l = 3; l <= n; l++) { + pn = (((static_cast(2.0) * static_cast(l)) - static_cast(1.0)) * x * + pnm1 - + ((static_cast(l) - static_cast(1.0)) * pnm2)) / + static_cast(l); + pnm2 = pnm1; + pnm1 = pn; + } + + return pn; +} +} diff --git a/src/utils/legendre.h b/src/utils/legendre.h deleted file mode 100644 index 2d146f7ce..000000000 --- a/src/utils/legendre.h +++ /dev/null @@ -1,124 +0,0 @@ -//================================================================== -/** - * legendre.h -- C++ functions to evaluate Legendre polynomials - * - * Copyright (C) 2014 by James A. Chappell - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * condition: - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ -//================================================================= -/* - * legendre.h: Version 0.02 - * Created by James A. Chappell - * http://www.storage-b.com/math-numerical-analysis/18 - * Created 29 September 2005 - * - * History: - * 29-sep-2005 created - * 14-nov-2014 templates - */ -//============== - -#ifndef __LEGENDRE_H__ -#define __LEGENDRE_H__ -/* - * Function calculates Legendre Polynomials Pn(x) - */ - -namespace Legendre -{ - // n = 0 - template - inline T P0(const T & /* x */) - { - return static_cast(1.0) ; - } - - // n = 1 - template - inline T P1(const T & x) - { - return x ; - } - - // n = 2 - template - inline T P2(const T & x) - { - return ((static_cast(3.0) * x*x) - static_cast(1.0)) * - static_cast(0.5) ; - } - -/* - * Pn(x) - */ - template - inline T Pn(unsigned int n, const T & x) - { - if (n == 0) - { - return P0(x) ; - } - else if (n == 1) - { - return P1(x) ; - } - else if (n == 2) - { - return P2(x) ; - } -/* - if (x == static_cast(1.0)) - { - return static_cast(1.0) ; - } - - if (x == static_cast(-1.0)) - { - return ((n % 2 == 0) ? static_cast(1.0) : static_cast(-1.0)) ; - } - - if ((x == static_cast(0.0)) && (n % 2)) - { - return static_cast(0.0) ; - } - */ - -/* We could simply do this: - return (double(((2 * n) - 1)) * x * Pn(n - 1, x) - - (double(n - 1)) * Pn(n - 2, x)) / (double)n ; - but it could be slow for large n */ - - T pnm1(P2(x)) ; - T pnm2(P1(x)) ; - T pn(pnm1) ; - - for (unsigned int l = 3 ; l <= n ; l++) - { - pn = (((static_cast(2.0) * static_cast(l)) - static_cast(1.0)) - * x * pnm1 - ((static_cast(l) - static_cast(1.0)) * pnm2)) - / static_cast(l) ; - pnm2 = pnm1; - pnm1 = pn; - } - - return pn ; - } -} -#endif // __LEGENDRE_H__ diff --git a/tests/dielectric_profile/one_layer.cpp b/tests/dielectric_profile/one_layer.cpp index 47fed3b0a..6008ab95f 100644 --- a/tests/dielectric_profile/one_layer.cpp +++ b/tests/dielectric_profile/one_layer.cpp @@ -28,8 +28,9 @@ #include #include +#include "Config.hpp" + #include -#include #include "green/dielectric_profile/OneLayerErf.hpp" #include "green/dielectric_profile/OneLayerTanh.hpp" @@ -114,7 +115,7 @@ double erf_value(double point, double e1, double e2, double w, double c) { w /= 6.0; double epsPlus = (e1 + e2) / 2.0; double epsMinus = (e2 - e1) / 2.0; - double val = boost::math::erf((point - c) / w); + double val = pcm::erf((point - c) / w); return (epsPlus + epsMinus * val); } double erf_deriv(double point, double e1, double e2, double w, double c) { diff --git a/tests/green/AnalyticEvaluate.hpp b/tests/green/AnalyticEvaluate.hpp index b9acff9cf..06d1ac926 100644 --- a/tests/green/AnalyticEvaluate.hpp +++ b/tests/green/AnalyticEvaluate.hpp @@ -28,10 +28,9 @@ #include -// Boost.Math includes -#include - +#include "utils/Legendre.hpp" #include "utils/MathUtils.hpp" +#include "utils/Stencils.hpp" /*! \brief Analytic evaluation of vacuum Green's function and its derivatives * @@ -304,7 +303,7 @@ inline double imagePotential(double eps, for (int l = 1; l <= 200; ++l) { f_l = f_l * radius * f_0; double C_0_l = (eps - epsSolv) * l / ((eps + epsSolv) * l + epsSolv); - double pl_x = boost::math::legendre_p(l, cos_gamma); + double pl_x = Legendre::Pn(l, cos_gamma); G_img += f_l * (C_0_l - factor) * pl_x; } @@ -351,8 +350,8 @@ inline double derivativeImagePotential(double eps, pp_origin_norm_l_3 *= pp_origin_norm; pp_origin_norm_l_1 *= pp_origin_norm; - double pl_x = boost::math::legendre_p(l, cos_gamma); // P_l(cos_gamma) - double pl_1_x = boost::math::legendre_p(l+1, cos_gamma); // P_(l+1)(cos_gamma) + double pl_x = Legendre::Pn(l, cos_gamma); // P_l(cos_gamma) + double pl_1_x = Legendre::Pn(l+1, cos_gamma); // P_(l+1)(cos_gamma) double cos_denom = std::pow(cos_gamma, 2) - 1; double tmp_a = ((l+1) * pl_x * pp_origin.dot(ppNormal)) / pp_origin_norm_l_3; @@ -376,6 +375,8 @@ inline double derivativeImagePotential(double eps, /*! \brief Analytic evaluation of spherical sharp Green's function and its * derivatives * Derivation details in J. Chem. Phys. 139, 0224105 (2013) + * TODO Now using a 7-point stencil for the derivatives. Should double-check formula + * given in paper and code that up. */ inline Eigen::Array4d analyticSphericalSharp(double eps, double epsSolv, @@ -393,12 +394,21 @@ inline Eigen::Array4d analyticSphericalSharp(double eps, // Value of the function result(0) = 1.0 / (epsSolv * distance) - G_img; - double d_probe_G_img = - derivativeImagePotential(eps, epsSolv, radius, origin, sp, ppNormal, pp); + double d_probe_G_img = sevenPointStencil( + pcm::bind(imagePotential, eps, epsSolv, radius, origin, pcm::_1, pcm::_2), + pp, + sp, + ppNormal, + 1.0e-04); // Value of the directional derivative wrt probe result(1) = (sp - pp).dot(ppNormal) / (epsSolv * distance_3) - d_probe_G_img; - double d_source_G_img = 0.0; + double d_source_G_img = sevenPointStencil( + pcm::bind(imagePotential, eps, epsSolv, radius, origin, pcm::_1, pcm::_2), + sp, + pp, + spNormal, + 1.0e-04); // Directional derivative wrt source result(2) = -(sp - pp).dot(spNormal) / (epsSolv * distance_3) - d_source_G_img; // Value of the Hessian From d35da04521426fca0853d1a9138d91b81823a0a8 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 18:54:43 +0100 Subject: [PATCH 11/28] Update .gitattributes --- src/utils/Legendre.hpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/utils/Legendre.hpp b/src/utils/Legendre.hpp index 2ecc05d5d..a3296a9dc 100644 --- a/src/utils/Legendre.hpp +++ b/src/utils/Legendre.hpp @@ -1,3 +1,26 @@ +/** + * PCMSolver, an API for the Polarizable Continuum Model + * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. + * + * This file is part of PCMSolver. + * + * PCMSolver is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * PCMSolver is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with PCMSolver. If not, see . + * + * For information on the complete list of contributors to the + * PCMSolver API, see: + */ + //================================================================== /** * legendre.h -- C++ functions to evaluate Legendre polynomials From 3f8c0f7453e8fd43a971066630ba3743914cff9e Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 18:54:43 +0100 Subject: [PATCH 12/28] Update .gitattributes --- .gitattributes | 2 +- src/utils/Legendre.hpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitattributes b/.gitattributes index c3de12cbe..646fabd51 100644 --- a/.gitattributes +++ b/.gitattributes @@ -49,7 +49,7 @@ src/utils/*.hpp licensefile=.githooks/LICENSE-C++ src/utils/*.cpp licensefile=.githooks/LICENSE-C++ src/utils/cnpy.hpp !licensefile src/utils/cnpy.cpp !licensefile -src/utils/legendre.h !licensefile +src/utils/Legendre.hpp !licensefile # tests tests/unit_tests.cpp licensefile=.githooks/LICENSE-C++ diff --git a/src/utils/Legendre.hpp b/src/utils/Legendre.hpp index a3296a9dc..d47a6b9da 100644 --- a/src/utils/Legendre.hpp +++ b/src/utils/Legendre.hpp @@ -22,8 +22,8 @@ */ //================================================================== -/** - * legendre.h -- C++ functions to evaluate Legendre polynomials +/* + * Legendre.hpp -- C++ functions to evaluate Legendre polynomials * * Copyright (C) 2014 by James A. Chappell * From aa90cdff0fe573696fc71f1c25aab3a4bd435998 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 19:00:47 +0100 Subject: [PATCH 13/28] Use std::map instead of flat_map --- src/utils/Timer.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/Timer.hpp b/src/utils/Timer.hpp index 186403138..480d051c7 100644 --- a/src/utils/Timer.hpp +++ b/src/utils/Timer.hpp @@ -24,17 +24,17 @@ #pragma once #include +#include #include #include #include "Cxx11Workarounds.hpp" -#include #include namespace timer { typedef pcm::tuple timing; -typedef boost::container::flat_map TimingsMap; +typedef std::map TimingsMap; typedef std::pair TimingsPair; timing get_timing(); From 53b4800e3dbfae0cbae569d93a4ec8edbcf81244 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 19:16:53 +0100 Subject: [PATCH 14/28] Implement BOOST_FOREACH loops in C++11 --- src/green/InterfacesImpl.hpp | 14 ++++++++++---- src/interface/Meddle.cpp | 10 ++++++++-- src/utils/Timer.hpp | 6 ++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/green/InterfacesImpl.hpp b/src/green/InterfacesImpl.hpp index 2e770d296..b8d50d9b5 100644 --- a/src/green/InterfacesImpl.hpp +++ b/src/green/InterfacesImpl.hpp @@ -30,8 +30,10 @@ #include "Config.hpp" #include -#include +#ifndef HAS_CXX11 +#include +#endif // Boost.Odeint includes #include @@ -347,10 +349,14 @@ template class Omega __final { -parms.observer_step_, pcm::bind( &Omega::push_back, this, pcm::_1, pcm::_2)); - // Reverse order of StateVariable-s in RadialSolution - // this ensures that they are in ascending order, as later expected by - // function_impl and derivative_impl +// Reverse order of StateVariable-s in RadialSolution +// this ensures that they are in ascending order, as later expected by +// function_impl and derivative_impl +#ifdef HAS_CXX11 + for (auto & comp : function_) { +#else /* HAS_CXX11 */ BOOST_FOREACH (StateVariable & comp, function_) { +#endif /* HAS_CXX11 */ std::reverse(comp.begin(), comp.end()); } } diff --git a/src/interface/Meddle.cpp b/src/interface/Meddle.cpp index 9271fea1e..973871195 100644 --- a/src/interface/Meddle.cpp +++ b/src/interface/Meddle.cpp @@ -32,7 +32,9 @@ #include +#ifndef HAS_CXX11 #include +#endif #include "bi_operators/BIOperatorData.hpp" #include "bi_operators/BoundaryIntegralOperator.hpp" @@ -330,8 +332,12 @@ void pcmsolver_save_surface_functions(pcmsolver_context_t * context) { } void pcm::Meddle::saveSurfaceFunctions() const { hostWriter_("\nDumping surface functions to .npy files"); - BOOST_FOREACH (SurfaceFunctionPair pair, functions_) { - cnpy::custom::npy_save(pair.first + ".npy", pair.second); +#ifdef HAS_CXX11 + for (auto sf_pair : functions_) { +#else /* HAS_CXX11 */ + BOOST_FOREACH (SurfaceFunctionPair sf_pair, functions_) { +#endif /* HAS_CXX11 */ + cnpy::custom::npy_save(sf_pair.first + ".npy", sf_pair.second); } } diff --git a/src/utils/Timer.hpp b/src/utils/Timer.hpp index 480d051c7..a1ad78ef4 100644 --- a/src/utils/Timer.hpp +++ b/src/utils/Timer.hpp @@ -30,7 +30,9 @@ #include "Cxx11Workarounds.hpp" +#ifndef HAS_CXX11 #include +#endif namespace timer { typedef pcm::tuple timing; @@ -56,7 +58,11 @@ class Timer { std::ostream & printObject(std::ostream & os) const { os << " PCMSolver API timing results " << std::endl; os << "----------------------------------------------------" << std::endl; +#ifdef HAS_CXX11 + for (auto t_pair : timings_) { +#else /* HAS_CXX11 */ BOOST_FOREACH (TimingsPair t_pair, timings_) { +#endif /* HAS_CXX11 */ os << "Checkpoint: " << t_pair.first << std::endl; os << " Wall time: " << pcm::get<0>(t_pair.second) << " ms" << std::endl; os << " CPU time: " << pcm::get<1>(t_pair.second) << " ms" << std::endl; From 84e5a1572091219f80dfb8a8e59e0fdc1ed21726 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sat, 25 Nov 2017 22:00:34 +0100 Subject: [PATCH 15/28] Do not use Boost.Format --- src/cavity/GePolCavity.cpp | 55 +++++++++++++++++++++----------------- src/utils/Molecule.cpp | 9 +++---- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/src/cavity/GePolCavity.cpp b/src/cavity/GePolCavity.cpp index 8a7b31e54..7969af357 100644 --- a/src/cavity/GePolCavity.cpp +++ b/src/cavity/GePolCavity.cpp @@ -26,14 +26,16 @@ #include #include #include +#include #include #include #include #include -#include "Config.hpp" +#include +#include -#include +#include "Config.hpp" #include @@ -169,7 +171,7 @@ void GePolCavity::build(const std::string & suffix, int gen3 = molecule_.pointGroup().generators(2); std::stringstream pedra; - pedra << "PEDRA.OUT_" << suffix << "_" << ::getpid(); + pedra << "PEDRA.OUT_" << suffix << "_" << getpid(); int len_f_pedra = std::strlen(pedra.str().c_str()); // Go PEDRA, Go! TIMER_ON("GePolCavity::generatecavity_cpp"); @@ -342,7 +344,7 @@ void GePolCavity::build(const std::string & suffix, void GePolCavity::writeOFF(const std::string & suffix) { std::stringstream off; - off << "cavity.off_" << suffix << "_" << ::getpid(); + off << "cavity.off_" << suffix << "_" << getpid(); std::ofstream fout; fout.open(off.str().c_str()); @@ -359,23 +361,26 @@ void GePolCavity::writeOFF(const std::string & suffix) { Eigen::MatrixXi ivts = Eigen::MatrixXi::Zero(nElements_, 10); for (PCMSolverIndex i = 0; i < nElements_; ++i) { if (i == 0) - fout << boost::format("# Sphere number %i\n") % elements_[i].iSphere(); + fout << "# Sphere number " << elements_[i].iSphere() << std::endl; c1 = 1.0; c2 = 1.0; c3 = 1.0; for (int j = 0; j < elements_[i].nVertices(); ++j) { ivts(i, j) = k; k = k + 1; - fout << boost::format("%20.14f\t%20.14f\t%20.14f\t%1.3f\t%1.3f\t%1.3f\t%1.3f " - " # Tess %i\n") % - elements_[i].vertices()(0, j) % elements_[i].vertices()(1, j) % - elements_[i].vertices()(2, j) % c1 % c2 % c3 % 0.75 % (i + 1); + fout << std::fixed << std::left << std::setfill('0') << std::setprecision(14) + << elements_[i].vertices()(0, j) << " " + << elements_[i].vertices()(1, j) << " " + << elements_[i].vertices()(2, j) << " " << std::fixed << std::left + << std::setfill('0') << std::setprecision(4) << c1 << " " << c2 + << " " << c3 << " " << 0.75 << " " + << " # Tess " << (i + 1) << std::endl; } } for (PCMSolverIndex i = 0; i < nElements_; ++i) { - fout << boost::format("%i ") % elements_[i].nVertices(); + fout << elements_[i].nVertices() << " "; for (int j = 0; j < elements_[i].nVertices(); ++j) { - fout << boost::format("%i ") % ivts(i, j); + fout << ivts(i, j) << " "; } fout << std::endl; } @@ -399,26 +404,26 @@ std::ostream & GePolCavity::printCavity(std::ostream & os) { os << "-------- ---- -------- ------- ----------- ----------- -----------\n"; // Print original set of spheres int original = nSpheres_ - addedSpheres; + Eigen::IOFormat CleanFmt(6, Eigen::DontAlignCols, " ", "\n", "", ""); for (int i = 0; i < original; ++i) { - os << boost::format("%4i") % (i + 1); - os << boost::format(" %s") % molecule_.atoms()[i].symbol; - os << boost::format("%10.4f") % (molecule_.atoms()[i].radius); - os << boost::format(" %1.2f ") % (molecule_.atoms()[i].radiusScaling); - os << boost::format("%10.6f ") % (molecule_.geometry(0, i) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (molecule_.geometry(1, i) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (molecule_.geometry(2, i) * bohrToAngstrom()); + os << std::setw(4) << i + 1; + os << " " << molecule_.atoms()[i].symbol << " "; + os << std::fixed << std::setprecision(4) << molecule_.atoms()[i].radius; + os << std::fixed << std::setprecision(2) << " " + << molecule_.atoms()[i].radiusScaling << " "; + os << (molecule_.geometry().col(i).transpose() * bohrToAngstrom()) + .format(CleanFmt); os << std::endl; } // Print added spheres for (int j = 0; j < addedSpheres; ++j) { int idx = original + j; - os << boost::format("%4i") % (idx + 1); - os << boost::format(" %s") % "Du"; - os << boost::format("%9.4f") % (sphereRadius_(idx) * bohrToAngstrom()); - os << boost::format(" %1.2f ") % 1.00; - os << boost::format("%10.6f ") % (sphereCenter_(0, idx) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (sphereCenter_(1, idx) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (sphereCenter_(2, idx) * bohrToAngstrom()); + os << std::setw(4) << idx + 1; + os << " Du "; + os << std::fixed << std::setprecision(4) + << sphereRadius_(idx) * bohrToAngstrom(); + os << std::fixed << std::setprecision(2) << " 1.00"; + os << (sphereCenter_.col(idx).transpose() * bohrToAngstrom()).format(CleanFmt); os << std::endl; } return os; diff --git a/src/utils/Molecule.cpp b/src/utils/Molecule.cpp index 240bfe259..c10631ce4 100644 --- a/src/utils/Molecule.cpp +++ b/src/utils/Molecule.cpp @@ -32,8 +32,6 @@ #include "Config.hpp" -#include - #include #include @@ -255,14 +253,13 @@ Molecule & Molecule::operator=(const Molecule & other) { std::ostream & operator<<(std::ostream & os, const Molecule & m) { if (m.nAtoms_ != 0) { + Eigen::IOFormat CleanFmt(6, Eigen::DontAlignCols, " ", "\n", "", ""); os << " Geometry (in Angstrom)" << std::endl; os << " Center X Y Z \n"; os << "------------ ------------ ------------ ------------\n"; for (size_t i = 0; i < m.nAtoms_; ++i) { - os << boost::format("%|=12s|") % m.atoms_[i].symbol; - os << boost::format(" %10.6f ") % (m.geometry_(0, i) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (m.geometry_(1, i) * bohrToAngstrom()); - os << boost::format(" %10.6f ") % (m.geometry_(2, i) * bohrToAngstrom()); + os << std::setw(12) << m.atoms_[i].symbol; + os << (m.geometry_.col(i).transpose() * bohrToAngstrom()).format(CleanFmt); os << std::endl; } os << "Rotor type: " << rotorTypeList[m.rotor_]; From 9a763211f5fcb9ba1b1b030220fe81ba031252e6 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sun, 26 Nov 2017 18:47:54 -0500 Subject: [PATCH 16/28] Update Catch to v1.1.10 --- .ci/ci_build.sh | 2 +- .travis.yml | 10 +- external/Catch/catch.hpp | 2182 ++++++++++++++++++++++++-------------- 3 files changed, 1365 insertions(+), 829 deletions(-) diff --git a/.ci/ci_build.sh b/.ci/ci_build.sh index 1f5e9f777..2aaf3eeb9 100755 --- a/.ci/ci_build.sh +++ b/.ci/ci_build.sh @@ -2,7 +2,7 @@ # The return code will capture an error from ANY of the functions in the pipe set -euo pipefail -cmake --build . -- --jobs=2 VERBOSE=1 | tee build.log | grep "Building" +cmake --build . -- VERBOSE=1 | tee build.log | grep "Building" RESULT=$? if [ $RESULT -eq 0 ]; then diff --git a/.travis.yml b/.travis.yml index 9b20032df..50323c905 100644 --- a/.travis.yml +++ b/.travis.yml @@ -70,12 +70,12 @@ matrix: - os: osx osx_image: xcode7.3 env: - - CXX_COMPILER='g++-6' - - C_COMPILER='gcc-6' - - Fortran_COMPILER='gfortran-6' + - CXX_COMPILER='g++-7' + - C_COMPILER='gcc-7' + - Fortran_COMPILER='gfortran-7' - BUILD_TYPE='release' - PYTHON='python3' - - HOMEBREW_GCC='gcc@6' + - HOMEBREW_GCC='gcc@7' - RUN_DANGER=false - os: linux @@ -107,7 +107,7 @@ install: - | if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then brew update - brew install ${HOMEBREW_GCC} ${PYTHON} boost ccache cmake + brew install ${HOMEBREW_GCC} ${PYTHON} boost ccache cmake zlib pip install virtualenv --upgrade export PATH="/usr/local/opt/ccache/libexec:$PATH" else diff --git a/external/Catch/catch.hpp b/external/Catch/catch.hpp index 2a09fd193..849c53c13 100644 --- a/external/Catch/catch.hpp +++ b/external/Catch/catch.hpp @@ -1,6 +1,6 @@ /* - * Catch v1.7.2 - * Generated: 2017-02-13 15:57:33.350226 + * Catch v1.11.0 + * Generated: 2017-10-31 13:42:42.914833 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. @@ -40,6 +40,8 @@ #elif defined __GNUC__ # pragma GCC diagnostic ignored "-Wvariadic-macros" # pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wparentheses" + # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpadded" #endif @@ -82,6 +84,7 @@ // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too @@ -117,11 +120,46 @@ # endif # if defined(CATCH_CPP11_OR_GREATER) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) +# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ + _Pragma( "clang diagnostic pop" ) + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic pop" ) # endif #endif // __clang__ +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) + +# if !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# endif + +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE + +#endif // __CYGWIN__ + //////////////////////////////////////////////////////////////////////////////// // Borland #ifdef __BORLANDC__ @@ -148,10 +186,6 @@ # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif -# if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_CPP11_OR_GREATER) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" ) -# endif - // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below @@ -191,10 +225,15 @@ // Use __COUNTER__ if the compiler supports it #if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \ - ( defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3 ) || \ + ( defined __GNUC__ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3 )) ) || \ ( defined __clang__ && __clang_major__ >= 3 ) -#define CATCH_INTERNAL_CONFIG_COUNTER +// Use of __COUNTER__ is suppressed during code analysis in CLion/AppCode 2017.2.x and former, +// because __COUNTER__ is not properly handled by it. +// This does not affect compilation +#if ( !defined __JETBRAINS_IDE__ || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif #endif @@ -275,10 +314,7 @@ #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_UNIQUE_PTR #endif -// Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for -// analytics) because, at time of writing, __COUNTER__ is not properly handled by it. -// This does not affect compilation -#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__) +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11) @@ -290,9 +326,18 @@ #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) # define CATCH_CONFIG_WINDOWS_SEH #endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS #endif // noexcept support: @@ -376,14 +421,14 @@ namespace Catch { }; template - inline void deleteAll( ContainerT& container ) { + void deleteAll( ContainerT& container ) { typename ContainerT::const_iterator it = container.begin(); typename ContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete *it; } template - inline void deleteAllValues( AssociativeContainerT& container ) { + void deleteAllValues( AssociativeContainerT& container ) { typename AssociativeContainerT::const_iterator it = container.begin(); typename AssociativeContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) @@ -463,7 +508,6 @@ namespace Catch { { public: NotImplementedException( SourceLineInfo const& lineInfo ); - NotImplementedException( NotImplementedException const& ) {} virtual ~NotImplementedException() CATCH_NOEXCEPT {} @@ -732,59 +776,76 @@ void registerTestCaseFunction /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ namespace{ \ struct TestName : ClassName{ \ void test(); \ }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); /* NOLINT */ \ } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ - Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS #else /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \ static void TestName(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ static void TestName() #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\ + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ namespace{ \ struct TestCaseName : ClassName{ \ void test(); \ }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); /* NOLINT */ \ } \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ void TestCaseName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ - Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); + CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ + Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + #endif // #included from: internal/catch_capture.hpp @@ -871,20 +932,25 @@ namespace Catch { template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& ); + + private: + DecomposedExpression& operator = (DecomposedExpression const&); }; struct AssertionInfo { - AssertionInfo() {} - AssertionInfo( std::string const& _macroName, + AssertionInfo(); + AssertionInfo( char const * _macroName, SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ); + char const * _capturedExpression, + ResultDisposition::Flags _resultDisposition, + char const * _secondArg = ""); - std::string macroName; + char const * macroName; SourceLineInfo lineInfo; - std::string capturedExpression; + char const * capturedExpression; ResultDisposition::Flags resultDisposition; + char const * secondArg; }; struct AssertionResultData @@ -967,313 +1033,161 @@ namespace Catch { namespace Matchers { namespace Impl { - namespace Generic { - template class AllOf; - template class AnyOf; - template class Not; - } - - template - struct Matcher : SharedImpl - { - typedef ExpressionT ExpressionType; - - virtual ~Matcher() {} - virtual Ptr clone() const = 0; - virtual bool match( ExpressionT const& expr ) const = 0; - virtual std::string toString() const = 0; - - Generic::AllOf operator && ( Matcher const& other ) const; - Generic::AnyOf operator || ( Matcher const& other ) const; - Generic::Not operator ! () const; - }; - - template - struct MatcherImpl : Matcher { - - virtual Ptr > clone() const { - return Ptr >( new DerivedT( static_cast( *this ) ) ); - } - }; + template struct MatchAllOf; + template struct MatchAnyOf; + template struct MatchNotOf; - namespace Generic { - template - class Not : public MatcherImpl, ExpressionT> { + class MatcherUntypedBase { public: - explicit Not( Matcher const& matcher ) : m_matcher(matcher.clone()) {} - Not( Not const& other ) : m_matcher( other.m_matcher ) {} - - virtual bool match( ExpressionT const& expr ) const CATCH_OVERRIDE { - return !m_matcher->match( expr ); + std::string toString() const { + if( m_cachedToString.empty() ) + m_cachedToString = describe(); + return m_cachedToString; } - virtual std::string toString() const CATCH_OVERRIDE { - return "not " + m_matcher->toString(); - } + protected: + virtual ~MatcherUntypedBase(); + virtual std::string describe() const = 0; + mutable std::string m_cachedToString; private: - Ptr< Matcher > m_matcher; + MatcherUntypedBase& operator = ( MatcherUntypedBase const& ); }; - template - class AllOf : public MatcherImpl, ExpressionT> { - public: + template + struct MatcherMethod { + virtual bool match( ObjectT const& arg ) const = 0; + }; + template + struct MatcherMethod { + virtual bool match( PtrT* arg ) const = 0; + }; - AllOf() {} - AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} + template + struct MatcherBase : MatcherUntypedBase, MatcherMethod { - AllOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( !m_matchers[i]->match( expr ) ) + MatchAllOf operator && ( MatcherBase const& other ) const; + MatchAnyOf operator || ( MatcherBase const& other ) const; + MatchNotOf operator ! () const; + }; + + template + struct MatchAllOf : MatcherBase { + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if (!m_matchers[i]->match(arg)) return false; + } return true; } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; + virtual std::string describe() const CATCH_OVERRIDE { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) - oss << " and "; - oss << m_matchers[i]->toString(); + description += " and "; + description += m_matchers[i]->toString(); } - oss << " )"; - return oss.str(); + description += " )"; + return description; } - AllOf operator && ( Matcher const& other ) const { - AllOf allOfExpr( *this ); - allOfExpr.add( other ); - return allOfExpr; + MatchAllOf& operator && ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; } - private: - std::vector > > m_matchers; + std::vector const*> m_matchers; }; + template + struct MatchAnyOf : MatcherBase { - template - class AnyOf : public MatcherImpl, ExpressionT> { - public: - - AnyOf() {} - AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} - - AnyOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( m_matchers[i]->match( expr ) ) + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + for( std::size_t i = 0; i < m_matchers.size(); ++i ) { + if (m_matchers[i]->match(arg)) return true; + } return false; } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; + virtual std::string describe() const CATCH_OVERRIDE { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) - oss << " or "; - oss << m_matchers[i]->toString(); + description += " or "; + description += m_matchers[i]->toString(); } - oss << " )"; - return oss.str(); - } - - AnyOf operator || ( Matcher const& other ) const { - AnyOf anyOfExpr( *this ); - anyOfExpr.add( other ); - return anyOfExpr; + description += " )"; + return description; } - private: - std::vector > > m_matchers; - }; - - } // namespace Generic - - template - Generic::AllOf Matcher::operator && ( Matcher const& other ) const { - Generic::AllOf allOfExpr; - allOfExpr.add( *this ); - allOfExpr.add( other ); - return allOfExpr; - } - - template - Generic::AnyOf Matcher::operator || ( Matcher const& other ) const { - Generic::AnyOf anyOfExpr; - anyOfExpr.add( *this ); - anyOfExpr.add( other ); - return anyOfExpr; - } - - template - Generic::Not Matcher::operator ! () const { - return Generic::Not( *this ); - } - - namespace StdString { - - inline std::string makeString( std::string const& str ) { return str; } - inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } - - struct CasedString - { - CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) - : m_caseSensitivity( caseSensitivity ), - m_str( adjustString( str ) ) - {} - std::string adjustString( std::string const& str ) const { - return m_caseSensitivity == CaseSensitive::No - ? toLower( str ) - : str; - - } - std::string toStringSuffix() const - { - return m_caseSensitivity == CaseSensitive::No - ? " (case insensitive)" - : std::string(); - } - CaseSensitive::Choice m_caseSensitivity; - std::string m_str; - }; - - struct Equals : MatcherImpl { - Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) - : m_data( str, caseSensitivity ) - {} - Equals( Equals const& other ) : m_data( other.m_data ){} - - virtual ~Equals(); - - virtual bool match( std::string const& expr ) const { - return m_data.m_str == m_data.adjustString( expr );; - } - virtual std::string toString() const { - return "equals: \"" + m_data.m_str + '"' + m_data.toStringSuffix(); + MatchAnyOf& operator || ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; } - CasedString m_data; + std::vector const*> m_matchers; }; - struct Contains : MatcherImpl { - Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) - : m_data( substr, caseSensitivity ){} - Contains( Contains const& other ) : m_data( other.m_data ){} + template + struct MatchNotOf : MatcherBase { - virtual ~Contains(); + MatchNotOf( MatcherBase const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} - virtual bool match( std::string const& expr ) const { - return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos; - } - virtual std::string toString() const { - return "contains: \"" + m_data.m_str + '"' + m_data.toStringSuffix(); + virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { + return !m_underlyingMatcher.match( arg ); } - CasedString m_data; - }; - - struct StartsWith : MatcherImpl { - StartsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) - : m_data( substr, caseSensitivity ){} - - StartsWith( StartsWith const& other ) : m_data( other.m_data ){} - - virtual ~StartsWith(); - - virtual bool match( std::string const& expr ) const { - return startsWith( m_data.adjustString( expr ), m_data.m_str ); + virtual std::string describe() const CATCH_OVERRIDE { + return "not " + m_underlyingMatcher.toString(); } - virtual std::string toString() const { - return "starts with: \"" + m_data.m_str + '"' + m_data.toStringSuffix(); - } - - CasedString m_data; + MatcherBase const& m_underlyingMatcher; }; - struct EndsWith : MatcherImpl { - EndsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) - : m_data( substr, caseSensitivity ){} - EndsWith( EndsWith const& other ) : m_data( other.m_data ){} - - virtual ~EndsWith(); - - virtual bool match( std::string const& expr ) const { - return endsWith( m_data.adjustString( expr ), m_data.m_str ); - } - virtual std::string toString() const { - return "ends with: \"" + m_data.m_str + '"' + m_data.toStringSuffix(); - } + template + MatchAllOf MatcherBase::operator && ( MatcherBase const& other ) const { + return MatchAllOf() && *this && other; + } + template + MatchAnyOf MatcherBase::operator || ( MatcherBase const& other ) const { + return MatchAnyOf() || *this || other; + } + template + MatchNotOf MatcherBase::operator ! () const { + return MatchNotOf( *this ); + } - CasedString m_data; - }; - } // namespace StdString } // namespace Impl // The following functions create the actual matcher objects. // This allows the types to be inferred - template - inline Impl::Generic::Not Not( Impl::Matcher const& m ) { - return Impl::Generic::Not( m ); - } - - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ).add( m3 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ).add( m3 ); - } - - inline Impl::StdString::Equals Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { - return Impl::StdString::Equals( str, caseSensitivity ); - } - inline Impl::StdString::Equals Equals( const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { - return Impl::StdString::Equals( Impl::StdString::makeString( str ), caseSensitivity ); - } - inline Impl::StdString::Contains Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { - return Impl::StdString::Contains( substr, caseSensitivity ); - } - inline Impl::StdString::Contains Contains( const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { - return Impl::StdString::Contains( Impl::StdString::makeString( substr ), caseSensitivity ); + // - deprecated: prefer ||, && and ! + template + Impl::MatchNotOf Not( Impl::MatcherBase const& underlyingMatcher ) { + return Impl::MatchNotOf( underlyingMatcher ); } - inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { - return Impl::StdString::StartsWith( substr ); + template + Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { + return Impl::MatchAllOf() && m1 && m2; } - inline Impl::StdString::StartsWith StartsWith( const char* substr ) { - return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); + template + Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { + return Impl::MatchAllOf() && m1 && m2 && m3; } - inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { - return Impl::StdString::EndsWith( substr ); + template + Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { + return Impl::MatchAnyOf() || m1 || m2; } - inline Impl::StdString::EndsWith EndsWith( const char* substr ) { - return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); + template + Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { + return Impl::MatchAnyOf() || m1 || m2 || m3; } } // namespace Matchers using namespace Matchers; +using Matchers::Impl::MatcherBase; } // namespace Catch @@ -1303,6 +1217,7 @@ namespace Catch { char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg = "" ); + ~ResultBuilder(); template ExpressionLhs operator <= ( T const& operand ); @@ -1310,7 +1225,7 @@ namespace Catch { template ResultBuilder& operator << ( T const& value ) { - m_stream.oss << value; + stream().oss << value; return *this; } @@ -1328,7 +1243,7 @@ namespace Catch { void captureResult( ResultWas::OfType resultType ); void captureExpression(); void captureExpectedException( std::string const& expectedMessage ); - void captureExpectedException( Matchers::Impl::Matcher const& matcher ); + void captureExpectedException( Matchers::Impl::MatcherBase const& matcher ); void handleResult( AssertionResult const& result ); void react(); bool shouldDebugBreak() const; @@ -1337,13 +1252,33 @@ namespace Catch { template void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString ); + void setExceptionGuard(); + void unsetExceptionGuard(); + private: AssertionInfo m_assertionInfo; AssertionResultData m_data; - CopyableStream m_stream; + + CopyableStream &stream() + { + if(!m_usedStream) + { + m_usedStream = true; + m_stream().oss.str(""); + } + return m_stream(); + } + + static CopyableStream &m_stream() + { + static CopyableStream s; + return s; + } bool m_shouldDebugBreak; bool m_shouldThrow; + bool m_guardException; + bool m_usedStream; }; } // namespace Catch @@ -1358,6 +1293,8 @@ namespace Catch { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch +#pragma warning(disable:4018) // more "signed/unsigned mismatch" +#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) #endif #include @@ -1383,176 +1320,103 @@ namespace Internal { template<> struct OperatorTraits{ static const char* getName(){ return ">="; } }; template - inline T& opCast(T const& t) { return const_cast(t); } - -// nullptr_t support based on pull request #154 from Konstantin Baumann + T& removeConst(T const &t) { return const_cast(t); } #ifdef CATCH_CONFIG_CPP11_NULLPTR - inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } -#endif // CATCH_CONFIG_CPP11_NULLPTR + inline std::nullptr_t removeConst(std::nullptr_t) { return nullptr; } +#endif // So the compare overloads can be operator agnostic we convey the operator as a template // enum, which is used to specialise an Evaluator for doing the comparison. template - class Evaluator{}; + struct Evaluator{}; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs) { - return bool( opCast( lhs ) == opCast( rhs ) ); + return bool(removeConst(lhs) == removeConst(rhs) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) != opCast( rhs ) ); + return bool(removeConst(lhs) != removeConst(rhs) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) < opCast( rhs ) ); + return bool(removeConst(lhs) < removeConst(rhs) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) > opCast( rhs ) ); + return bool(removeConst(lhs) > removeConst(rhs) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) >= opCast( rhs ) ); + return bool(removeConst(lhs) >= removeConst(rhs) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) <= opCast( rhs ) ); + return bool(removeConst(lhs) <= removeConst(rhs) ); } }; - template - bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // This level of indirection allows us to specialise for integer types - // to avoid signed/ unsigned warnings - - // "base" overload - template - bool compare( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // unsigned X to int - template bool compare( unsigned int lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // unsigned X to long - template bool compare( unsigned int lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // int to unsigned X - template bool compare( int lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // long to unsigned X - template bool compare( long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long (when comparing against NULL) - template bool compare( long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - - // pointer to int (when comparing against NULL) - template bool compare( int lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, int rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - -#ifdef CATCH_CONFIG_CPP11_LONG_LONG - // long long to unsigned X - template bool compare( long long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned long long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // unsigned long long to X - template bool compare( unsigned long long lhs, int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, long long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long long (when comparing against NULL) - template bool compare( long long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } -#endif // CATCH_CONFIG_CPP11_LONG_LONG + // Special case for comparing a pointer to an int (deduced for p==0) + template + struct Evaluator { + static bool evaluate( int lhs, T* rhs) { + return reinterpret_cast( lhs ) == rhs; + } + }; + template + struct Evaluator { + static bool evaluate( T* lhs, int rhs) { + return lhs == reinterpret_cast( rhs ); + } + }; + template + struct Evaluator { + static bool evaluate( int lhs, T* rhs) { + return reinterpret_cast( lhs ) != rhs; + } + }; + template + struct Evaluator { + static bool evaluate( T* lhs, int rhs) { + return lhs != reinterpret_cast( rhs ); + } + }; -#ifdef CATCH_CONFIG_CPP11_NULLPTR - // pointer to nullptr_t (when comparing against nullptr) - template bool compare( std::nullptr_t, T* rhs ) { - return Evaluator::evaluate( nullptr, rhs ); - } - template bool compare( T* lhs, std::nullptr_t ) { - return Evaluator::evaluate( lhs, nullptr ); - } -#endif // CATCH_CONFIG_CPP11_NULLPTR + template + struct Evaluator { + static bool evaluate( long lhs, T* rhs) { + return reinterpret_cast( lhs ) == rhs; + } + }; + template + struct Evaluator { + static bool evaluate( T* lhs, long rhs) { + return lhs == reinterpret_cast( rhs ); + } + }; + template + struct Evaluator { + static bool evaluate( long lhs, T* rhs) { + return reinterpret_cast( lhs ) != rhs; + } + }; + template + struct Evaluator { + static bool evaluate( T* lhs, long rhs) { + return lhs != reinterpret_cast( rhs ); + } + }; } // end of namespace Internal } // end of namespace Catch @@ -1659,7 +1523,7 @@ std::string toString( std::nullptr_t ); #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ); - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); + std::string toString( NSString * CATCH_ARC_STRONG & nsstring ); std::string toString( NSObject* const& nsObject ); #endif @@ -1667,6 +1531,7 @@ namespace Detail { extern const std::string unprintableString; + #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK) struct BorgType { template BorgType( T const& ); }; @@ -1685,6 +1550,20 @@ namespace Detail { static T const&t; enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; }; +#else + template + class IsStreamInsertable { + template + static auto test(int) + -> decltype( std::declval() << std::declval(), std::true_type() ); + + template + static auto test(...) -> std::false_type; + + public: + static const bool value = decltype(test(0))::value; + }; +#endif #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template - inline std::string rawMemoryToString( const T& object ) { + std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } @@ -1874,6 +1753,8 @@ class ExpressionLhs : public DecomposedExpression { public: ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {} + ExpressionLhs& operator = ( const ExpressionLhs& ); + template BinaryExpression operator == ( RhsT const& rhs ) { @@ -1926,7 +1807,7 @@ class ExpressionLhs : public DecomposedExpression { } virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { - dest = Catch::toString( m_truthy ); + dest = Catch::toString( m_lhs ); } private: @@ -1952,9 +1833,11 @@ class BinaryExpression : public DecomposedExpression { BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs ) : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {} + BinaryExpression& operator = ( BinaryExpression& ); + void endExpression() const { m_rb - .setResultType( Internal::compare( m_lhs, m_rhs ) ) + .setResultType( Internal::Evaluator::evaluate( m_lhs, m_rhs ) ) .endExpression( *this ); } @@ -2018,7 +1901,7 @@ class MatchExpression : public DecomposedExpression { namespace Catch { template - inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { + ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { return ExpressionLhs( *this, operand ); } @@ -2027,7 +1910,7 @@ namespace Catch { } template - inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher, + void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString ) { MatchExpression expr( arg, matcher, matcherString ); setResultType( matcher.match( arg ) ); @@ -2123,7 +2006,13 @@ namespace Catch { virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; + virtual void exceptionEarlyReported() = 0; + virtual void handleFatalErrorCondition( std::string const& message ) = 0; + + virtual bool lastAssertionPassed() = 0; + virtual void assertionPassed() = 0; + virtual void assertionRun() = 0; }; IResultCapture& getResultCapture(); @@ -2166,9 +2055,9 @@ namespace Catch{ #if defined(__ppc64__) || defined(__ppc__) #define CATCH_TRAP() \ __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ - : : : "memory","r0","r3","r4" ) + : : : "memory","r0","r3","r4" ) /* NOLINT */ #else - #define CATCH_TRAP() __asm__("int $3\n" : : ) + #define CATCH_TRAP() __asm__("int $3\n" : : /* NOLINT */ ) #endif #elif defined(CATCH_PLATFORM_LINUX) @@ -2176,7 +2065,7 @@ namespace Catch{ // directly at the location of the failing check instead of breaking inside // raise() called from it, i.e. one stack frame below. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) - #define CATCH_TRAP() asm volatile ("int $3") + #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ #else // Fall back to the generic way. #include @@ -2207,45 +2096,47 @@ namespace Catch { }; } -// #included from: catch_type_traits.hpp -#define TWOBLUECUBES_CATCH_TYPE_TRAITS_HPP_INCLUDED - -#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) -#include +#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) +# define CATCH_INTERNAL_STRINGIFY(expr) #expr +#else +# define CATCH_INTERNAL_STRINGIFY(expr) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" #endif -namespace Catch { - -#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) +#if defined(CATCH_CONFIG_FAST_COMPILE) +/////////////////////////////////////////////////////////////////////////////// +// We can speedup compilation significantly by breaking into debugger lower in +// the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER +// macro in each assertion +#define INTERNAL_CATCH_REACT( resultBuilder ) \ + resultBuilder.react(); - template - using add_lvalue_reference = std::add_lvalue_reference; +/////////////////////////////////////////////////////////////////////////////// +// Another way to speed-up compilation is to omit local try-catch for REQUIRE* +// macros. +// This can potentially cause false negative, if the test code catches +// the exception before it propagates back up to the runner. +#define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr), resultDisposition ); \ + __catchResult.setExceptionGuard(); \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + ( __catchResult <= expr ).endExpression(); \ + CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + __catchResult.unsetExceptionGuard(); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::isTrue( false && static_cast( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look +// The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. - template - using add_const = std::add_const; +#define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \ + do { \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ + __catchResult.setExceptionGuard(); \ + __catchResult.captureMatch( arg, matcher, CATCH_INTERNAL_STRINGIFY(matcher) ); \ + __catchResult.unsetExceptionGuard(); \ + INTERNAL_CATCH_REACT( __catchResult ) \ + } while( Catch::alwaysFalse() ) #else - - template - struct add_const { - typedef const T type; - }; - - template - struct add_lvalue_reference { - typedef T& type; - }; - template - struct add_lvalue_reference { - typedef T& type; - }; - // No && overload, because that is C++11, in which case we have - // proper type_traits implementation from the standard library - -#endif - -} - /////////////////////////////////////////////////////////////////////////////// // In the event of a failure works out if the debugger needs to be invoked // and/or an exception thrown and takes appropriate action. @@ -2254,14 +2145,16 @@ namespace Catch { #define INTERNAL_CATCH_REACT( resultBuilder ) \ if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ resultBuilder.react(); +#endif /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ +#define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \ do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr), resultDisposition ); \ try { \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ ( __catchResult <= expr ).endExpression(); \ + CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ @@ -2271,19 +2164,19 @@ namespace Catch { // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( Catch::getResultCapture().getLastResult()->succeeded() ) +#define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ + if( Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( !Catch::getResultCapture().getLastResult()->succeeded() ) +#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ + if( !Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ +#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \ do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr), resultDisposition ); \ try { \ static_cast(expr); \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ @@ -2295,9 +2188,9 @@ namespace Catch { } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS( expr, resultDisposition, matcher, macroName ) \ +#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \ do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr), resultDisposition, CATCH_INTERNAL_STRINGIFY(matcher) ); \ if( __catchResult.allowThrows() ) \ try { \ static_cast(expr); \ @@ -2312,15 +2205,15 @@ namespace Catch { } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ +#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ if( __catchResult.allowThrows() ) \ try { \ static_cast(expr); \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ - catch( Catch::add_const::type>::type ) { \ + catch( exceptionType ) { \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ @@ -2333,7 +2226,7 @@ namespace Catch { /////////////////////////////////////////////////////////////////////////////// #ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ + #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ @@ -2341,7 +2234,7 @@ namespace Catch { INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #else - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ + #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << log + ::Catch::StreamEndStop(); \ @@ -2351,15 +2244,15 @@ namespace Catch { #endif /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_INFO( log, macroName ) \ +#define INTERNAL_CATCH_INFO( macroName, log ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; /////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ +#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ + Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ try { \ - __catchResult.captureMatch( arg, matcher, #matcher ); \ + __catchResult.captureMatch( arg, matcher, CATCH_INTERNAL_STRINGIFY(matcher) ); \ } catch( ... ) { \ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ } \ @@ -2472,14 +2365,19 @@ namespace Catch { // #included from: catch_timer.h #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED -#ifdef CATCH_PLATFORM_WINDOWS -typedef unsigned long long uint64_t; +#ifdef _MSC_VER + +namespace Catch { + typedef unsigned long long UInt64; +} #else #include +namespace Catch { + typedef uint64_t UInt64; +} #endif namespace Catch { - class Timer { public: Timer() : m_ticks( 0 ) {} @@ -2489,7 +2387,7 @@ namespace Catch { double getElapsedSeconds() const; private: - uint64_t m_ticks; + UInt64 m_ticks; }; } // namespace Catch @@ -2528,7 +2426,6 @@ namespace Catch { // #included from: internal/catch_generators.hpp #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED -#include #include #include #include @@ -2642,7 +2539,7 @@ class CompositeGenerator { private: void move( CompositeGenerator& other ) { - std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); + m_composed.insert( m_composed.end(), other.m_composed.begin(), other.m_composed.end() ); m_totalSize += other.m_totalSize; other.m_composed.clear(); } @@ -2724,12 +2621,15 @@ namespace Catch { struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; + struct ITagAliasRegistry; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; + virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; + virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; }; @@ -2739,6 +2639,7 @@ namespace Catch { virtual void registerListener( Ptr const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; + virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; }; IRegistryHub& getRegistryHub(); @@ -2825,33 +2726,40 @@ namespace Detail { public: explicit Approx ( double value ) : m_epsilon( std::numeric_limits::epsilon()*100 ), + m_margin( 0.0 ), m_scale( 1.0 ), m_value( value ) {} - Approx( Approx const& other ) - : m_epsilon( other.m_epsilon ), - m_scale( other.m_scale ), - m_value( other.m_value ) - {} - static Approx custom() { return Approx( 0 ); } - Approx operator()( double value ) { - Approx approx( value ); +#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) + + template ::value>::type> + Approx operator()( T value ) { + Approx approx( static_cast(value) ); approx.epsilon( m_epsilon ); + approx.margin( m_margin ); approx.scale( m_scale ); return approx; } -#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) + template ::value>::type> + explicit Approx( T value ): Approx(static_cast(value)) + {} + template ::value>::type> friend bool operator == ( const T& lhs, Approx const& rhs ) { // Thanks to Richard Harris for his help refining this formula auto lhs_v = double(lhs); - return std::fabs( lhs_v - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs_v), std::fabs(rhs.m_value) ) ); + bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value))); + if (relativeOK) { + return true; + } + + return std::fabs(lhs_v - rhs.m_value) <= rhs.m_margin; } template ::value>::type> @@ -2870,32 +2778,60 @@ namespace Detail { } template ::value>::type> - friend bool operator <= ( T lhs, Approx const& rhs ) - { - return double(lhs) < rhs.m_value || lhs == rhs; + friend bool operator <= ( T lhs, Approx const& rhs ) { + return double(lhs) < rhs.m_value || lhs == rhs; } template ::value>::type> - friend bool operator <= ( Approx const& lhs, T rhs ) - { - return lhs.m_value < double(rhs) || lhs == rhs; + friend bool operator <= ( Approx const& lhs, T rhs ) { + return lhs.m_value < double(rhs) || lhs == rhs; } template ::value>::type> - friend bool operator >= ( T lhs, Approx const& rhs ) - { - return double(lhs) > rhs.m_value || lhs == rhs; + friend bool operator >= ( T lhs, Approx const& rhs ) { + return double(lhs) > rhs.m_value || lhs == rhs; } template ::value>::type> - friend bool operator >= ( Approx const& lhs, T rhs ) - { - return lhs.m_value > double(rhs) || lhs == rhs; + friend bool operator >= ( Approx const& lhs, T rhs ) { + return lhs.m_value > double(rhs) || lhs == rhs; } + + template ::value>::type> + Approx& epsilon( T newEpsilon ) { + m_epsilon = double(newEpsilon); + return *this; + } + + template ::value>::type> + Approx& margin( T newMargin ) { + m_margin = double(newMargin); + return *this; + } + + template ::value>::type> + Approx& scale( T newScale ) { + m_scale = double(newScale); + return *this; + } + #else + + Approx operator()( double value ) { + Approx approx( value ); + approx.epsilon( m_epsilon ); + approx.margin( m_margin ); + approx.scale( m_scale ); + return approx; + } + friend bool operator == ( double lhs, Approx const& rhs ) { // Thanks to Richard Harris for his help refining this formula - return std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) ); + bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) ); + if (relativeOK) { + return true; + } + return std::fabs(lhs - rhs.m_value) <= rhs.m_margin; } friend bool operator == ( Approx const& lhs, double rhs ) { @@ -2910,36 +2846,37 @@ namespace Detail { return !operator==( rhs, lhs ); } - friend bool operator <= ( double lhs, Approx const& rhs ) - { - return lhs < rhs.m_value || lhs == rhs; + friend bool operator <= ( double lhs, Approx const& rhs ) { + return lhs < rhs.m_value || lhs == rhs; } - friend bool operator <= ( Approx const& lhs, double rhs ) - { - return lhs.m_value < rhs || lhs == rhs; + friend bool operator <= ( Approx const& lhs, double rhs ) { + return lhs.m_value < rhs || lhs == rhs; } - friend bool operator >= ( double lhs, Approx const& rhs ) - { - return lhs > rhs.m_value || lhs == rhs; + friend bool operator >= ( double lhs, Approx const& rhs ) { + return lhs > rhs.m_value || lhs == rhs; } - friend bool operator >= ( Approx const& lhs, double rhs ) - { - return lhs.m_value > rhs || lhs == rhs; + friend bool operator >= ( Approx const& lhs, double rhs ) { + return lhs.m_value > rhs || lhs == rhs; } -#endif Approx& epsilon( double newEpsilon ) { m_epsilon = newEpsilon; return *this; } + Approx& margin( double newMargin ) { + m_margin = newMargin; + return *this; + } + Approx& scale( double newScale ) { m_scale = newScale; return *this; } +#endif std::string toString() const { std::ostringstream oss; @@ -2949,6 +2886,7 @@ namespace Detail { private: double m_epsilon; + double m_margin; double m_scale; double m_value; }; @@ -2961,6 +2899,153 @@ inline std::string toString( Detail::Approx const& value ) { } // end namespace Catch +// #included from: internal/catch_matchers_string.h +#define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED + +namespace Catch { +namespace Matchers { + + namespace StdString { + + struct CasedString + { + CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); + std::string adjustString( std::string const& str ) const; + std::string caseSensitivitySuffix() const; + + CaseSensitive::Choice m_caseSensitivity; + std::string m_str; + }; + + struct StringMatcherBase : MatcherBase { + StringMatcherBase( std::string const& operation, CasedString const& comparator ); + virtual std::string describe() const CATCH_OVERRIDE; + + CasedString m_comparator; + std::string m_operation; + }; + + struct EqualsMatcher : StringMatcherBase { + EqualsMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct ContainsMatcher : StringMatcherBase { + ContainsMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct StartsWithMatcher : StringMatcherBase { + StartsWithMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + struct EndsWithMatcher : StringMatcherBase { + EndsWithMatcher( CasedString const& comparator ); + virtual bool match( std::string const& source ) const CATCH_OVERRIDE; + }; + + } // namespace StdString + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + +} // namespace Matchers +} // namespace Catch + +// #included from: internal/catch_matchers_vector.h +#define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED + +namespace Catch { +namespace Matchers { + + namespace Vector { + + template + struct ContainsElementMatcher : MatcherBase, T> { + + ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + return std::find(v.begin(), v.end(), m_comparator) != v.end(); + } + + virtual std::string describe() const CATCH_OVERRIDE { + return "Contains: " + Catch::toString( m_comparator ); + } + + T const& m_comparator; + }; + + template + struct ContainsMatcher : MatcherBase, std::vector > { + + ContainsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + // !TBD: see note in EqualsMatcher + if (m_comparator.size() > v.size()) + return false; + for (size_t i = 0; i < m_comparator.size(); ++i) + if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end()) + return false; + return true; + } + virtual std::string describe() const CATCH_OVERRIDE { + return "Contains: " + Catch::toString( m_comparator ); + } + + std::vector const& m_comparator; + }; + + template + struct EqualsMatcher : MatcherBase, std::vector > { + + EqualsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const CATCH_OVERRIDE { + // !TBD: This currently works if all elements can be compared using != + // - a more general approach would be via a compare template that defaults + // to using !=. but could be specialised for, e.g. std::vector etc + // - then just call that directly + if (m_comparator.size() != v.size()) + return false; + for (size_t i = 0; i < v.size(); ++i) + if (m_comparator[i] != v[i]) + return false; + return true; + } + virtual std::string describe() const CATCH_OVERRIDE { + return "Equals: " + Catch::toString( m_comparator ); + } + std::vector const& m_comparator; + }; + + } // namespace Vector + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + template + Vector::ContainsMatcher Contains( std::vector const& comparator ) { + return Vector::ContainsMatcher( comparator ); + } + + template + Vector::ContainsElementMatcher VectorContains( T const& comparator ) { + return Vector::ContainsElementMatcher( comparator ); + } + + template + Vector::EqualsMatcher Equals( std::vector const& comparator ) { + return Vector::EqualsMatcher( comparator ); + } + +} // namespace Matchers +} // namespace Catch + // #included from: internal/catch_interfaces_tag_alias_registry.h #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED @@ -2972,7 +3057,7 @@ inline std::string toString( Detail::Approx const& value ) { namespace Catch { struct TagAlias { - TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} + TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} std::string tag; SourceLineInfo lineInfo; @@ -3044,8 +3129,18 @@ namespace Catch { } private: - T* nullableValue; - char storage[sizeof(T)]; + T *nullableValue; + union { + char storage[sizeof(T)]; + + // These are here to force alignment for the storage + long double dummy1; + void (*dummy2)(); + long double dummy3; +#ifdef CATCH_CONFIG_CPP11_LONG_LONG + long long dummy4; +#endif + }; }; } // end namespace Catch @@ -3244,64 +3339,67 @@ namespace Catch { namespace Impl { namespace NSStringMatchers { - template - struct StringHolder : MatcherImpl{ + struct StringHolder : MatcherBase{ StringHolder( NSString* substr ) : m_substr( [substr copy] ){} StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} StringHolder() { arcSafeRelease( m_substr ); } + virtual bool match( NSString* arg ) const CATCH_OVERRIDE { + return false; + } + NSString* m_substr; }; - struct Equals : StringHolder { + struct Equals : StringHolder { Equals( NSString* substr ) : StringHolder( substr ){} - virtual bool match( ExpressionType const& str ) const { + virtual bool match( NSString* str ) const CATCH_OVERRIDE { return (str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } - virtual std::string toString() const { + virtual std::string describe() const CATCH_OVERRIDE { return "equals string: " + Catch::toString( m_substr ); } }; - struct Contains : StringHolder { + struct Contains : StringHolder { Contains( NSString* substr ) : StringHolder( substr ){} - virtual bool match( ExpressionType const& str ) const { + virtual bool match( NSString* str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } - virtual std::string toString() const { + virtual std::string describe() const CATCH_OVERRIDE { return "contains string: " + Catch::toString( m_substr ); } }; - struct StartsWith : StringHolder { + struct StartsWith : StringHolder { StartsWith( NSString* substr ) : StringHolder( substr ){} - virtual bool match( ExpressionType const& str ) const { + virtual bool match( NSString* str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } - virtual std::string toString() const { + virtual std::string describe() const CATCH_OVERRIDE { return "starts with: " + Catch::toString( m_substr ); } }; - struct EndsWith : StringHolder { + struct EndsWith : StringHolder { EndsWith( NSString* substr ) : StringHolder( substr ){} - virtual bool match( ExpressionType const& str ) const { + virtual bool match( NSString* str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } - virtual std::string toString() const { + virtual std::string describe() const CATCH_OVERRIDE { return "ends with: " + Catch::toString( m_substr ); } }; @@ -3342,6 +3440,29 @@ return @ desc; \ #endif #ifdef CATCH_IMPL + +// !TBD: Move the leak detector code into a separate header +#ifdef CATCH_CONFIG_WINDOWS_CRTDBG +#include +class LeakDetector { +public: + LeakDetector() { + int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + flag |= _CRTDBG_LEAK_CHECK_DF; + flag |= _CRTDBG_ALLOC_MEM_DF; + _CrtSetDbgFlag(flag); + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + // Change this to leaking allocation's number to break there + _CrtSetBreakAlloc(-1); + } +}; +#else +class LeakDetector {}; +#endif + +LeakDetector leakDetector; + // #included from: internal/catch_impl.hpp #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED @@ -3534,7 +3655,7 @@ namespace Catch { ITagAliasRegistry const* m_tagAliases; public: - TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} + TestSpecParser( ITagAliasRegistry const& tagAliases ) :m_mode(None), m_exclusion(false), m_start(0), m_pos(0), m_tagAliases( &tagAliases ) {} TestSpecParser& parse( std::string const& arg ) { m_mode = None; @@ -3601,7 +3722,7 @@ namespace Catch { void addPattern() { std::string token = subString(); for( size_t i = 0; i < m_escapeChars.size(); ++i ) - token = token.substr( 0, m_escapeChars[i]-i ) + token.substr( m_escapeChars[i]+1-i ); + token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 ); m_escapeChars.clear(); if( startsWith( token, "exclude:" ) ) { m_exclusion = true; @@ -3668,6 +3789,12 @@ namespace Catch { Yes, No }; }; + struct WaitForKeypress { enum When { + Never, + BeforeStart = 1, + BeforeExit = 2, + BeforeStartAndExit = BeforeStart | BeforeExit + }; }; class TestSpec; @@ -3718,6 +3845,7 @@ namespace Catch { std::ostream& cout(); std::ostream& cerr(); + std::ostream& clog(); struct IStream { virtual ~IStream() CATCH_NOEXCEPT; @@ -3773,25 +3901,29 @@ namespace Catch { listTags( false ), listReporters( false ), listTestNamesOnly( false ), + listExtraInfo( false ), showSuccessfulTests( false ), shouldDebugBreak( false ), noThrow( false ), showHelp( false ), showInvisibles( false ), filenamesAsTags( false ), + libIdentify( false ), abortAfter( -1 ), rngSeed( 0 ), verbosity( Verbosity::Normal ), warnings( WarnAbout::Nothing ), showDurations( ShowDurations::DefaultForReporter ), runOrder( RunTests::InDeclarationOrder ), - useColour( UseColour::Auto ) + useColour( UseColour::Auto ), + waitForKeypress( WaitForKeypress::Never ) {} bool listTests; bool listTags; bool listReporters; bool listTestNamesOnly; + bool listExtraInfo; bool showSuccessfulTests; bool shouldDebugBreak; @@ -3799,6 +3931,7 @@ namespace Catch { bool showHelp; bool showInvisibles; bool filenamesAsTags; + bool libIdentify; int abortAfter; unsigned int rngSeed; @@ -3808,6 +3941,7 @@ namespace Catch { ShowDurations::OrNot showDurations; RunTests::InWhatOrder runOrder; UseColour::YesOrNo useColour; + WaitForKeypress::When waitForKeypress; std::string outputFilename; std::string name; @@ -3850,6 +3984,7 @@ namespace Catch { bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool listTags() const { return m_data.listTags; } bool listReporters() const { return m_data.listReporters; } + bool listExtraInfo() const { return m_data.listExtraInfo; } std::string getProcessName() const { return m_data.processName; } @@ -3937,6 +4072,7 @@ namespace Catch { #include #include #include +#include // Use optional outer namespace #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE @@ -4046,7 +4182,7 @@ namespace Tbc { return oss.str(); } - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { + friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) @@ -4279,7 +4415,7 @@ namespace Clara { _dest = _source; } char toLowerCh(char c) { - return static_cast( ::tolower( c ) ); + return static_cast( std::tolower( c ) ); } inline void convertInto( std::string const& _source, bool& _dest ) { std::string sourceLC = _source; @@ -4433,12 +4569,13 @@ namespace Clara { } void parseIntoTokens( std::string const& arg, std::vector& tokens ) { - for( std::size_t i = 0; i <= arg.size(); ++i ) { + for( std::size_t i = 0; i < arg.size(); ++i ) { char c = arg[i]; if( c == '"' ) inQuotes = !inQuotes; mode = handleMode( i, c, arg, tokens ); } + mode = handleMode( arg.size(), '\0', arg, tokens ); } Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { switch( mode ) { @@ -4471,6 +4608,7 @@ namespace Clara { default: from = i; return ShortOpt; } } + Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { if( std::string( ":=\0", 3 ).find( c ) == std::string::npos ) return mode; @@ -4802,7 +4940,7 @@ namespace Clara { } std::vector parseInto( std::vector const& args, ConfigT& config ) const { - std::string processName = args[0]; + std::string processName = args.empty() ? std::string() : args[0]; std::size_t lastSlash = processName.find_last_of( "/\\" ); if( lastSlash != std::string::npos ) processName = processName.substr( lastSlash+1 ); @@ -4997,6 +5135,18 @@ namespace Catch { else throw std::runtime_error( "colour mode must be one of: auto, yes or no" ); } + inline void setWaitForKeypress( ConfigData& config, std::string const& keypress ) { + std::string keypressLc = toLower( keypress ); + if( keypressLc == "start" ) + config.waitForKeypress = WaitForKeypress::BeforeStart; + else if( keypressLc == "exit" ) + config.waitForKeypress = WaitForKeypress::BeforeExit; + else if( keypressLc == "both" ) + config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; + else + throw std::runtime_error( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" ); + }; + inline void forceColour( ConfigData& config ) { config.useColour = UseColour::Yes; } @@ -5108,6 +5258,10 @@ namespace Catch { .describe( "list all/matching test cases names only" ) .bind( &ConfigData::listTestNamesOnly ); + cli["--list-extra-info"] + .describe( "list all/matching test cases with more info" ) + .bind( &ConfigData::listExtraInfo ); + cli["--list-reporters"] .describe( "list all reporters" ) .bind( &ConfigData::listReporters ); @@ -5128,6 +5282,14 @@ namespace Catch { .describe( "should output be colourised" ) .bind( &setUseColour, "yes|no" ); + cli["--libidentify"] + .describe( "report name and version according to libidentify standard" ) + .bind( &ConfigData::libIdentify ); + + cli["--wait-for-keypress"] + .describe( "waits for a keypress before exiting" ) + .bind( &setWaitForKeypress, "start|exit|both" ); + return cli; } @@ -5636,8 +5798,9 @@ namespace Catch { } std::size_t matchedTests = 0; - TextAttributes nameAttr, tagsAttr; + TextAttributes nameAttr, descAttr, tagsAttr; nameAttr.setInitialIndent( 2 ).setIndent( 4 ); + descAttr.setIndent( 4 ); tagsAttr.setIndent( 6 ); std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); @@ -5652,6 +5815,13 @@ namespace Catch { Colour colourGuard( colour ); Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; + if( config.listExtraInfo() ) { + Catch::cout() << " " << testCaseInfo.lineInfo << std::endl; + std::string description = testCaseInfo.description; + if( description.empty() ) + description = "(NO DESCRIPTION)"; + Catch::cout() << Text( description, descAttr ) << std::endl; + } if( !testCaseInfo.tags.empty() ) Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; } @@ -5675,9 +5845,12 @@ namespace Catch { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); if( startsWith( testCaseInfo.name, '#' ) ) - Catch::cout() << '"' << testCaseInfo.name << '"' << std::endl; + Catch::cout() << '"' << testCaseInfo.name << '"'; else - Catch::cout() << testCaseInfo.name << std::endl; + Catch::cout() << testCaseInfo.name; + if ( config.listExtraInfo() ) + Catch::cout() << "\t@" << testCaseInfo.lineInfo; + Catch::cout() << std::endl; } return matchedTests; } @@ -5769,7 +5942,7 @@ namespace Catch { inline Option list( Config const& config ) { Option listedCount; - if( config.listTests() ) + if( config.listTests() || ( config.listExtraInfo() && !config.listTestNamesOnly() ) ) listedCount = listedCount.valueOr(0) + listTests( config ); if( config.listTestNamesOnly() ) listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); @@ -5788,13 +5961,14 @@ namespace Catch { // #included from: catch_test_case_tracker.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED -#include +#include #include #include #include -#include #include +CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS + namespace Catch { namespace TestCaseTracking { @@ -6065,12 +6239,12 @@ namespace TestCaseTracking { if( !filters.empty() ) { m_filters.push_back(""); // Root - should never be consulted m_filters.push_back(""); // Test Case - not a section filter - std::copy( filters.begin(), filters.end(), std::back_inserter( m_filters ) ); + m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); } } void addNextFilters( std::vector const& filters ) { if( filters.size() > 1 ) - std::copy( filters.begin()+1, filters.end(), std::back_inserter( m_filters ) ); + m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); } }; @@ -6140,6 +6314,8 @@ using TestCaseTracking::IndexTracker; } // namespace Catch +CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS + // #included from: catch_fatal_condition.hpp #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED @@ -6209,7 +6385,6 @@ namespace Catch { static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { - reset(); reportFatal(signalDefs[i].name); } } @@ -6259,6 +6434,16 @@ namespace Catch { #else // Not Windows - assumed to be POSIX compatible ////////////////////////// +# if !defined(CATCH_CONFIG_POSIX_SIGNALS) + +namespace Catch { + struct FatalConditionHandler { + void reset() {} + }; +} + +# else // CATCH_CONFIG_POSIX_SIGNALS is defined + #include namespace Catch { @@ -6337,6 +6522,8 @@ namespace Catch { } // namespace Catch +# endif // CATCH_CONFIG_POSIX_SIGNALS + #endif // not Windows #include @@ -6367,6 +6554,29 @@ namespace Catch { std::string& m_targetString; }; + // StdErr has two constituent streams in C++, std::cerr and std::clog + // This means that we need to redirect 2 streams into 1 to keep proper + // order of writes and cannot use StreamRedirect on its own + class StdErrRedirect { + public: + StdErrRedirect(std::string& targetString) + :m_cerrBuf( cerr().rdbuf() ), m_clogBuf(clog().rdbuf()), + m_targetString(targetString){ + cerr().rdbuf(m_oss.rdbuf()); + clog().rdbuf(m_oss.rdbuf()); + } + ~StdErrRedirect() { + m_targetString += m_oss.str(); + cerr().rdbuf(m_cerrBuf); + clog().rdbuf(m_clogBuf); + } + private: + std::streambuf* m_cerrBuf; + std::streambuf* m_clogBuf; + std::ostringstream m_oss; + std::string& m_targetString; + }; + /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { @@ -6381,7 +6591,8 @@ namespace Catch { m_context( getCurrentMutableContext() ), m_activeTestCase( CATCH_NULL ), m_config( _config ), - m_reporter( reporter ) + m_reporter( reporter ), + m_shouldReportUnexpected ( true ) { m_context.setRunner( this ); m_context.setConfig( m_config ); @@ -6456,17 +6667,38 @@ namespace Catch { m_totals.assertions.passed++; } else if( !result.isOk() ) { - m_totals.assertions.failed++; + if( m_activeTestCase->getTestCaseInfo().okToFail() ) + m_totals.assertions.failedButOk++; + else + m_totals.assertions.failed++; } - if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) - m_messages.clear(); + // We have no use for the return value (whether messages should be cleared), because messages were made scoped + // and should be let to clear themselves out. + static_cast(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); // Reset working state - m_lastAssertionInfo = AssertionInfo( std::string(), m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); + m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); m_lastResult = result; } + virtual bool lastAssertionPassed() + { + return m_totals.assertions.passed == (m_prevPassed + 1); + } + + virtual void assertionPassed() + { + m_totals.assertions.passed++; + m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"; + m_lastAssertionInfo.macroName = ""; + } + + virtual void assertionRun() + { + m_prevPassed = m_totals.assertions.passed; + } + virtual bool sectionStarted ( SectionInfo const& sectionInfo, Counts& assertions @@ -6538,11 +6770,19 @@ namespace Catch { return &m_lastResult; } + virtual void exceptionEarlyReported() { + m_shouldReportUnexpected = false; + } + virtual void handleFatalErrorCondition( std::string const& message ) { - ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); - resultBuilder.setResultType( ResultWas::FatalErrorCondition ); - resultBuilder << message; - resultBuilder.captureExpression(); + // Don't rebuild the result -- the stringification itself can cause more fatal errors + // Instead, fake a result data. + AssertionResultData tempResult; + tempResult.resultType = ResultWas::FatalErrorCondition; + tempResult.message = message; + AssertionResult result(m_lastAssertionInfo, tempResult); + + getResultCapture().assertionEnded(result); handleUnfinishedSections(); @@ -6559,6 +6799,7 @@ namespace Catch { Totals deltaTotals; deltaTotals.testCases.failed = 1; + deltaTotals.assertions.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, std::string(), @@ -6583,8 +6824,9 @@ namespace Catch { m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; + m_shouldReportUnexpected = true; try { - m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, std::string(), ResultDisposition::Normal ); + m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); seedRng( *m_config ); @@ -6592,7 +6834,7 @@ namespace Catch { timer.start(); if( m_reporter->getPreferences().shouldRedirectStdOut ) { StreamRedirect coutRedir( Catch::cout(), redirectedCout ); - StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); + StdErrRedirect errRedir( redirectedCerr ); invokeActiveTestCase(); } else { @@ -6604,7 +6846,11 @@ namespace Catch { // This just means the test was aborted due to failure } catch(...) { - makeUnexpectedResultBuilder().useActiveException(); + // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions + // are reported without translation at the point of origin. + if (m_shouldReportUnexpected) { + makeUnexpectedResultBuilder().useActiveException(); + } } m_testCaseTracker->close(); handleUnfinishedSections(); @@ -6613,12 +6859,6 @@ namespace Catch { Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); - if( testCaseInfo.okToFail() ) { - std::swap( assertions.failedButOk, assertions.failed ); - m_totals.assertions.failed -= assertions.failedButOk; - m_totals.assertions.failedButOk += assertions.failedButOk; - } - SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } @@ -6632,9 +6872,9 @@ namespace Catch { private: ResultBuilder makeUnexpectedResultBuilder() const { - return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), + return ResultBuilder( m_lastAssertionInfo.macroName, m_lastAssertionInfo.lineInfo, - m_lastAssertionInfo.capturedExpression.c_str(), + m_lastAssertionInfo.capturedExpression, m_lastAssertionInfo.resultDisposition ); } @@ -6664,6 +6904,8 @@ namespace Catch { std::vector m_unfinishedSections; std::vector m_activeSections; TrackerContext m_trackerContext; + size_t m_prevPassed; + bool m_shouldReportUnexpected; }; IResultCapture& getResultCapture() { @@ -6685,7 +6927,7 @@ namespace Catch { Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, - std::string const& _branchName, + char const * const _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; @@ -6693,7 +6935,7 @@ namespace Catch { unsigned int const patchNumber; // buildNumber is only used if branchName is not null - std::string const branchName; + char const * const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); @@ -6702,7 +6944,7 @@ namespace Catch { void operator=( Version const& ); }; - extern Version libraryVersion; + inline Version libraryVersion(); } #include @@ -6721,10 +6963,14 @@ namespace Catch { return reporter; } +#if !defined(CATCH_CONFIG_DEFAULT_REPORTER) +#define CATCH_CONFIG_DEFAULT_REPORTER "console" +#endif + Ptr makeReporter( Ptr const& config ) { std::vector reporters = config->getReporterNames(); if( reporters.empty() ) - reporters.push_back( "console" ); + reporters.push_back( CATCH_CONFIG_DEFAULT_REPORTER ); Ptr reporter; for( std::vector::const_iterator it = reporters.begin(), itEnd = reporters.end(); @@ -6784,11 +7030,11 @@ namespace Catch { if( lastSlash != std::string::npos ) filename = filename.substr( lastSlash+1 ); - std::string::size_type lastDot = filename.find_last_of( "." ); + std::string::size_type lastDot = filename.find_last_of( '.' ); if( lastDot != std::string::npos ) filename = filename.substr( 0, lastDot ); - tags.insert( "#" + filename ); + tags.insert( '#' + filename ); setTags( test, tags ); } } @@ -6814,11 +7060,18 @@ namespace Catch { } void showHelp( std::string const& processName ) { - Catch::cout() << "\nCatch v" << libraryVersion << "\n"; + Catch::cout() << "\nCatch v" << libraryVersion() << "\n"; m_cli.usage( Catch::cout(), processName ); Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; } + void libIdentify() { + Catch::cout() + << std::left << std::setw(16) << "description: " << "A Catch test executable\n" + << std::left << std::setw(16) << "category: " << "testframework\n" + << std::left << std::setw(16) << "framework: " << "Catch Test\n" + << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl; + } int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { try { @@ -6826,6 +7079,8 @@ namespace Catch { m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData ); if( m_configData.showHelp ) showHelp( m_configData.processName ); + if( m_configData.libIdentify ) + libIdentify(); m_config.reset(); } catch( std::exception& ex ) { @@ -6849,14 +7104,69 @@ namespace Catch { int run( int argc, char const* const* const argv ) { - int returnCode = applyCommandLine( argc, argv ); + int returnCode = applyCommandLine( argc, argv ); + if( returnCode == 0 ) + returnCode = run(); + return returnCode; + } + + #if defined(WIN32) && defined(UNICODE) + int run( int argc, wchar_t const* const* const argv ) { + + char **utf8Argv = new char *[ argc ]; + + for ( int i = 0; i < argc; ++i ) { + int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); + + utf8Argv[ i ] = new char[ bufSize ]; + + WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); + } + + int returnCode = applyCommandLine( argc, utf8Argv ); if( returnCode == 0 ) returnCode = run(); + + for ( int i = 0; i < argc; ++i ) + delete [] utf8Argv[ i ]; + + delete [] utf8Argv; + return returnCode; } + #endif int run() { - if( m_configData.showHelp ) + if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { + Catch::cout() << "...waiting for enter/ return before starting" << std::endl; + static_cast(std::getchar()); + } + int exitCode = runInternal(); + if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { + Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl; + static_cast(std::getchar()); + } + return exitCode; + } + + Clara::CommandLine const& cli() const { + return m_cli; + } + std::vector const& unusedTokens() const { + return m_unusedTokens; + } + ConfigData& configData() { + return m_configData; + } + Config& config() { + if( !m_config ) + m_config = new Config( m_configData ); + return *m_config; + } + private: + + int runInternal() { + if( m_configData.showHelp || m_configData.libIdentify ) return 0; try @@ -6880,21 +7190,6 @@ namespace Catch { } } - Clara::CommandLine const& cli() const { - return m_cli; - } - std::vector const& unusedTokens() const { - return m_unusedTokens; - } - ConfigData& configData() { - return m_configData; - } - Config& config() { - if( !m_config ) - m_config = new Config( m_configData ); - return *m_config; - } - private: Clara::CommandLine m_cli; std::vector m_unusedTokens; ConfigData m_configData; @@ -6919,7 +7214,7 @@ namespace Catch { namespace Catch { struct RandomNumberGenerator { - typedef std::ptrdiff_t result_type; + typedef unsigned int result_type; result_type operator()( result_type n ) const { return std::rand() % n; } @@ -7202,6 +7497,26 @@ namespace Catch { }; } +// #included from: catch_tag_alias_registry.h +#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED + +#include + +namespace Catch { + + class TagAliasRegistry : public ITagAliasRegistry { + public: + virtual ~TagAliasRegistry(); + virtual Option find( std::string const& alias ) const; + virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; + void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); + + private: + std::map m_registry; + }; + +} // end namespace Catch + namespace Catch { namespace { @@ -7223,6 +7538,9 @@ namespace Catch { virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { return m_exceptionTranslatorRegistry; } + virtual ITagAliasRegistry const& getTagAliasRegistry() const CATCH_OVERRIDE { + return m_tagAliasRegistry; + } public: // IMutableRegistryHub virtual void registerReporter( std::string const& name, Ptr const& factory ) CATCH_OVERRIDE { @@ -7237,11 +7555,15 @@ namespace Catch { virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { m_exceptionTranslatorRegistry.registerTranslator( translator ); } + virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) CATCH_OVERRIDE { + m_tagAliasRegistry.add( alias, tag, lineInfo ); + } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; + TagAliasRegistry m_tagAliasRegistry; }; // Single, global, instance @@ -7387,6 +7709,9 @@ namespace Catch { std::ostream& cerr() { return std::cerr; } + std::ostream& clog() { + return std::clog; + } #endif } @@ -7486,6 +7811,23 @@ namespace Catch { // #included from: catch_console_colour_impl.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED +// #included from: catch_errno_guard.hpp +#define TWOBLUECUBES_CATCH_ERRNO_GUARD_HPP_INCLUDED + +#include + +namespace Catch { + + class ErrnoGuard { + public: + ErrnoGuard():m_oldErrno(errno){} + ~ErrnoGuard() { errno = m_oldErrno; } + private: + int m_oldErrno; + }; + +} + namespace Catch { namespace { @@ -7621,6 +7963,7 @@ namespace { }; IColourImpl* platformColourInstance() { + ErrnoGuard guard; Ptr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() @@ -7739,14 +8082,18 @@ namespace Catch { namespace Catch { - AssertionInfo::AssertionInfo( std::string const& _macroName, + AssertionInfo::AssertionInfo():macroName(""), capturedExpression(""), resultDisposition(ResultDisposition::Normal), secondArg(""){} + + AssertionInfo::AssertionInfo( char const * _macroName, SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ) + char const * _capturedExpression, + ResultDisposition::Flags _resultDisposition, + char const * _secondArg) : macroName( _macroName ), lineInfo( _lineInfo ), capturedExpression( _capturedExpression ), - resultDisposition( _resultDisposition ) + resultDisposition( _resultDisposition ), + secondArg( _secondArg ) {} AssertionResult::AssertionResult() {} @@ -7773,24 +8120,30 @@ namespace Catch { } bool AssertionResult::hasExpression() const { - return !m_info.capturedExpression.empty(); + return m_info.capturedExpression[0] != 0; } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } + std::string capturedExpressionWithSecondArgument( char const * capturedExpression, char const * secondArg ) { + return (secondArg[0] == 0 || secondArg[0] == '"' && secondArg[1] == '"') + ? capturedExpression + : std::string(capturedExpression) + ", " + secondArg; + } + std::string AssertionResult::getExpression() const { if( isFalseTest( m_info.resultDisposition ) ) - return '!' + m_info.capturedExpression; + return "!(" + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg) + ")"; else - return m_info.capturedExpression; + return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg); } std::string AssertionResult::getExpressionInMacro() const { - if( m_info.macroName.empty() ) - return m_info.capturedExpression; + if( m_info.macroName[0] == 0 ) + return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg); else - return m_info.macroName + "( " + m_info.capturedExpression + " )"; + return std::string(m_info.macroName) + "( " + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg) + " )"; } bool AssertionResult::hasExpandedExpression() const { @@ -7850,17 +8203,13 @@ namespace Catch { } inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { if( isReservedTag( tag ) ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "Tag name [" << tag << "] not allowed.\n" - << "Tag names starting with non alpha-numeric characters are reserved\n"; - } - { - Colour colourGuard( Colour::FileName ); - Catch::cerr() << _lineInfo << std::endl; - } - exit(1); + std::ostringstream ss; + ss << Colour(Colour::Red) + << "Tag name [" << tag << "] not allowed.\n" + << "Tag names starting with non alpha-numeric characters are reserved\n" + << Colour(Colour::FileName) + << _lineInfo << '\n'; + throw std::runtime_error(ss.str()); } } @@ -8022,7 +8371,7 @@ namespace Catch { ( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, - std::string const& _branchName, + char const * const _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ), minorVersion( _minorVersion ), @@ -8035,15 +8384,18 @@ namespace Catch { os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber; - - if( !version.branchName.empty() ) { - os << '-' << version.branchName - << '.' << version.buildNumber; + // branchName is never null -> 0th char is \0 if it is empty + if (version.branchName[0]) { + os << '-' << version.branchName + << '.' << version.buildNumber; } return os; } - Version libraryVersion( 1, 7, 2, "", 0 ); + inline Version libraryVersion() { + static Version version( 1, 11, 0, "", 0 ); + return version; + } } @@ -8077,7 +8429,9 @@ namespace Catch { {} ScopedMessage::~ScopedMessage() { - getResultCapture().popScopedMessage( m_info ); + if ( !std::uncaught_exception() ){ + getResultCapture().popScopedMessage(m_info); + } } } // end namespace Catch @@ -8214,29 +8568,32 @@ namespace Catch #endif #ifdef CATCH_PLATFORM_WINDOWS + #else + #include + #endif namespace Catch { namespace { #ifdef CATCH_PLATFORM_WINDOWS - uint64_t getCurrentTicks() { - static uint64_t hz=0, hzo=0; + UInt64 getCurrentTicks() { + static UInt64 hz=0, hzo=0; if (!hz) { QueryPerformanceFrequency( reinterpret_cast( &hz ) ); QueryPerformanceCounter( reinterpret_cast( &hzo ) ); } - uint64_t t; + UInt64 t; QueryPerformanceCounter( reinterpret_cast( &t ) ); return ((t-hzo)*1000000)/hz; } #else - uint64_t getCurrentTicks() { + UInt64 getCurrentTicks() { timeval t; gettimeofday(&t,CATCH_NULL); - return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); + return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); } #endif } @@ -8388,6 +8745,10 @@ namespace Catch { m_timer.start(); } +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17 +#endif Section::~Section() { if( m_sectionIncluded ) { SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); @@ -8397,6 +8758,9 @@ namespace Catch { getResultCapture().sectionEnded( endInfo ); } } +#if defined(_MSC_VER) +#pragma warning(pop) +#endif // This indicates whether the section should be executed or not Section::operator bool() const { @@ -8469,6 +8833,9 @@ namespace Catch { // be strace, for example) in /proc/$PID/status, so just get it from // there instead. bool isDebuggerActive(){ + // Libstdc++ has a bug, where std::ifstream sets errno to 0 + // This way our users can properly assert over errno values + ErrnoGuard guard; std::ifstream in("/proc/self/status"); for( std::string line; std::getline(in, line); ) { static const int PREFIX_LEN = 11; @@ -8709,7 +9076,7 @@ std::string toString( std::nullptr_t ) { return "nil"; return "@" + toString([nsstring UTF8String]); } - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { + std::string toString( NSString * CATCH_ARC_STRONG & nsstring ) { if( !nsstring ) return "nil"; return "@" + toString([nsstring UTF8String]); @@ -8726,21 +9093,28 @@ std::string toString( std::nullptr_t ) { namespace Catch { - std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) { - return secondArg.empty() || secondArg == "\"\"" - ? capturedExpression - : capturedExpression + ", " + secondArg; - } ResultBuilder::ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg ) - : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ), + : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition, secondArg ), m_shouldDebugBreak( false ), - m_shouldThrow( false ) + m_shouldThrow( false ), + m_guardException( false ), + m_usedStream( false ) {} + ResultBuilder::~ResultBuilder() { +#if defined(CATCH_CONFIG_FAST_COMPILE) + if ( m_guardException ) { + stream().oss << "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; + captureResult( ResultWas::ThrewException ); + getCurrentContext().getResultCapture()->exceptionEarlyReported(); + } +#endif + } + ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { m_data.resultType = result; return *this; @@ -8751,13 +9125,25 @@ namespace Catch { } void ResultBuilder::endExpression( DecomposedExpression const& expr ) { - AssertionResult result = build( expr ); - handleResult( result ); + // Flip bool results if FalseTest flag is set + if( isFalseTest( m_assertionInfo.resultDisposition ) ) { + m_data.negate( expr.isBinaryExpression() ); + } + + getResultCapture().assertionRun(); + + if(getCurrentContext().getConfig()->includeSuccessfulResults() || m_data.resultType != ResultWas::Ok) + { + AssertionResult result = build( expr ); + handleResult( result ); + } + else + getResultCapture().assertionPassed(); } void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { m_assertionInfo.resultDisposition = resultDisposition; - m_stream.oss << Catch::translateActiveException(); + stream().oss << Catch::translateActiveException(); captureResult( ResultWas::ThrewException ); } @@ -8768,17 +9154,17 @@ namespace Catch { void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { if( expectedMessage.empty() ) - captureExpectedException( Matchers::Impl::Generic::AllOf() ); + captureExpectedException( Matchers::Impl::MatchAllOf() ); else captureExpectedException( Matchers::Equals( expectedMessage ) ); } - void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher const& matcher ) { + void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase const& matcher ) { assert( !isFalseTest( m_assertionInfo.resultDisposition ) ); AssertionResultData data = m_data; data.resultType = ResultWas::Ok; - data.reconstructedExpression = m_assertionInfo.capturedExpression; + data.reconstructedExpression = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg); std::string actualMessage = Catch::translateActiveException(); if( !matcher.match( actualMessage ) ) { @@ -8807,6 +9193,15 @@ namespace Catch { } void ResultBuilder::react() { +#if defined(CATCH_CONFIG_FAST_COMPILE) + if (m_shouldDebugBreak) { + /////////////////////////////////////////////////////////////////// + // To inspect the state during test, you need to go one level up the callstack + // To go back to the test and change execution, jump over the throw statement + /////////////////////////////////////////////////////////////////// + CATCH_BREAK_INTO_DEBUGGER(); + } +#endif if( m_shouldThrow ) throw Catch::TestFailureException(); } @@ -8830,18 +9225,21 @@ namespace Catch { assert( m_data.resultType != ResultWas::Unknown ); AssertionResultData data = m_data; - // Flip bool results if FalseTest flag is set - if( isFalseTest( m_assertionInfo.resultDisposition ) ) { - data.negate( expr.isBinaryExpression() ); - } - - data.message = m_stream.oss.str(); + if(m_usedStream) + data.message = m_stream().oss.str(); data.decomposedExpression = &expr; // for lazy reconstruction return AssertionResult( m_assertionInfo, data ); } void ResultBuilder::reconstructExpression( std::string& dest ) const { - dest = m_assertionInfo.capturedExpression; + dest = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg); + } + + void ResultBuilder::setExceptionGuard() { + m_guardException = true; + } + void ResultBuilder::unsetExceptionGuard() { + m_guardException = false; } } // end namespace Catch @@ -8849,27 +9247,6 @@ namespace Catch { // #included from: catch_tag_alias_registry.hpp #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED -// #included from: catch_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED - -#include - -namespace Catch { - - class TagAliasRegistry : public ITagAliasRegistry { - public: - virtual ~TagAliasRegistry(); - virtual Option find( std::string const& alias ) const; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; - void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - static TagAliasRegistry& get(); - - private: - std::map m_registry; - }; - -} // end namespace Catch - namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} @@ -8897,44 +9274,120 @@ namespace Catch { return expandedTestSpec; } - void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { + void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) { std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; + oss << Colour( Colour::Red ) + << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" + << Colour( Colour::FileName ) + << lineInfo << '\n'; throw std::domain_error( oss.str().c_str() ); } if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" already registered.\n" - << "\tFirst seen at " << find(alias)->lineInfo << '\n' - << "\tRedefined at " << lineInfo; + oss << Colour( Colour::Red ) + << "error: tag alias, \"" << alias << "\" already registered.\n" + << "\tFirst seen at " + << Colour( Colour::Red ) << find(alias)->lineInfo << '\n' + << Colour( Colour::Red ) << "\tRedefined at " + << Colour( Colour::FileName) << lineInfo << '\n'; throw std::domain_error( oss.str().c_str() ); } } - TagAliasRegistry& TagAliasRegistry::get() { - static TagAliasRegistry instance; - return instance; + ITagAliasRegistry::~ITagAliasRegistry() {} + ITagAliasRegistry const& ITagAliasRegistry::get() { + return getRegistryHub().getTagAliasRegistry(); } - ITagAliasRegistry::~ITagAliasRegistry() {} - ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } - RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - try { - TagAliasRegistry::get().add( alias, tag, lineInfo ); - } - catch( std::exception& ex ) { - Colour colourGuard( Colour::Red ); - Catch::cerr() << ex.what() << std::endl; - exit(1); - } + getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo ); } } // end namespace Catch +// #included from: catch_matchers_string.hpp + +namespace Catch { +namespace Matchers { + + namespace StdString { + + CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) + : m_caseSensitivity( caseSensitivity ), + m_str( adjustString( str ) ) + {} + std::string CasedString::adjustString( std::string const& str ) const { + return m_caseSensitivity == CaseSensitive::No + ? toLower( str ) + : str; + } + std::string CasedString::caseSensitivitySuffix() const { + return m_caseSensitivity == CaseSensitive::No + ? " (case insensitive)" + : std::string(); + } + + StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) + : m_comparator( comparator ), + m_operation( operation ) { + } + + std::string StringMatcherBase::describe() const { + std::string description; + description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + + m_comparator.caseSensitivitySuffix().size()); + description += m_operation; + description += ": \""; + description += m_comparator.m_str; + description += "\""; + description += m_comparator.caseSensitivitySuffix(); + return description; + } + + EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} + + bool EqualsMatcher::match( std::string const& source ) const { + return m_comparator.adjustString( source ) == m_comparator.m_str; + } + + ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} + + bool ContainsMatcher::match( std::string const& source ) const { + return contains( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} + + bool StartsWithMatcher::match( std::string const& source ) const { + return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} + + bool EndsWithMatcher::match( std::string const& source ) const { + return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + } // namespace StdString + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + +} // namespace Matchers +} // namespace Catch // #included from: ../reporters/catch_reporter_multi.hpp #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED @@ -9078,9 +9531,34 @@ Ptr addReporter( Ptr const& existingRepo #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED #include +#include +#include +#include namespace Catch { + namespace { + // Because formatting using c++ streams is stateful, drop down to C is required + // Alternatively we could use stringstream, but its performance is... not good. + std::string getFormattedDuration( double duration ) { + // Max exponent + 1 is required to represent the whole part + // + 1 for decimal point + // + 3 for the 3 decimal places + // + 1 for null terminator + const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; + char buffer[maxDoubleSize]; + + // Save previous errno, to prevent sprintf from overwriting it + ErrnoGuard guard; +#ifdef _MSC_VER + sprintf_s(buffer, "%.3f", duration); +#else + sprintf(buffer, "%.3f", duration); +#endif + return std::string(buffer); + } + } + struct StreamingReporterBase : SharedImpl { StreamingReporterBase( ReporterConfig const& _config ) @@ -9177,7 +9655,8 @@ namespace Catch { BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} bool operator() ( Ptr const& node ) const { - return node->stats.sectionInfo.lineInfo == m_other.lineInfo; + return ((node->stats.sectionInfo.name == m_other.name) && + (node->stats.sectionInfo.lineInfo == m_other.lineInfo)); } private: void operator=( BySectionInfo const& ); @@ -9406,9 +9885,13 @@ namespace Catch { #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } +// Deprecated - use the form without INTERNAL_ #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } +#define CATCH_REGISTER_LISTENER( listenerType ) \ + namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } + // #included from: ../internal/catch_xmlwriter.hpp #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED @@ -9641,20 +10124,6 @@ namespace Catch { }; } -// #included from: catch_reenable_warnings.h - -#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(pop) -# else -# pragma clang diagnostic pop -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic pop -#endif - namespace Catch { class XmlReporter : public StreamingReporterBase { @@ -9677,6 +10146,12 @@ namespace Catch { return std::string(); } + void writeSourceInfo( SourceLineInfo const& sourceInfo ) { + m_xml + .writeAttribute( "filename", sourceInfo.file ) + .writeAttribute( "line", sourceInfo.line ); + } + public: // StreamingReporterBase virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { @@ -9706,6 +10181,8 @@ namespace Catch { .writeAttribute( "description", testInfo.description ) .writeAttribute( "tags", testInfo.tagsAsString ); + writeSourceInfo( testInfo.lineInfo ); + if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); m_xml.ensureTagClosed(); @@ -9717,6 +10194,7 @@ namespace Catch { m_xml.startElement( "Section" ) .writeAttribute( "name", trim( sectionInfo.name ) ) .writeAttribute( "description", sectionInfo.description ); + writeSourceInfo( sectionInfo.lineInfo ); m_xml.ensureTagClosed(); } } @@ -9724,71 +10202,76 @@ namespace Catch { virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - const AssertionResult& assertionResult = assertionStats.assertionResult; - // Print any info messages in tags. - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { + AssertionResult const& result = assertionStats.assertionResult; + + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + + if( includeResults ) { + // Print any info messages in tags. for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { + it != itEnd; + ++it ) { if( it->type == ResultWas::Info ) { m_xml.scopedElement( "Info" ) - .writeText( it->message ); + .writeText( it->message ); } else if ( it->type == ResultWas::Warning ) { m_xml.scopedElement( "Warning" ) - .writeText( it->message ); + .writeText( it->message ); } } } // Drop out if result was successful but we're not printing them. - if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) + if( !includeResults && result.getResultType() != ResultWas::Warning ) return true; // Print the expression if there is one. - if( assertionResult.hasExpression() ) { + if( result.hasExpression() ) { m_xml.startElement( "Expression" ) - .writeAttribute( "success", assertionResult.succeeded() ) - .writeAttribute( "type", assertionResult.getTestMacroName() ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ); + .writeAttribute( "success", result.succeeded() ) + .writeAttribute( "type", result.getTestMacroName() ); + + writeSourceInfo( result.getSourceInfo() ); m_xml.scopedElement( "Original" ) - .writeText( assertionResult.getExpression() ); + .writeText( result.getExpression() ); m_xml.scopedElement( "Expanded" ) - .writeText( assertionResult.getExpandedExpression() ); + .writeText( result.getExpandedExpression() ); } // And... Print a result applicable to each result type. - switch( assertionResult.getResultType() ) { + switch( result.getResultType() ) { case ResultWas::ThrewException: - m_xml.scopedElement( "Exception" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); + m_xml.startElement( "Exception" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); break; case ResultWas::FatalErrorCondition: - m_xml.scopedElement( "FatalErrorCondition" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); + m_xml.startElement( "FatalErrorCondition" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); break; case ResultWas::Info: m_xml.scopedElement( "Info" ) - .writeText( assertionResult.getMessage() ); + .writeText( result.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: - m_xml.scopedElement( "Failure" ) - .writeText( assertionResult.getMessage() ); + m_xml.startElement( "Failure" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); break; default: break; } - if( assertionResult.hasExpression() ) + if( result.hasExpression() ) m_xml.endElement(); return true; @@ -9894,7 +10377,9 @@ namespace Catch { public: JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ), - xml( _config.stream() ) + xml( _config.stream() ), + unexpectedExceptions( 0 ), + m_okToFail( false ) { m_reporterPrefs.shouldRedirectStdOut = true; } @@ -9920,8 +10405,11 @@ namespace Catch { CumulativeReporterBase::testGroupStarting( groupInfo ); } + virtual void testCaseStarting( TestCaseInfo const& testCaseInfo ) CATCH_OVERRIDE { + m_okToFail = testCaseInfo.okToFail(); + } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) + if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } @@ -10086,6 +10574,7 @@ namespace Catch { std::ostringstream stdOutForSuite; std::ostringstream stdErrForSuite; unsigned int unexpectedExceptions; + bool m_okToFail; }; INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) @@ -10095,6 +10584,9 @@ namespace Catch { // #included from: ../reporters/catch_reporter_console.hpp #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED +#include +#include + namespace Catch { struct ConsoleReporter : StreamingReporterBase { @@ -10118,18 +10610,15 @@ namespace Catch { virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { AssertionResult const& result = _assertionStats.assertionResult; - bool printInfoMessages = true; + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } + // Drop out if result was successful but we're not printing them. + if( !includeResults && result.getResultType() != ResultWas::Warning ) + return false; lazyPrint(); - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); + AssertionPrinter printer( stream, _assertionStats, includeResults ); printer.print(); stream << std::endl; return true; @@ -10149,15 +10638,12 @@ namespace Catch { stream << "\nNo assertions in test case"; stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; } + if( m_config->showDurations() == ShowDurations::Always ) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } if( m_headerPrinted ) { - if( m_config->showDurations() == ShowDurations::Always ) - stream << "Completed in " << _sectionStats.durationInSeconds << 's' << std::endl; m_headerPrinted = false; } - else { - if( m_config->showDurations() == ShowDurations::Always ) - stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << 's' << std::endl; - } StreamingReporterBase::sectionEnded( _sectionStats ); } @@ -10222,7 +10708,11 @@ namespace Catch { case ResultWas::ThrewException: colour = Colour::Error; passOrFail = "FAILED"; - messageLabel = "due to unexpected exception with message"; + messageLabel = "due to unexpected exception with "; + if (_stats.infoMessages.size() == 1) + messageLabel += "message"; + if (_stats.infoMessages.size() > 1) + messageLabel += "messages"; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; @@ -10338,7 +10828,7 @@ namespace Catch { stream << '\n' << getLineOfChars<'~'>() << '\n'; Colour colour( Colour::SecondaryText ); stream << currentTestRunInfo->name - << " is a Catch v" << libraryVersion << " host application.\n" + << " is a Catch v" << libraryVersion() << " host application.\n" << "Run with -? for options\n\n"; if( m_config->rngSeed() != 0 ) @@ -10551,8 +11041,7 @@ namespace Catch { stream << "No test cases matched '" << spec << '\'' << std::endl; } - virtual void assertionStarting( AssertionInfo const& ) { - } + virtual void assertionStarting( AssertionInfo const& ) {} virtual bool assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; @@ -10573,6 +11062,12 @@ namespace Catch { return true; } + virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE { + if (m_config->showDurations() == ShowDurations::Always) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + } + virtual void testRunEnded( TestRunStats const& _testRunStats ) { printTotals( _testRunStats.totals ); stream << '\n' << std::endl; @@ -10678,7 +11173,7 @@ namespace Catch { stream << result.getSourceInfo() << ':'; } - void printResultType( Colour::Code colour, std::string passOrFail ) const { + void printResultType( Colour::Code colour, std::string const& passOrFail ) const { if( !passOrFail.empty() ) { { Colour colourGuard( colour ); @@ -10688,7 +11183,7 @@ namespace Catch { } } - void printIssue( std::string issue ) const { + void printIssue( std::string const& issue ) const { stream << ' ' << issue; } @@ -10859,11 +11354,7 @@ namespace Catch { TestSpec::NamePattern::~NamePattern() {} TestSpec::TagPattern::~TagPattern() {} TestSpec::ExcludedPattern::~ExcludedPattern() {} - - Matchers::Impl::StdString::Equals::~Equals() {} - Matchers::Impl::StdString::Contains::~Contains() {} - Matchers::Impl::StdString::StartsWith::~StartsWith() {} - Matchers::Impl::StdString::EndsWith::~EndsWith() {} + Matchers::Impl::MatcherUntypedBase::~MatcherUntypedBase() {} void Config::dummy() {} @@ -10887,8 +11378,14 @@ namespace Catch { #ifndef __OBJC__ +#if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) +// Standard C/C++ Win32 Unicode wmain entry point +extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { +#else // Standard C/C++ main entry point int main (int argc, char * argv[]) { +#endif + int result = Catch::Session().run( argc, argv ); return ( result < 0xff ? result : 0xff ); } @@ -10924,33 +11421,43 @@ int main (int argc, char * const argv[]) { // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL -#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) -#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#else +#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#endif -#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "CATCH_REQUIRE_THROWS" ) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) -#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "CATCH_REQUIRE_THROWS_WITH" ) -#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) +#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) +#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) -#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) -#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) -#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) -#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) -#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) +#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) +#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) -#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CATCH_CHECK_THROWS" ) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) -#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" ) -#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) +#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) +#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) +#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) + +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#else +#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif -#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) -#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) -#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) +#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) +#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) +#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) +#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) @@ -10958,16 +11465,18 @@ int main (int argc, char * const argv[]) { #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) - #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) + #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) + #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) + #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #else #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) - #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) + #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) + #define CATCH_FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) + #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) #endif #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) @@ -10993,50 +11502,63 @@ int main (int argc, char * const argv[]) { // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else -#define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" ) -#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) + +#else +#define REQUIRE( expr ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) +#endif + +#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) +#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) -#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "REQUIRE_THROWS" ) -#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) -#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "REQUIRE_THROWS_WITH" ) -#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) +#define CHECK( expr ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) +#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) -#define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) -#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) -#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) -#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) -#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) +#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) +#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CHECK_THROWS" ) -#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) -#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CHECK_THROWS_WITH" ) -#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) +#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) +#if defined(CATCH_CONFIG_FAST_COMPILE) +#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#else +#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif -#define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) -#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) -#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) +#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) +#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) +#define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) +#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) #ifdef CATCH_CONFIG_VARIADIC_MACROS - #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) - #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) - #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) +#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) +#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) +#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) +#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) +#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #else - #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) +#define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) - #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) + #define FAIL( msg ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) + #define FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) + #define SUCCEED( msg ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) #endif #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) @@ -11065,5 +11587,19 @@ int main (int argc, char * const argv[]) { using Catch::Detail::Approx; +// #included from: internal/catch_reenable_warnings.h + +#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(pop) +# else +# pragma clang diagnostic pop +# endif +#elif defined __GNUC__ +# pragma GCC diagnostic pop +#endif + #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED From 72510cc3eea192c51659bc059e65a08788ac1efe Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Sun, 26 Nov 2017 20:00:12 -0500 Subject: [PATCH 17/28] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6635d0c17..22a8cf981 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Travis CI runs release builds using [ccache](https://ccache.samba.org/) to speed 1. Apple Clang 7.3.0, GFortran 5.5.0, Python 2.7 This build generates _only_ the static library. - 2. GCC 6.4.0, Python 3.6 This build generates _both_ the shared and static + 2. GCC 7.2.0, Python 3.6 This build generates _both_ the shared and static libraries, linking executables to the former. The build needed for submission to [Coverity scan](https://scan.coverity.com/) From eff7e7de6c91599ab4ce50cfcba9f19e48278052 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Mon, 27 Nov 2017 12:01:49 -0500 Subject: [PATCH 18/28] Fix docstrings in dielectric_profile [ci skip] --- src/green/dielectric_profile/Anisotropic.hpp | 12 ++--- src/green/dielectric_profile/MembraneTanh.hpp | 49 +++++++++++++------ src/green/dielectric_profile/Metal.hpp | 12 ++--- src/green/dielectric_profile/OneLayerErf.hpp | 2 +- src/green/dielectric_profile/OneLayerTanh.hpp | 12 ++--- src/green/dielectric_profile/ProfileTypes.hpp | 2 +- src/green/dielectric_profile/Sharp.hpp | 12 ++--- src/green/dielectric_profile/Uniform.hpp | 12 ++--- src/green/dielectric_profile/Yukawa.hpp | 10 ++-- 9 files changed, 71 insertions(+), 52 deletions(-) diff --git a/src/green/dielectric_profile/Anisotropic.hpp b/src/green/dielectric_profile/Anisotropic.hpp index b98ec782d..9189fdf0b 100644 --- a/src/green/dielectric_profile/Anisotropic.hpp +++ b/src/green/dielectric_profile/Anisotropic.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -31,15 +31,15 @@ #include "utils/MathUtils.hpp" -/*! \file Anisotropic.hpp - * \class Anisotropic +/*! \file Anisotropic.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \class Anisotropic * \brief describes a medium with anisotropy, i.e. liquid crystal * \author Roberto Di Remigio * \date 2014 */ - -namespace pcm { -namespace dielectric_profile { class Anisotropic __final { private: /// Diagonal of the permittivity tensor in the lab-fixed frame diff --git a/src/green/dielectric_profile/MembraneTanh.hpp b/src/green/dielectric_profile/MembraneTanh.hpp index f97065080..997ac8306 100644 --- a/src/green/dielectric_profile/MembraneTanh.hpp +++ b/src/green/dielectric_profile/MembraneTanh.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -27,16 +27,16 @@ #include "Config.hpp" -/*! \file MembraneTanh.hpp - * \class MembraneTanh +/*! \file MembraneTanh.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \class MembraneTanh * \brief A dielectric profile mimicking a memmbrane as in Eq. 30 in \cite * Frediani2004a * \author Roberto Di Remigio * \date 2015 */ - -namespace pcm { -namespace dielectric_profile { class MembraneTanh { private: double epsilon1_; @@ -63,9 +63,29 @@ class MembraneTanh { factor_23 * (1 - std::pow(tanh_r_23, 2))); // first derivative of epsilon(r) } + std::ostream & printObject(std::ostream & os) { + os << "Profile functional form: tanh" << std::endl; + os << "Permittivity left-side = " << epsilon1_ << std::endl; + os << "Permittivity middle = " << epsilon2_ << std::endl; + os << "Permittivity right-side = " << epsilon3_ << std::endl; + os << "Profile width, 1st layer = " << width12_ << " AU" << std::endl; + os << "Profile width, 2nd layer = " << width23_ << " AU" << std::endl; + os << "Profile center, 1st layer = " << center12_ << " AU" << std::endl; + os << "Profile center, 2nd layer = " << center23_ << " AU"; + return os; + } public: MembraneTanh() {} + /*! Constructor for a two-layer interface (membrane) + * \param[in] e1 left-side dielectric constant + * \param[in] e2 middle portion dielectric constant + * \param[in] e3 right-side dielectric constant + * \param[in] w12 width of the first interface layer + * \param[in] w23 width of the second interface layer + * \param[in] c12 center of the first diffuse layer + * \param[in] c23 center of the second diffuse layer + */ MembraneTanh(double e1, double e2, double e3, @@ -76,19 +96,15 @@ class MembraneTanh { : epsilon1_(e1), epsilon2_(e2), epsilon3_(e3), - width12_(w12), - width23_(w23), + width12_(w12 / 6.0), + width23_(w23 / 6.0), center12_(c12), center23_(c23) {} - /*! The permittivity profile of the transition layer - * \param[out] e the value of the dielectric constant at point r - * \param[out] de the value of the derivative of the dielectric constant - * at point r + /*! Returns a tuple holding the permittivity and its derivative * \param[in] r evaluation point */ - void operator()(double & e, double & de, const double r) const { - e = value(r); - de = derivative(r); + pcm::tuple operator()(const double r) const { + return pcm::make_tuple(value(r), derivative(r)); } double epsilon1() const { return epsilon1_; } double epsilon2() const { return epsilon2_; } @@ -97,6 +113,9 @@ class MembraneTanh { double width23() const { return width23_; } double center12() const { return center12_; } double center23() const { return center23_; } + friend std::ostream & operator<<(std::ostream & os, MembraneTanh & th) { + return th.printObject(os); + } }; } // namespace dielectric_profile } // namespace pcm diff --git a/src/green/dielectric_profile/Metal.hpp b/src/green/dielectric_profile/Metal.hpp index facc9691e..0e38956e3 100644 --- a/src/green/dielectric_profile/Metal.hpp +++ b/src/green/dielectric_profile/Metal.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -28,15 +28,15 @@ #include "Config.hpp" -/*! \file Metal.hpp - * \struct Metal +/*! \file Metal.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \struct Metal * \brief An object with complex permittivity * \author Roberto Di Remigio * \date 2015 */ - -namespace pcm { -namespace dielectric_profile { struct Metal __final { std::complex epsilon; Metal() : epsilon(std::complex(1.0, 1.0)) {} diff --git a/src/green/dielectric_profile/OneLayerErf.hpp b/src/green/dielectric_profile/OneLayerErf.hpp index 0daae6b27..6579ec118 100644 --- a/src/green/dielectric_profile/OneLayerErf.hpp +++ b/src/green/dielectric_profile/OneLayerErf.hpp @@ -32,7 +32,7 @@ namespace pcm { namespace dielectric_profile { -/*! \class OneLayerErf +/*! \class OneLayerErf * \brief A erf dielectric profile * \author Roberto Di Remigio * \date 2015 diff --git a/src/green/dielectric_profile/OneLayerTanh.hpp b/src/green/dielectric_profile/OneLayerTanh.hpp index aaeb4a1db..82f20e459 100644 --- a/src/green/dielectric_profile/OneLayerTanh.hpp +++ b/src/green/dielectric_profile/OneLayerTanh.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -27,17 +27,17 @@ #include "Config.hpp" -/*! \file OneLayerTanh.hpp - * \class OneLayerTanh +/*! \file OneLayerTanh.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \class OneLayerTanh * \brief A tanh dielectric profile as in \cite Frediani2004a * \author Roberto Di Remigio * \date 2014 * \note The parameter given from user input for width_ is divided by 6.0 in * the constructor to keep consistency with \cite Frediani2004a */ - -namespace pcm { -namespace dielectric_profile { class OneLayerTanh { private: /// Dielectric constant on the left of the interface diff --git a/src/green/dielectric_profile/ProfileTypes.hpp b/src/green/dielectric_profile/ProfileTypes.hpp index 345919070..fbead12df 100644 --- a/src/green/dielectric_profile/ProfileTypes.hpp +++ b/src/green/dielectric_profile/ProfileTypes.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * diff --git a/src/green/dielectric_profile/Sharp.hpp b/src/green/dielectric_profile/Sharp.hpp index 53868057d..db4e10ae3 100644 --- a/src/green/dielectric_profile/Sharp.hpp +++ b/src/green/dielectric_profile/Sharp.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -27,15 +27,15 @@ #include "Config.hpp" -/*! \file Sharp.hpp - * \struct Sharp +/*! \file Sharp.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \struct Sharp * \brief A sharp dielectric separation * \author Roberto Di Remigio * \date 2015 */ - -namespace pcm { -namespace dielectric_profile { struct Sharp __final { double epsilon; double epsilonSolvent; diff --git a/src/green/dielectric_profile/Uniform.hpp b/src/green/dielectric_profile/Uniform.hpp index 913246a50..3db634f2f 100644 --- a/src/green/dielectric_profile/Uniform.hpp +++ b/src/green/dielectric_profile/Uniform.hpp @@ -1,4 +1,4 @@ -/** +/* * PCMSolver, an API for the Polarizable Continuum Model * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. * @@ -27,15 +27,15 @@ #include "Config.hpp" -/*! \file Uniform.hpp - * \struct Uniform +/*! \file Uniform.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \struct Uniform * \brief a uniform dielectric profile * \author Roberto Di Remigio * \date 2015 */ - -namespace pcm { -namespace dielectric_profile { struct Uniform __final { double epsilon; Uniform() : epsilon(1.0) {} diff --git a/src/green/dielectric_profile/Yukawa.hpp b/src/green/dielectric_profile/Yukawa.hpp index 2e29c43db..59261ce5e 100644 --- a/src/green/dielectric_profile/Yukawa.hpp +++ b/src/green/dielectric_profile/Yukawa.hpp @@ -27,15 +27,15 @@ #include "Config.hpp" -/*! \file Yukawa.hpp - * \struct Yukawa +/*! \file Yukawa.hpp */ + +namespace pcm { +namespace dielectric_profile { +/*! \struct Yukawa * \brief describes a medium with damping, i.e. ionic liquid * \author Roberto Di Remigio * \date 2015 */ - -namespace pcm { -namespace dielectric_profile { struct Yukawa __final { double epsilon; double kappa; From 7105750c91addb2a59bacc6e363acf471eb3850f Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Mon, 27 Nov 2017 12:04:17 -0500 Subject: [PATCH 19/28] Use Xcode 8gm --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 50323c905..944ca3d55 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,7 +57,7 @@ matrix: - RUN_DANGER=true - os: osx - osx_image: xcode7.3 + osx_image: xcode8 env: - CXX_COMPILER='clang++' - C_COMPILER='clang' @@ -68,7 +68,7 @@ matrix: - STATIC='--static' - RUN_DANGER=false - os: osx - osx_image: xcode7.3 + osx_image: xcode8 env: - CXX_COMPILER='g++-7' - C_COMPILER='gcc-7' From ef83c97762d82456aab6309da9e2ec8f5744f648 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Mon, 27 Nov 2017 13:05:41 -0500 Subject: [PATCH 20/28] Allow use of membrane profile --- .travis.yml | 4 +- src/green/AnisotropicLiquid.cpp | 5 +- src/green/AnisotropicLiquid.hpp | 2 +- src/green/GreensFunction.hpp | 4 +- src/green/IonicLiquid.cpp | 4 +- src/green/IonicLiquid.hpp | 2 +- src/green/SphericalDiffuse.cpp | 23 -------- src/green/SphericalDiffuse.hpp | 97 +++++++++++++++++++++++---------- src/green/UniformDielectric.cpp | 4 +- src/green/Vacuum.cpp | 5 +- src/green/Vacuum.hpp | 4 +- src/utils/cnpy.hpp | 1 + 12 files changed, 83 insertions(+), 72 deletions(-) diff --git a/.travis.yml b/.travis.yml index 944ca3d55..50323c905 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,7 +57,7 @@ matrix: - RUN_DANGER=true - os: osx - osx_image: xcode8 + osx_image: xcode7.3 env: - CXX_COMPILER='clang++' - C_COMPILER='clang' @@ -68,7 +68,7 @@ matrix: - STATIC='--static' - RUN_DANGER=false - os: osx - osx_image: xcode8 + osx_image: xcode7.3 env: - CXX_COMPILER='g++-7' - C_COMPILER='gcc-7' diff --git a/src/green/AnisotropicLiquid.cpp b/src/green/AnisotropicLiquid.cpp index 1e1702d17..12611d641 100644 --- a/src/green/AnisotropicLiquid.cpp +++ b/src/green/AnisotropicLiquid.cpp @@ -43,9 +43,8 @@ template AnisotropicLiquid::AnisotropicLiquid( const Eigen::Vector3d & eigen_eps, const Eigen::Vector3d & euler_ang) - : GreensFunction() { - this->profile_ = Anisotropic(eigen_eps, euler_ang); -} + : GreensFunction( + Anisotropic(eigen_eps, euler_ang)) {} template DerivativeTraits AnisotropicLiquid::operator()( diff --git a/src/green/AnisotropicLiquid.hpp b/src/green/AnisotropicLiquid.hpp index 13bb4aa81..50fc6af11 100644 --- a/src/green/AnisotropicLiquid.hpp +++ b/src/green/AnisotropicLiquid.hpp @@ -46,7 +46,6 @@ class Anisotropic; namespace pcm { namespace green { -template /*! \class AnisotropicLiquid * \brief Green's functions for anisotropic liquid, described by a tensorial * permittivity @@ -54,6 +53,7 @@ template * \date 2016 * \tparam DerivativeTraits evaluation strategy for the function and its derivatives */ +template class AnisotropicLiquid __final : public GreensFunction { public: diff --git a/src/green/GreensFunction.hpp b/src/green/GreensFunction.hpp index 76e494f8a..a10d6785b 100644 --- a/src/green/GreensFunction.hpp +++ b/src/green/GreensFunction.hpp @@ -49,7 +49,7 @@ template */ class GreensFunction : public IGreensFunction { public: - GreensFunction() : delta_(1.0e-04) {} + GreensFunction(const ProfilePolicy & p) : delta_(1.0e-04), profile_(p) {} virtual ~GreensFunction() {} /*! @{ Methods to sample the Green's function directional derivatives */ /*! Returns value of the directional derivative of the @@ -186,7 +186,7 @@ class GreensFunction : public IGreensFunction { template class GreensFunction : public IGreensFunction { public: - GreensFunction() : delta_(1.0e-04) {} + GreensFunction(const ProfilePolicy & p) : delta_(1.0e-04), profile_(p) {} virtual ~GreensFunction() {} /*! @{ Methods to sample the Green's function directional derivatives */ /*! Returns value of the directional derivative of the diff --git a/src/green/IonicLiquid.cpp b/src/green/IonicLiquid.cpp index 8ae6b1649..ca84725b2 100644 --- a/src/green/IonicLiquid.cpp +++ b/src/green/IonicLiquid.cpp @@ -41,9 +41,7 @@ using dielectric_profile::Yukawa; namespace green { template IonicLiquid::IonicLiquid(double eps, double k) - : GreensFunction() { - this->profile_ = Yukawa(eps, k); -} + : GreensFunction(Yukawa(eps, k)) {} template DerivativeTraits IonicLiquid::operator()( diff --git a/src/green/IonicLiquid.hpp b/src/green/IonicLiquid.hpp index 537122e39..eb02d8921 100644 --- a/src/green/IonicLiquid.hpp +++ b/src/green/IonicLiquid.hpp @@ -46,7 +46,6 @@ struct Yukawa; namespace pcm { namespace green { -template /*! \class IonicLiquid * \brief Green's functions for ionic liquid, described by the linearized * Poisson-Boltzmann equation. @@ -54,6 +53,7 @@ template * \date 2013-2016 * \tparam DerivativeTraits evaluation strategy for the function and its derivatives */ +template class IonicLiquid __final : public GreensFunction { public: diff --git a/src/green/SphericalDiffuse.cpp b/src/green/SphericalDiffuse.cpp index 6b13b95f8..bd0d44e42 100644 --- a/src/green/SphericalDiffuse.cpp +++ b/src/green/SphericalDiffuse.cpp @@ -41,21 +41,6 @@ namespace pcm { namespace green { -template -SphericalDiffuse::SphericalDiffuse(double e1, - double e2, - double w, - double c, - const Eigen::Vector3d & o, - int l) - : GreensFunction(), - origin_(o), - maxLGreen_(l), - maxLC_(2 * l) { - initProfilePolicy(e1, e2, w, c); - initSphericalDiffuse(); -} - template double SphericalDiffuse::coefficientCoulomb( const Eigen::Vector3d & source, @@ -250,14 +235,6 @@ std::ostream & SphericalDiffuse::printObject(std::ostream & os) { return os; } -template -void SphericalDiffuse::initProfilePolicy(double e1, - double e2, - double w, - double c) { - this->profile_ = ProfilePolicy(e1, e2, w, c); -} - template void SphericalDiffuse::initSphericalDiffuse() { using namespace detail; diff --git a/src/green/SphericalDiffuse.hpp b/src/green/SphericalDiffuse.hpp index 7e66cc4b7..3ebef8c53 100644 --- a/src/green/SphericalDiffuse.hpp +++ b/src/green/SphericalDiffuse.hpp @@ -24,6 +24,7 @@ #pragma once #include +#include #include "Config.hpp" @@ -38,6 +39,7 @@ class Element; namespace dielectric_profile { class OneLayerTanh; +class MembraneTanh; } // namespace dielectric_profile } // namespace pcm @@ -46,31 +48,27 @@ class OneLayerTanh; #include "InterfacesImpl.hpp" namespace pcm { -namespace green { -template +template +using IsSame = typename std::enable_if::value>::type; +template +using IsNotSame = typename std::enable_if::value>::type; +namespace green { /*! \class SphericalDiffuse * \brief Green's function for a diffuse interface with spherical symmetry * \author Hui Cao, Ville Weijo, Luca Frediani and Roberto Di Remigio * \date 2010-2015 * \tparam ProfilePolicy functional form of the diffuse layer * - * This class is general, in the sense that no specific dielectric profile has been - *set in its definition. - * In principle any profile that can be described by: - * 1. a left-side dielectric constant; - * 2. a right-side dielectric constant; - * 3. an interface layer width; - * 4. an interface layer center - * can be used to define a new diffuse interface with spherical symmetry. * The origin of the dielectric sphere can be changed by means of the constructor. * The solution of the differential equation defining the Green's function is - ***always** - * performed assuming that the dielectric sphere is centered in the origin of the - *coordinate - * system. Whenever the public methods are invoked to "sample" the Green's function + * **always** performed assuming that the dielectric sphere is centered in the + * origin of the + * coordinate system. Whenever the public methods are invoked to "sample" the + * Green's function * at a pair of points, a translation of the sampling points is performed first. */ +template class SphericalDiffuse __final : public GreensFunction { public: /*! Constructor for a one-layer interface @@ -80,13 +78,54 @@ class SphericalDiffuse __final : public GreensFunction { * \param[in] c center of the diffuse layer * \param[in] o center of the sphere * \param[in] l maximum value of angular momentum + * \note For SFINAE to work correctly, this constructor **must be** in the header + * file. */ + template > SphericalDiffuse(double e1, double e2, double w, double c, const Eigen::Vector3d & o, - int l); + int l) + : GreensFunction(ProfilePolicy(e1, e2, w, c)), + origin_(o), + maxLGreen_(l), + maxLC_(2 * l) { + initSphericalDiffuse(); + } + /*! Constructor for a two-layer interface (membrane) + * \param[in] e1 left-side dielectric constant + * \param[in] e2 middle portion dielectric constant + * \param[in] e3 right-side dielectric constant + * \param[in] w12 width of the first interface layer + * \param[in] w23 width of the second interface layer + * \param[in] c12 center of the first diffuse layer + * \param[in] c23 center of the second diffuse layer + * \param[in] o center of the sphere + * \param[in] l maximum value of angular momentum + * \note For SFINAE to work correctly, this constructor **must be** in the header + * file. + */ + template > + SphericalDiffuse(double e1, + double e2, + double e3, + double w12, + double w23, + double c12, + double c23, + const Eigen::Vector3d & o, + int l) + : GreensFunction( + ProfilePolicy(e1, e2, e3, w12, w23, c12, c23)), + origin_(o), + maxLGreen_(l), + maxLC_(2 * l) { + initSphericalDiffuse(); + } virtual ~SphericalDiffuse() {} friend std::ostream & operator<<(std::ostream & os, SphericalDiffuse & gf) { @@ -115,7 +154,8 @@ class SphericalDiffuse __final : public GreensFunction { * \f$ \nabla_{\mathbf{p_2}}G(\mathbf{p}_1, \mathbf{p}_2)\cdot *\mathbf{n}_{\mathbf{p}_2}\f$ * Notice that this method returns the directional derivative with respect - * to the probe point, thus assuming that the direction is relative to that point. + * to the probe point, thus assuming that the direction is relative to that + *point. * * \param[in] direction the direction * \param[in] p1 first point @@ -129,7 +169,8 @@ class SphericalDiffuse __final : public GreensFunction { * \f$ \nabla_{\mathbf{p_2}}G(\mathbf{p}_1, \mathbf{p}_2)\cdot *\mathbf{n}_{\mathbf{p}_2}\f$ * Notice that this method returns the directional derivative with respect - * to the probe point, thus assuming that the direction is relative to that point. + * to the probe point, thus assuming that the direction is relative to that + *point. * * \param[in] direction the direction * \param[in] p1 first point @@ -144,7 +185,8 @@ class SphericalDiffuse __final : public GreensFunction { * \f$ \nabla_{\mathbf{p_2}}G(\mathbf{p}_1, \mathbf{p}_2)\cdot *\mathbf{n}_{\mathbf{p}_2}\f$ * Notice that this method returns the directional derivative with respect - * to the probe point, thus assuming that the direction is relative to that point. + * to the probe point, thus assuming that the direction is relative to that + *point. * * \param[in] direction the direction * \param[in] p1 first point @@ -165,7 +207,8 @@ class SphericalDiffuse __final : public GreensFunction { * \note This takes care of the origin shift */ virtual Stencil operator()(Stencil * sp, Stencil * pp) const __override; - /*! Returns value of the kernel of the \f$\mathcal{D}\f$ integral operator for the + /*! Returns value of the kernel of the \f$\mathcal{D}\f$ integral operator for + * the * pair of points p1, p2: * \f$ [\boldsymbol{\varepsilon}\nabla_{\mathbf{p_2}}G(\mathbf{p}_1, * \mathbf{p}_2)]\cdot \mathbf{n}_{\mathbf{p}_2}\f$ @@ -189,13 +232,6 @@ class SphericalDiffuse __final : public GreensFunction { virtual double doubleLayer_impl(const Element & e, double factor) const __override; virtual std::ostream & printObject(std::ostream & os) __override; - /*! Initializes a one-layer profile - * \param[in] e1 left-side dielectric constant - * \param[in] e2 right-side dielectric constant - * \param[in] w width of the interface layer - * \param[in] c center of the diffuse layer - */ - void initProfilePolicy(double e1, double e2, double w, double c); /*! This calculates all the components needed to evaluate the Green's function */ void initSphericalDiffuse(); @@ -204,7 +240,8 @@ class SphericalDiffuse __final : public GreensFunction { /*! @{ Parameters and functions for the calculation of the Green's function, * including Coulomb singularity */ - /*! Maximum angular momentum in the __final summation over Legendre polynomials to + /*! Maximum angular momentum in the __final summation over Legendre polynomials + * to * obtain G */ int maxLGreen_; /*! \brief First independent radial solution, used to build Green's function. @@ -222,7 +259,8 @@ class SphericalDiffuse __final : public GreensFunction { * \param[in] sp source point * \param[in] pp probe point * \param[in] Cr12 Coulomb singularity separation coefficient - * \note This function shifts the given source and probe points by the location of + * \note This function shifts the given source and probe points by the location + * of * the * dielectric sphere. */ @@ -249,7 +287,8 @@ class SphericalDiffuse __final : public GreensFunction { /*! \brief Returns coefficient for the separation of the Coulomb singularity * \param[in] sp first point * \param[in] pp second point - * \note This function shifts the given source and probe points by the location of + * \note This function shifts the given source and probe points by the location + * of * the * dielectric sphere. */ diff --git a/src/green/UniformDielectric.cpp b/src/green/UniformDielectric.cpp index 69169477b..957679424 100644 --- a/src/green/UniformDielectric.cpp +++ b/src/green/UniformDielectric.cpp @@ -41,9 +41,7 @@ using dielectric_profile::Uniform; namespace green { template UniformDielectric::UniformDielectric(double eps) - : GreensFunction() { - this->profile_ = Uniform(eps); -} + : GreensFunction(Uniform(eps)) {} template DerivativeTraits UniformDielectric::operator()( diff --git a/src/green/Vacuum.cpp b/src/green/Vacuum.cpp index 8cfb36c87..5e953621f 100644 --- a/src/green/Vacuum.cpp +++ b/src/green/Vacuum.cpp @@ -39,9 +39,8 @@ using cavity::Element; using dielectric_profile::Uniform; namespace green { template -Vacuum::Vacuum() : GreensFunction() { - this->profile_ = Uniform(1.0); -} +Vacuum::Vacuum() + : GreensFunction(Uniform(1.0)) {} template DerivativeTraits Vacuum::operator()(DerivativeTraits * sp, diff --git a/src/green/Vacuum.hpp b/src/green/Vacuum.hpp index afa7d7d27..c6e9ff82f 100644 --- a/src/green/Vacuum.hpp +++ b/src/green/Vacuum.hpp @@ -28,6 +28,7 @@ #include "Config.hpp" #include + /*! \file Vacuum.hpp */ namespace pcm { @@ -46,8 +47,6 @@ struct Uniform; namespace pcm { namespace green { -template - /*! \class Vacuum * \brief Green's function for vacuum. * \author Luca Frediani and Roberto Di Remigio @@ -57,6 +56,7 @@ template // TODO: * I don't think the ProfilePolicy parameter is needed in this case! // * can we use enable_if (or similar tricks) to avoid implementing useless // functions? +template class Vacuum __final : public GreensFunction { public: diff --git a/src/utils/cnpy.hpp b/src/utils/cnpy.hpp index ce769d288..a31587a03 100644 --- a/src/utils/cnpy.hpp +++ b/src/utils/cnpy.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include From c0af86c8fc63b07ef2a5fc87047aa7d592923c0c Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Mon, 27 Nov 2017 15:10:22 -0500 Subject: [PATCH 21/28] Fix use of enable_if --- CHANGELOG.md | 7 ++- include/Cxx11Workarounds.hpp | 27 ++++++++++ src/green/SphericalDiffuse.cpp | 9 ++-- src/green/SphericalDiffuse.hpp | 10 +--- src/green/dielectric_profile/MembraneTanh.hpp | 38 +++++++++----- src/green/dielectric_profile/OneLayerErf.hpp | 25 +++++++--- src/green/dielectric_profile/OneLayerTanh.hpp | 27 +++++++--- tests/green/green_spherical_diffuse.cpp | 50 ++++++++++--------- 8 files changed, 129 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fc4298dc..23ac6fe68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,11 +26,14 @@ defining the type of object and to remove now unused information. - Documentation building is fully handled _via_ `sphinx-build`: CMake will no longer generate a `doc` build target. - Simplified `.travis.yml` and got rid of Conda to handle multiple Python versions. +- The [Catch unit test framework](https://github.com/philsquared/Catch) has + been updated to its latest version still supporting C++03 + [v1.11.0](https://github.com/philsquared/Catch/releases/tag/v1.11.0) ### Fixed -- Documentation building on ReadTheDocs is fully functional again, thanks @arnfinn :tada: - The build had been failing for a while since docs were generated for all files, including +- Documentation building on ReadTheDocs is fully functional again, thanks @arnfinn :tada: + The build had been failing for a while since docs were generated for all files, including documentation files from previous build. Besides, source code doxygen blocks were not exctracted when inside namespaces. diff --git a/include/Cxx11Workarounds.hpp b/include/Cxx11Workarounds.hpp index beb1ddfcb..7a36d97d2 100644 --- a/include/Cxx11Workarounds.hpp +++ b/include/Cxx11Workarounds.hpp @@ -75,6 +75,18 @@ using std::to_string; namespace pcm { using std::erf; } /* end namespace pcm */ +/* workarounds */ +#include +namespace pcm { +using std::enable_if; +using std::is_same; + +template +using IsSame = typename std::enable_if::value>::type; + +template +using IsNotSame = typename std::enable_if::value>::type; +} /* end namespace pcm */ #else /* HAS_CXX11*/ /* Smart pointers workarounds */ #include @@ -115,11 +127,26 @@ namespace pcm { template std::string to_string(const Source & arg) { return boost::lexical_cast(arg); } +} /* end namespace pcm */ /* workarounds */ #include namespace pcm { using boost::math::erf; } /* end namespace pcm */ +/* workarounds */ +#include +#include +namespace pcm { +using boost::enable_if; +using boost::is_same; + +template struct IsSame { + typedef boost::enable_if::value>::type; +}; + +template struct IsNotSame { + typedef boost::enable_if::value>::type; +}; } /* end namespace pcm */ #endif /* HAS_CXX11 */ diff --git a/src/green/SphericalDiffuse.cpp b/src/green/SphericalDiffuse.cpp index bd0d44e42..7ade536f4 100644 --- a/src/green/SphericalDiffuse.cpp +++ b/src/green/SphericalDiffuse.cpp @@ -246,9 +246,9 @@ void SphericalDiffuse::initSphericalDiffuse() { double factor_x_ = 0.0; /*! Weight of the state */ double factor_dxdt_ = 0.0; /*! Weight of the state derivative */ double r_0_ = 0.5; /*! Lower bound of the integration interval */ - double r_infinity_ = - this->profile_.center() + 200.0; /*! Upper bound of the integration interval */ - double observer_step_ = 1.0e-03; /*! Time step between observer calls */ + double r_infinity_ = this->profile_.upperLimit() + + 200.0; /*! Upper bound of the integration interval */ + double observer_step_ = 1.0e-03; /*! Time step between observer calls */ IntegratorParameters params_(eps_abs_, eps_rel_, factor_x_, @@ -416,5 +416,8 @@ template class SphericalDiffuse; using dielectric_profile::OneLayerErf; template class SphericalDiffuse; + +using dielectric_profile::MembraneTanh; +template class SphericalDiffuse; } // namespace green } // namespace pcm diff --git a/src/green/SphericalDiffuse.hpp b/src/green/SphericalDiffuse.hpp index 3ebef8c53..f38943d41 100644 --- a/src/green/SphericalDiffuse.hpp +++ b/src/green/SphericalDiffuse.hpp @@ -24,7 +24,6 @@ #pragma once #include -#include #include "Config.hpp" @@ -48,11 +47,6 @@ class MembraneTanh; #include "InterfacesImpl.hpp" namespace pcm { -template -using IsSame = typename std::enable_if::value>::type; - -template -using IsNotSame = typename std::enable_if::value>::type; namespace green { /*! \class SphericalDiffuse * \brief Green's function for a diffuse interface with spherical symmetry @@ -82,7 +76,7 @@ class SphericalDiffuse __final : public GreensFunction { * file. */ template > + typename = pcm::IsNotSame > SphericalDiffuse(double e1, double e2, double w, @@ -109,7 +103,7 @@ class SphericalDiffuse __final : public GreensFunction { * file. */ template > + typename = pcm::IsSame > SphericalDiffuse(double e1, double e2, double e3, diff --git a/src/green/dielectric_profile/MembraneTanh.hpp b/src/green/dielectric_profile/MembraneTanh.hpp index 997ac8306..bad84e315 100644 --- a/src/green/dielectric_profile/MembraneTanh.hpp +++ b/src/green/dielectric_profile/MembraneTanh.hpp @@ -24,6 +24,7 @@ #pragma once #include +#include #include "Config.hpp" @@ -46,22 +47,40 @@ class MembraneTanh { double width23_; double center12_; double center23_; + /*! Domain of the permittivity function + * This is formally \f$ [0, +\infty) \f$, for all practical purposes + * the permittivity function is equal to the epsilon3_ already at 6.0 * width23_ + * Thus the upper limit in the domain_ is initialized as center23_ + 12.0 * + * width23_ + */ + std::pair domain_; + /*! Returns value of dielectric profile at given point + * \param[in] point where to evaluate the profile + * \note We return epsilon3_ when the sampling point is outside the upper limit. + */ double value(double point) const { double eps_13 = (epsilon1_ + epsilon3_) / 2.0; double eps_21 = (epsilon2_ - epsilon1_) / 2.0; double eps_23 = (epsilon2_ - epsilon3_) / 2.0; double tanh_r_12 = std::tanh((point - center12_) / width12_); double tanh_r_23 = std::tanh((point - center23_) / width23_); - return (eps_13 + eps_21 * tanh_r_12 - eps_23 * tanh_r_23); // epsilon(r) + return (point > domain_.second) + ? epsilon3_ + : (eps_13 + eps_21 * tanh_r_12 - eps_23 * tanh_r_23); } + /*! Returns value of derivative of dielectric profile at given point + * \param[in] point where to evaluate the derivative + * \note We return 0.0 (derivative of the constant value epsilon3_) when the + * sampling point is outside the upper limit. + */ double derivative(double point) const { double factor_21 = (epsilon2_ - epsilon1_) / (2.0 * width12_); double factor_23 = (epsilon2_ - epsilon3_) / (2.0 * width23_); double tanh_r_12 = std::tanh((point - center12_) / width12_); double tanh_r_23 = std::tanh((point - center23_) / width23_); - return (factor_21 * (1 - std::pow(tanh_r_12, 2)) - - factor_23 * - (1 - std::pow(tanh_r_23, 2))); // first derivative of epsilon(r) + return (point > domain_.second) ? epsilon3_ + : (factor_21 * (1 - std::pow(tanh_r_12, 2)) - + factor_23 * (1 - std::pow(tanh_r_23, 2))); } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: tanh" << std::endl; @@ -99,20 +118,15 @@ class MembraneTanh { width12_(w12 / 6.0), width23_(w23 / 6.0), center12_(c12), - center23_(c23) {} + center23_(c23), + domain_(std::make_pair(0.0, center23_ + 12.0 * width23_)) {} /*! Returns a tuple holding the permittivity and its derivative * \param[in] r evaluation point */ pcm::tuple operator()(const double r) const { return pcm::make_tuple(value(r), derivative(r)); } - double epsilon1() const { return epsilon1_; } - double epsilon2() const { return epsilon2_; } - double epsilon3() const { return epsilon3_; } - double width12() const { return width12_; } - double width23() const { return width23_; } - double center12() const { return center12_; } - double center23() const { return center23_; } + double upperLimit() const { return domain_.second; } friend std::ostream & operator<<(std::ostream & os, MembraneTanh & th) { return th.printObject(os); } diff --git a/src/green/dielectric_profile/OneLayerErf.hpp b/src/green/dielectric_profile/OneLayerErf.hpp index 6579ec118..b3dff3655 100644 --- a/src/green/dielectric_profile/OneLayerErf.hpp +++ b/src/green/dielectric_profile/OneLayerErf.hpp @@ -25,6 +25,7 @@ #include #include +#include #include "Config.hpp" @@ -49,23 +50,32 @@ class OneLayerErf { double width_; /// Center of the transition layer double center_; + /*! Domain of the permittivity function + * This is formally \f$ [0, +\infty) \f$, for all practical purposes + * the permittivity function is equal to the epsilon2_ already at 6.0 * width_ + * Thus the upper limit in the domain_ is initialized as center_ + 12.0 * width_ + */ + std::pair domain_; /*! Returns value of dielectric profile at given point * \param[in] point where to evaluate the profile + * \note We return epsilon2_ when the sampling point is outside the upper limit. */ double value(double point) const { double epsPlus = (epsilon1_ + epsilon2_) / 2.0; double epsMinus = (epsilon2_ - epsilon1_) / 2.0; double val = pcm::erf((point - center_) / width_); - return (epsPlus + epsMinus * val); // epsilon(r) + return (point > domain_.second) ? epsilon2_ : (epsPlus + epsMinus * val); } /*! Returns value of derivative of dielectric profile at given point * \param[in] point where to evaluate the derivative + * \note We return 0.0 (derivative of the constant value epsilon2_) when the + * sampling point is outside the upper limit. */ double derivative(double point) const { double factor = (epsilon2_ - epsilon1_) / (width_ * std::sqrt(M_PI)); double t = (point - center_) / width_; double val = std::exp(-std::pow(t, 2)); - return (factor * val); // first derivative of epsilon(r) + return (point > domain_.second) ? 0.0 : (factor * val); } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: erf" << std::endl; @@ -79,17 +89,18 @@ class OneLayerErf { public: OneLayerErf() {} OneLayerErf(double e1, double e2, double w, double c) - : epsilon1_(e1), epsilon2_(e2), width_(w / 6.0), center_(c) {} + : epsilon1_(e1), + epsilon2_(e2), + width_(w / 6.0), + center_(c), + domain_(std::make_pair(0.0, center_ + 12.0 * width_)) {} /*! Returns a tuple holding the permittivity and its derivative * \param[in] r evaluation point */ pcm::tuple operator()(const double r) const { return pcm::make_tuple(value(r), derivative(r)); } - double epsilon1() const { return epsilon1_; } - double epsilon2() const { return epsilon2_; } - double width() const { return width_; } - double center() const { return center_; } + double upperLimit() const { return domain_.second; } friend std::ostream & operator<<(std::ostream & os, OneLayerErf & th) { return th.printObject(os); } diff --git a/src/green/dielectric_profile/OneLayerTanh.hpp b/src/green/dielectric_profile/OneLayerTanh.hpp index 82f20e459..1875ce583 100644 --- a/src/green/dielectric_profile/OneLayerTanh.hpp +++ b/src/green/dielectric_profile/OneLayerTanh.hpp @@ -24,6 +24,7 @@ #pragma once #include +#include #include "Config.hpp" @@ -31,7 +32,7 @@ namespace pcm { namespace dielectric_profile { -/*! \class OneLayerTanh +/*! \class OneLayerTanh * \brief A tanh dielectric profile as in \cite Frediani2004a * \author Roberto Di Remigio * \date 2014 @@ -48,22 +49,31 @@ class OneLayerTanh { double width_; /// Center of the transition layer double center_; + /*! Domain of the permittivity function + * This is formally \f$ [0, +\infty) \f$, for all practical purposes + * the permittivity function is equal to the epsilon2_ already at 6.0 * width_ + * Thus the upper limit in the domain_ is initialized as center_ + 12.0 * width_ + */ + std::pair domain_; /*! Returns value of dielectric profile at given point * \param[in] point where to evaluate the profile + * \note We return epsilon2_ when the sampling point is outside the upper limit. */ double value(double point) const { double epsPlus = (epsilon1_ + epsilon2_) / 2.0; double epsMinus = (epsilon2_ - epsilon1_) / 2.0; double tanh_r = std::tanh((point - center_) / width_); - return (epsPlus + epsMinus * tanh_r); // epsilon(r) + return (point > domain_.second) ? epsilon2_ : (epsPlus + epsMinus * tanh_r); } /*! Returns value of derivative of dielectric profile at given point * \param[in] point where to evaluate the derivative + * \note We return 0.0 (derivative of the constant value epsilon2_) when the + * sampling point is outside the upper limit. */ double derivative(double point) const { double factor = (epsilon2_ - epsilon1_) / (2.0 * width_); double tanh_r = std::tanh((point - center_) / width_); - return (factor * (1 - std::pow(tanh_r, 2))); // first derivative of epsilon(r) + return (point > domain_.second) ? 0.0 : (factor * (1 - std::pow(tanh_r, 2))); } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: tanh" << std::endl; @@ -77,17 +87,18 @@ class OneLayerTanh { public: OneLayerTanh() {} OneLayerTanh(double e1, double e2, double w, double c) - : epsilon1_(e1), epsilon2_(e2), width_(w / 6.0), center_(c) {} + : epsilon1_(e1), + epsilon2_(e2), + width_(w / 6.0), + center_(c), + domain_(std::make_pair(0.0, center_ + 12.0 * width_)) {} /*! Returns a tuple holding the permittivity and its derivative * \param[in] r evaluation point */ pcm::tuple operator()(const double r) const { return pcm::make_tuple(value(r), derivative(r)); } - double epsilon1() const { return epsilon1_; } - double epsilon2() const { return epsilon2_; } - double width() const { return width_; } - double center() const { return center_; } + double upperLimit() const { return domain_.second; } friend std::ostream & operator<<(std::ostream & os, OneLayerTanh & th) { return th.printObject(os); } diff --git a/tests/green/green_spherical_diffuse.cpp b/tests/green/green_spherical_diffuse.cpp index ba55ea854..56c5ab750 100644 --- a/tests/green/green_spherical_diffuse.cpp +++ b/tests/green/green_spherical_diffuse.cpp @@ -32,6 +32,7 @@ #include "green/DerivativeTypes.hpp" #include "green/SphericalDiffuse.hpp" +#include "green/dielectric_profile/MembraneTanh.hpp" #include "green/dielectric_profile/OneLayerErf.hpp" #include "green/dielectric_profile/OneLayerTanh.hpp" @@ -39,6 +40,7 @@ using namespace pcm; using green::SphericalDiffuse; using dielectric_profile::OneLayerErf; using dielectric_profile::OneLayerTanh; +using dielectric_profile::MembraneTanh; SCENARIO("Evaluation of the spherical diffuse Green's function and its derivatives", "[green][green_spherical_diffuse]") { @@ -68,7 +70,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ Eigen::Vector3d sphereCenter = Eigen::Vector3d::Zero(); SphericalDiffuse<> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL); THEN("the value of the Green's function inside the droplet is") { - double value = 0.012507311388168523; + double value = 0.0125073117820161759; double gf_value = gf.kernelS(source1, probe1); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -79,7 +81,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ REQUIRE(value == Approx(gf_value)); } AND_THEN("the value of the Green's function outside the droplet is") { - double value = 0.50004567416494572; + double value = 0.500045986670381581; double gf_value = gf.kernelS(source2, probe2); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -91,7 +93,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the probe " "point inside the droplet is") { - double derProbe = -0.012506305835640469; + double derProbe = -0.0125062279977827817; double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -103,7 +105,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "probe point outside the droplet is") { - double derProbe = -0.29005549287308696; + double derProbe = -0.290055591821714032; double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -115,7 +117,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the source " "point inside the droplet is") { - double derSource = 0.012498621932118328; + double derSource = 0.0124986222807023373; double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -127,7 +129,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "source point outside the droplet is") { - double derSource = 0.28879776627577236; + double derSource = 0.288797487450476176; double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -144,7 +146,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ (Eigen::Vector3d() << 25.0, 0.0, 0.0).finished(); SphericalDiffuse<> gf(eps1, eps2, width, sphereRadius, sphereCenter, maxL); THEN("the value of the Green's function inside the droplet is") { - double value = 0.0125233347669694017; + double value = 0.0125233347952455679; double gf_value = gf.kernelS(source1, probe1); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -155,7 +157,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ REQUIRE(value == Approx(gf_value)); } AND_THEN("the value of the Green's function outside the droplet is") { - double value = 0.5000329900631173; + double value = 0.500029014239111391; double gf_value = gf.kernelS(source2, probe2); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -167,7 +169,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the probe " "point inside the droplet is") { - double derProbe = -0.0125024363466751109; + double derProbe = -0.0125024378794594271; double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -179,7 +181,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "probe point outside the droplet is") { - double derProbe = -0.289999709125188243; + double derProbe = -0.289998406246272378; double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -191,7 +193,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the source " "point inside the droplet is") { - double derSource = 0.0124899030052444404; + double derSource = 0.0124899030161038094; double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -203,7 +205,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "source point outside the droplet is") { - double derSource = 0.288657584958107449; + double derSource = 0.288655902260792629; double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -243,7 +245,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ SphericalDiffuse gf( eps1, eps2, width, sphereRadius, sphereCenter, maxL); THEN("the value of the Green's function inside the droplet is") { - double value = 0.012507311377769814; + double value = 0.0125073115838534744; double gf_value = gf.kernelS(source1, probe1); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -254,7 +256,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ REQUIRE(value == Approx(gf_value)); } AND_THEN("the value of the Green's function outside the droplet is") { - double value = 0.49991229576650942; + double value = 0.499912361753220347; double gf_value = gf.kernelS(source2, probe2); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -266,7 +268,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the probe " "point inside the droplet is") { - double derProbe = -0.012506340818360315; + double derProbe = -0.0125062686709680876; double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -278,7 +280,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "probe point outside the droplet is") { - double derProbe = -0.28997553534915177; + double derProbe = -0.289975568501799064; double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -290,7 +292,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the source " "point inside the droplet is") { - double derSource = 0.012498621813619368; + double derSource = 0.0124986220027042266; double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -302,7 +304,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "source point outside the droplet is") { - double derSource = 0.28871292628573908; + double derSource = 0.288712932449142201; double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -320,7 +322,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ SphericalDiffuse gf( eps1, eps2, width, sphereRadius, sphereCenter, maxL); THEN("the value of the Green's function inside the droplet is") { - double value = 0.012523344896520634; + double value = 0.0125233447844991293; double gf_value = gf.kernelS(source1, probe1); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -331,7 +333,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ REQUIRE(value == Approx(gf_value)); } AND_THEN("the value of the Green's function outside the droplet is") { - double value = 0.49989736527661349; + double value = 0.499897402784606149; double gf_value = gf.kernelS(source2, probe2); INFO("ref_value = " << std::setprecision( std::numeric_limits::digits10) @@ -343,7 +345,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the probe " "point inside the droplet is") { - double derProbe = -0.012502439280500169; + double derProbe = -0.0125024373412441214; double gf_derProbe = gf.derivativeProbe(probeNormal1, source1, probe1); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -355,7 +357,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "probe point outside the droplet is") { - double derProbe = -0.28995345687399254; + double derProbe = -0.289953249665575452; double gf_derProbe = gf.derivativeProbe(probeNormal2, source2, probe2); INFO("ref_derProbe = " << std::setprecision(std::numeric_limits::digits10) @@ -367,7 +369,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } THEN("the value of the Green's function directional derivative wrt the source " "point inside the droplet is") { - double derSource = 0.012489903372303254; + double derSource = 0.0124899033273999371; double gf_derSource = gf.derivativeSource(sourceNormal1, source1, probe1); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) @@ -379,7 +381,7 @@ SCENARIO("Evaluation of the spherical diffuse Green's function and its derivativ } AND_THEN("the value of the Green's function directional derivative wrt the " "source point outside the droplet is") { - double derSource = 0.28869402146192158; + double derSource = 0.288694045107451558; double gf_derSource = gf.derivativeSource(sourceNormal2, source2, probe2); INFO("ref_derSource = " << std::setprecision(std::numeric_limits::digits10) From 394e330fbe5604806fb9d39c31670de689d27812 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Mon, 27 Nov 2017 21:28:46 -0500 Subject: [PATCH 22/28] Remove boost::variant and boost::any --- include/Cxx11Workarounds.hpp | 14 --- src/green/AnisotropicLiquid.hpp | 9 +- src/green/Green.hpp | 3 + src/green/GreensFunction.hpp | 21 ++--- src/green/IGreensFunction.hpp | 5 +- src/green/IonicLiquid.hpp | 9 +- src/green/SphericalDiffuse.cpp | 1 - src/green/SphericalDiffuse.hpp | 18 ++-- src/green/UniformDielectric.hpp | 8 +- src/green/Vacuum.hpp | 9 +- src/green/dielectric_profile/CMakeLists.txt | 2 +- src/green/dielectric_profile/MembraneTanh.hpp | 41 +++++---- src/green/dielectric_profile/OneLayerErf.hpp | 30 +++++-- src/green/dielectric_profile/OneLayerTanh.hpp | 28 ++++-- src/green/dielectric_profile/ProfileTypes.hpp | 87 ------------------- src/solver/CPCMSolver.cpp | 2 +- src/solver/IEFSolver.cpp | 3 +- src/utils/cnpy.hpp | 1 - tests/cpcm/cpcm_gepol-C2H4_D2h.cpp | 1 + tests/cpcm/cpcm_gepol-H2O.cpp | 1 + tests/cpcm/cpcm_gepol-NH3.cpp | 1 + tests/cpcm/cpcm_gepol-point.cpp | 1 + 22 files changed, 118 insertions(+), 177 deletions(-) delete mode 100644 src/green/dielectric_profile/ProfileTypes.hpp diff --git a/include/Cxx11Workarounds.hpp b/include/Cxx11Workarounds.hpp index 7a36d97d2..2a15ec9ee 100644 --- a/include/Cxx11Workarounds.hpp +++ b/include/Cxx11Workarounds.hpp @@ -80,12 +80,6 @@ using std::erf; namespace pcm { using std::enable_if; using std::is_same; - -template -using IsSame = typename std::enable_if::value>::type; - -template -using IsNotSame = typename std::enable_if::value>::type; } /* end namespace pcm */ #else /* HAS_CXX11*/ /* Smart pointers workarounds */ @@ -139,14 +133,6 @@ using boost::math::erf; namespace pcm { using boost::enable_if; using boost::is_same; - -template struct IsSame { - typedef boost::enable_if::value>::type; -}; - -template struct IsNotSame { - typedef boost::enable_if::value>::type; -}; } /* end namespace pcm */ #endif /* HAS_CXX11 */ diff --git a/src/green/AnisotropicLiquid.hpp b/src/green/AnisotropicLiquid.hpp index 50fc6af11..9ec9882bb 100644 --- a/src/green/AnisotropicLiquid.hpp +++ b/src/green/AnisotropicLiquid.hpp @@ -35,14 +35,11 @@ namespace pcm { namespace cavity { class Element; } // namespace cavity - -namespace dielectric_profile { -class Anisotropic; -} // namespace dielectric_profile } // namespace pcm #include "GreenData.hpp" #include "GreensFunction.hpp" +#include "dielectric_profile/Anisotropic.hpp" namespace pcm { namespace green { @@ -64,6 +61,10 @@ class AnisotropicLiquid __final const Eigen::Vector3d & euler_ang); virtual ~AnisotropicLiquid() {} + virtual double permittivity() const __override __final { + PCMSOLVER_ERROR("permittivity() only implemented for uniform dielectrics"); + } + friend std::ostream & operator<<(std::ostream & os, AnisotropicLiquid & gf) { return gf.printObject(os); } diff --git a/src/green/Green.hpp b/src/green/Green.hpp index d601d7302..bc25c1349 100644 --- a/src/green/Green.hpp +++ b/src/green/Green.hpp @@ -33,6 +33,9 @@ #include "SphericalDiffuse.hpp" #include "UniformDielectric.hpp" #include "Vacuum.hpp" +#include "dielectric_profile/MembraneTanh.hpp" +#include "dielectric_profile/OneLayerErf.hpp" +#include "dielectric_profile/OneLayerTanh.hpp" #include "utils/Factory.hpp" /*! diff --git a/src/green/GreensFunction.hpp b/src/green/GreensFunction.hpp index a10d6785b..4015ed729 100644 --- a/src/green/GreensFunction.hpp +++ b/src/green/GreensFunction.hpp @@ -32,14 +32,13 @@ #include "DerivativeTypes.hpp" #include "IGreensFunction.hpp" +#include "dielectric_profile/Uniform.hpp" #include "utils/Stencils.hpp" /*! \file GreensFunction.hpp */ namespace pcm { namespace green { -template - /*! \class GreensFunction * \brief Templated interface for Green's functions * \author Luca Frediani and Roberto Di Remigio @@ -47,6 +46,7 @@ template * \tparam DerivativeTraits evaluation strategy for the function and its derivatives * \tparam ProfilePolicy dielectric profile type */ +template class GreensFunction : public IGreensFunction { public: GreensFunction(const ProfilePolicy & p) : delta_(1.0e-04), profile_(p) {} @@ -135,11 +135,7 @@ class GreensFunction : public IGreensFunction { /*! Whether the Green's function describes a uniform environment */ virtual bool uniform() const __final __override { - return dielectric_profile::uniform(this->profile_); - } - /*! Returns a dielectric permittivity profile */ - virtual Permittivity permittivity() const __final __override { - return this->profile_; + return pcm::is_same::value; } friend std::ostream & operator<<(std::ostream & os, GreensFunction & gf) { @@ -266,13 +262,12 @@ class GreensFunction : public IGreensFunction { } /*! @}*/ - /*! Whether the Green's function describes a uniform environment */ + /*! \return Whether the Green's function describes a uniform environment + * \note This uses is_same to check whether the type of ProfilePolicy is uniform + * not. + */ virtual bool uniform() const __final __override { - return dielectric_profile::uniform(this->profile_); - } - /*! Returns a dielectric permittivity profile */ - virtual Permittivity permittivity() const __final __override { - return this->profile_; + return pcm::is_same::value; } friend std::ostream & operator<<(std::ostream & os, GreensFunction & gf) { diff --git a/src/green/IGreensFunction.hpp b/src/green/IGreensFunction.hpp index 9dc5060ec..20c8ca57c 100644 --- a/src/green/IGreensFunction.hpp +++ b/src/green/IGreensFunction.hpp @@ -38,11 +38,8 @@ class Element; } // namespace green } // namespace pcm -#include "dielectric_profile/ProfileTypes.hpp" - namespace pcm { using cavity::Element; -using dielectric_profile::Permittivity; /*! \typedef KernelS * \brief functor handle to the kernelS method */ @@ -131,7 +128,7 @@ class IGreensFunction { /*! Whether the Green's function describes a uniform environment */ virtual bool uniform() const = 0; /*! Returns a dielectric permittivity profile */ - virtual Permittivity permittivity() const = 0; + virtual double permittivity() const = 0; /*! @{ Methods to compute the diagonal of the matrix representation of the S and D * operators by approximate collocation. */ diff --git a/src/green/IonicLiquid.hpp b/src/green/IonicLiquid.hpp index eb02d8921..573e0dad7 100644 --- a/src/green/IonicLiquid.hpp +++ b/src/green/IonicLiquid.hpp @@ -35,14 +35,11 @@ namespace pcm { namespace cavity { class Element; } // namespace cavity - -namespace dielectric_profile { -struct Yukawa; -} // namespace dielectric_profile } // namespace pcm #include "GreenData.hpp" #include "GreensFunction.hpp" +#include "dielectric_profile/Yukawa.hpp" namespace pcm { namespace green { @@ -60,6 +57,10 @@ class IonicLiquid __final IonicLiquid(double eps, double k); virtual ~IonicLiquid() {} + virtual double permittivity() const __override __final { + PCMSOLVER_ERROR("permittivity() only implemented for uniform dielectrics"); + } + friend std::ostream & operator<<(std::ostream & os, IonicLiquid & gf) { return gf.printObject(os); } diff --git a/src/green/SphericalDiffuse.cpp b/src/green/SphericalDiffuse.cpp index 7ade536f4..476a11c30 100644 --- a/src/green/SphericalDiffuse.cpp +++ b/src/green/SphericalDiffuse.cpp @@ -35,7 +35,6 @@ #include "GreenData.hpp" #include "GreensFunction.hpp" #include "cavity/Element.hpp" -#include "dielectric_profile/ProfileTypes.hpp" #include "utils/Legendre.hpp" #include "utils/MathUtils.hpp" diff --git a/src/green/SphericalDiffuse.hpp b/src/green/SphericalDiffuse.hpp index f38943d41..bab227e4d 100644 --- a/src/green/SphericalDiffuse.hpp +++ b/src/green/SphericalDiffuse.hpp @@ -35,16 +35,14 @@ namespace pcm { namespace cavity { class Element; } // namespace cavity - -namespace dielectric_profile { -class OneLayerTanh; -class MembraneTanh; -} // namespace dielectric_profile } // namespace pcm #include "GreenData.hpp" #include "GreensFunction.hpp" #include "InterfacesImpl.hpp" +#include "dielectric_profile/MembraneTanh.hpp" +#include "dielectric_profile/OneLayerErf.hpp" +#include "dielectric_profile/OneLayerTanh.hpp" namespace pcm { namespace green { @@ -76,7 +74,8 @@ class SphericalDiffuse __final : public GreensFunction { * file. */ template > + typename = typename pcm::enable_if< + !pcm::is_same::value>::type> SphericalDiffuse(double e1, double e2, double w, @@ -103,7 +102,8 @@ class SphericalDiffuse __final : public GreensFunction { * file. */ template > + typename = typename pcm::enable_if< + pcm::is_same::value>::type> SphericalDiffuse(double e1, double e2, double e3, @@ -122,6 +122,10 @@ class SphericalDiffuse __final : public GreensFunction { } virtual ~SphericalDiffuse() {} + virtual double permittivity() const __override __final { + PCMSOLVER_ERROR("permittivity() only implemented for uniform dielectrics"); + } + friend std::ostream & operator<<(std::ostream & os, SphericalDiffuse & gf) { return gf.printObject(os); } diff --git a/src/green/UniformDielectric.hpp b/src/green/UniformDielectric.hpp index 1f66009d1..94092837d 100644 --- a/src/green/UniformDielectric.hpp +++ b/src/green/UniformDielectric.hpp @@ -35,13 +35,11 @@ namespace pcm { namespace cavity { class Element; } // namespace cavity -namespace dielectric_profile { -struct Uniform; -} // namespace dielectric_profile } // namespace pcm #include "GreenData.hpp" #include "GreensFunction.hpp" +#include "dielectric_profile/Uniform.hpp" namespace pcm { namespace green { @@ -58,7 +56,9 @@ class UniformDielectric __final UniformDielectric(double eps); virtual ~UniformDielectric() {} - double epsilon() const { return this->profile_.epsilon; } + virtual double permittivity() const __override __final { + return this->profile_.epsilon; + } friend std::ostream & operator<<(std::ostream & os, UniformDielectric & gf) { return gf.printObject(os); diff --git a/src/green/Vacuum.hpp b/src/green/Vacuum.hpp index c6e9ff82f..53d2960c6 100644 --- a/src/green/Vacuum.hpp +++ b/src/green/Vacuum.hpp @@ -36,14 +36,11 @@ struct GreenData; namespace cavity { class Element; } // namespace cavity - -namespace dielectric_profile { -struct Uniform; -} // namespace dielectric_profile } // namespace pcm #include "DerivativeTypes.hpp" #include "GreensFunction.hpp" +#include "dielectric_profile/Uniform.hpp" namespace pcm { namespace green { @@ -63,6 +60,10 @@ class Vacuum __final Vacuum(); virtual ~Vacuum() {} + virtual double permittivity() const __override __final { + return this->profile_.epsilon; + } + friend std::ostream & operator<<(std::ostream & os, Vacuum & gf) { return gf.printObject(os); } diff --git a/src/green/dielectric_profile/CMakeLists.txt b/src/green/dielectric_profile/CMakeLists.txt index 4abf423ab..2080a7769 100644 --- a/src/green/dielectric_profile/CMakeLists.txt +++ b/src/green/dielectric_profile/CMakeLists.txt @@ -1,5 +1,5 @@ # List of headers -list(APPEND _headers_list Anisotropic.hpp MembraneTanh.hpp Metal.hpp OneLayerErf.hpp OneLayerTanh.hpp ProfileTypes.hpp Sharp.hpp Uniform.hpp Yukawa.hpp) +list(APPEND _headers_list Anisotropic.hpp MembraneTanh.hpp Metal.hpp OneLayerErf.hpp OneLayerTanh.hpp Sharp.hpp Uniform.hpp Yukawa.hpp) # Sets install directory for all the headers in the list foreach(_header ${_headers_list}) diff --git a/src/green/dielectric_profile/MembraneTanh.hpp b/src/green/dielectric_profile/MembraneTanh.hpp index bad84e315..740aa88e7 100644 --- a/src/green/dielectric_profile/MembraneTanh.hpp +++ b/src/green/dielectric_profile/MembraneTanh.hpp @@ -59,14 +59,20 @@ class MembraneTanh { * \note We return epsilon3_ when the sampling point is outside the upper limit. */ double value(double point) const { - double eps_13 = (epsilon1_ + epsilon3_) / 2.0; - double eps_21 = (epsilon2_ - epsilon1_) / 2.0; - double eps_23 = (epsilon2_ - epsilon3_) / 2.0; - double tanh_r_12 = std::tanh((point - center12_) / width12_); - double tanh_r_23 = std::tanh((point - center23_) / width23_); - return (point > domain_.second) - ? epsilon3_ - : (eps_13 + eps_21 * tanh_r_12 - eps_23 * tanh_r_23); + double retval = 0.0; + if (point < domain_.first) { + retval = epsilon1_; + } else if (point > domain_.second) { + retval = epsilon3_; + } else { + double eps_13 = (epsilon1_ + epsilon3_) / 2.0; + double eps_21 = (epsilon2_ - epsilon1_) / 2.0; + double eps_23 = (epsilon2_ - epsilon3_) / 2.0; + double tanh_r_12 = std::tanh((point - center12_) / width12_); + double tanh_r_23 = std::tanh((point - center23_) / width23_); + retval = eps_13 + eps_21 * tanh_r_12 - eps_23 * tanh_r_23; + } + return retval; } /*! Returns value of derivative of dielectric profile at given point * \param[in] point where to evaluate the derivative @@ -74,13 +80,18 @@ class MembraneTanh { * sampling point is outside the upper limit. */ double derivative(double point) const { - double factor_21 = (epsilon2_ - epsilon1_) / (2.0 * width12_); - double factor_23 = (epsilon2_ - epsilon3_) / (2.0 * width23_); - double tanh_r_12 = std::tanh((point - center12_) / width12_); - double tanh_r_23 = std::tanh((point - center23_) / width23_); - return (point > domain_.second) ? epsilon3_ - : (factor_21 * (1 - std::pow(tanh_r_12, 2)) - - factor_23 * (1 - std::pow(tanh_r_23, 2))); + double retval = 0.0; + if (point < domain_.first || point > domain_.second) { + retval = 0.0; + } else { + double factor_21 = (epsilon2_ - epsilon1_) / (2.0 * width12_); + double factor_23 = (epsilon2_ - epsilon3_) / (2.0 * width23_); + double tanh_r_12 = std::tanh((point - center12_) / width12_); + double tanh_r_23 = std::tanh((point - center23_) / width23_); + retval = factor_21 * (1 - std::pow(tanh_r_12, 2)) - + factor_23 * (1 - std::pow(tanh_r_23, 2)); + } + return retval; } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: tanh" << std::endl; diff --git a/src/green/dielectric_profile/OneLayerErf.hpp b/src/green/dielectric_profile/OneLayerErf.hpp index b3dff3655..7648a64c4 100644 --- a/src/green/dielectric_profile/OneLayerErf.hpp +++ b/src/green/dielectric_profile/OneLayerErf.hpp @@ -61,10 +61,18 @@ class OneLayerErf { * \note We return epsilon2_ when the sampling point is outside the upper limit. */ double value(double point) const { - double epsPlus = (epsilon1_ + epsilon2_) / 2.0; - double epsMinus = (epsilon2_ - epsilon1_) / 2.0; - double val = pcm::erf((point - center_) / width_); - return (point > domain_.second) ? epsilon2_ : (epsPlus + epsMinus * val); + double retval = 0.0; + if (point < domain_.first) { + retval = epsilon1_; + } else if (point > domain_.second) { + retval = epsilon2_; + } else { + double epsPlus = (epsilon1_ + epsilon2_) / 2.0; + double epsMinus = (epsilon2_ - epsilon1_) / 2.0; + double val = pcm::erf((point - center_) / width_); + retval = epsPlus + epsMinus * val; + } + return retval; } /*! Returns value of derivative of dielectric profile at given point * \param[in] point where to evaluate the derivative @@ -72,10 +80,16 @@ class OneLayerErf { * sampling point is outside the upper limit. */ double derivative(double point) const { - double factor = (epsilon2_ - epsilon1_) / (width_ * std::sqrt(M_PI)); - double t = (point - center_) / width_; - double val = std::exp(-std::pow(t, 2)); - return (point > domain_.second) ? 0.0 : (factor * val); + double retval = 0.0; + if (point < domain_.first || point > domain_.second) { + retval = 0.0; + } else { + double factor = (epsilon2_ - epsilon1_) / (width_ * std::sqrt(M_PI)); + double t = (point - center_) / width_; + double val = std::exp(-std::pow(t, 2)); + retval = factor * val; + } + return retval; } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: erf" << std::endl; diff --git a/src/green/dielectric_profile/OneLayerTanh.hpp b/src/green/dielectric_profile/OneLayerTanh.hpp index 1875ce583..ef958e2e1 100644 --- a/src/green/dielectric_profile/OneLayerTanh.hpp +++ b/src/green/dielectric_profile/OneLayerTanh.hpp @@ -60,10 +60,18 @@ class OneLayerTanh { * \note We return epsilon2_ when the sampling point is outside the upper limit. */ double value(double point) const { - double epsPlus = (epsilon1_ + epsilon2_) / 2.0; - double epsMinus = (epsilon2_ - epsilon1_) / 2.0; - double tanh_r = std::tanh((point - center_) / width_); - return (point > domain_.second) ? epsilon2_ : (epsPlus + epsMinus * tanh_r); + double retval = 0.0; + if (point < domain_.first) { + retval = epsilon1_; + } else if (point > domain_.second) { + retval = epsilon2_; + } else { + double epsPlus = (epsilon1_ + epsilon2_) / 2.0; + double epsMinus = (epsilon2_ - epsilon1_) / 2.0; + double tanh_r = std::tanh((point - center_) / width_); + retval = epsPlus + epsMinus * tanh_r; + } + return retval; } /*! Returns value of derivative of dielectric profile at given point * \param[in] point where to evaluate the derivative @@ -71,9 +79,15 @@ class OneLayerTanh { * sampling point is outside the upper limit. */ double derivative(double point) const { - double factor = (epsilon2_ - epsilon1_) / (2.0 * width_); - double tanh_r = std::tanh((point - center_) / width_); - return (point > domain_.second) ? 0.0 : (factor * (1 - std::pow(tanh_r, 2))); + double retval = 0.0; + if (point < domain_.first || point > domain_.second) { + retval = 0.0; + } else { + double factor = (epsilon2_ - epsilon1_) / (2.0 * width_); + double tanh_r = std::tanh((point - center_) / width_); + retval = factor * (1 - std::pow(tanh_r, 2)); + } + return retval; } std::ostream & printObject(std::ostream & os) { os << "Profile functional form: tanh" << std::endl; diff --git a/src/green/dielectric_profile/ProfileTypes.hpp b/src/green/dielectric_profile/ProfileTypes.hpp deleted file mode 100644 index fbead12df..000000000 --- a/src/green/dielectric_profile/ProfileTypes.hpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * PCMSolver, an API for the Polarizable Continuum Model - * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. - * - * This file is part of PCMSolver. - * - * PCMSolver is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PCMSolver is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with PCMSolver. If not, see . - * - * For information on the complete list of contributors to the - * PCMSolver API, see: - */ - -#pragma once - -#include "Config.hpp" - -#include -#include - -#include "Anisotropic.hpp" -#include "MembraneTanh.hpp" -#include "Metal.hpp" -#include "OneLayerErf.hpp" -#include "OneLayerTanh.hpp" -#include "Sharp.hpp" -#include "Uniform.hpp" -#include "Yukawa.hpp" - -namespace pcm { -namespace dielectric_profile { -/*! An object of Permittivity type can have one of the dielectric_profile types */ -typedef boost::variant - Permittivity; - -class isUniform : public boost::static_visitor { -public: - bool operator()(const Uniform & /* arg */) const { return true; } - bool operator()(const Yukawa & /* arg */) const { return false; } - bool operator()(const Anisotropic & /* arg */) const { return false; } - bool operator()(const OneLayerTanh & /* arg */) const { return false; } - bool operator()(const OneLayerErf & /* arg */) const { return false; } - bool operator()(const MembraneTanh & /* arg */) const { return false; } - bool operator()(const Metal & /* arg */) const { return false; } - bool operator()(const Sharp & /* arg */) const { return false; } -}; - -inline bool uniform(const Permittivity & arg) { - return boost::apply_visitor(isUniform(), arg); -} - -class epsilonValue : public boost::static_visitor { -public: - double operator()(const Uniform & arg) const { return arg.epsilon; } - pcm::tuple operator()(const Yukawa & arg) const { - return pcm::make_tuple(arg.epsilon, arg.kappa); - } - bool operator()(const Anisotropic & /* arg */) const { return false; } - bool operator()(const OneLayerTanh & /* arg */) const { return false; } - bool operator()(const OneLayerErf & /* arg */) const { return false; } - bool operator()(const MembraneTanh & /* arg */) const { return false; } - std::complex operator()(const Metal & arg) const { return arg.epsilon; } - double operator()(const Sharp & arg) const { return arg.epsilon; } -}; - -inline double epsilon(const Permittivity & arg) { - return boost::any_cast(boost::apply_visitor(epsilonValue(), arg)); -} -} // namespace dielectric_profile -} // namespace pcm diff --git a/src/solver/CPCMSolver.cpp b/src/solver/CPCMSolver.cpp index 0e8265c09..c2e82ef15 100644 --- a/src/solver/CPCMSolver.cpp +++ b/src/solver/CPCMSolver.cpp @@ -48,7 +48,7 @@ void CPCMSolver::buildSystemMatrix_impl(const ICavity & cavity, if (!isotropic_) PCMSOLVER_ERROR("C-PCM is defined only for isotropic environments!"); TIMER_ON("Computing S"); - double epsilon = dielectric_profile::epsilon(gf_o.permittivity()); + double epsilon = gf_o.permittivity(); S_ = op.computeS(cavity, gf_i); S_ /= (epsilon - 1.0) / (epsilon + correction_); // Get in Hermitian form diff --git a/src/solver/IEFSolver.cpp b/src/solver/IEFSolver.cpp index 6feaa5847..a83830d51 100644 --- a/src/solver/IEFSolver.cpp +++ b/src/solver/IEFSolver.cpp @@ -76,8 +76,7 @@ void IEFSolver::buildIsotropicMatrix(const ICavity & cav, const IGreensFunction & gf_i, const IGreensFunction & gf_o, const IBoundaryIntegralOperator & op) { - Tepsilon_ = detail::isotropicTEpsilon( - cav, gf_i, dielectric_profile::epsilon(gf_o.permittivity()), op); + Tepsilon_ = detail::isotropicTEpsilon(cav, gf_i, gf_o.permittivity(), op); Rinfinity_ = detail::isotropicRinfinity(cav, gf_i, op); // Pack into a block diagonal matrix diff --git a/src/utils/cnpy.hpp b/src/utils/cnpy.hpp index a31587a03..ce769d288 100644 --- a/src/utils/cnpy.hpp +++ b/src/utils/cnpy.hpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/cpcm/cpcm_gepol-C2H4_D2h.cpp b/tests/cpcm/cpcm_gepol-C2H4_D2h.cpp index ad29fec2b..2d9aa748d 100644 --- a/tests/cpcm/cpcm_gepol-C2H4_D2h.cpp +++ b/tests/cpcm/cpcm_gepol-C2H4_D2h.cpp @@ -35,6 +35,7 @@ #include "green/UniformDielectric.hpp" #include "green/Vacuum.hpp" #include "solver/CPCMSolver.hpp" +#include "utils/MathUtils.hpp" #include "utils/Molecule.hpp" using namespace pcm; diff --git a/tests/cpcm/cpcm_gepol-H2O.cpp b/tests/cpcm/cpcm_gepol-H2O.cpp index aa8d0f8bb..47ede8a0f 100644 --- a/tests/cpcm/cpcm_gepol-H2O.cpp +++ b/tests/cpcm/cpcm_gepol-H2O.cpp @@ -34,6 +34,7 @@ #include "green/UniformDielectric.hpp" #include "green/Vacuum.hpp" #include "solver/CPCMSolver.hpp" +#include "utils/MathUtils.hpp" #include "utils/Molecule.hpp" #include "utils/Symmetry.hpp" diff --git a/tests/cpcm/cpcm_gepol-NH3.cpp b/tests/cpcm/cpcm_gepol-NH3.cpp index c20562eb1..748bd63cd 100644 --- a/tests/cpcm/cpcm_gepol-NH3.cpp +++ b/tests/cpcm/cpcm_gepol-NH3.cpp @@ -34,6 +34,7 @@ #include "green/UniformDielectric.hpp" #include "green/Vacuum.hpp" #include "solver/CPCMSolver.hpp" +#include "utils/MathUtils.hpp" #include "utils/Molecule.hpp" #include "utils/Symmetry.hpp" diff --git a/tests/cpcm/cpcm_gepol-point.cpp b/tests/cpcm/cpcm_gepol-point.cpp index f9e042158..59c3d4693 100644 --- a/tests/cpcm/cpcm_gepol-point.cpp +++ b/tests/cpcm/cpcm_gepol-point.cpp @@ -34,6 +34,7 @@ #include "green/UniformDielectric.hpp" #include "green/Vacuum.hpp" #include "solver/CPCMSolver.hpp" +#include "utils/MathUtils.hpp" using namespace pcm; using bi_operators::Collocation; From fd7fb7bc02f8e730032d4ebafb2eef40bfd6ebf8 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Tue, 28 Nov 2017 11:09:28 -0500 Subject: [PATCH 23/28] Devirtualize two functions --- src/green/GreensFunction.hpp | 24 ++++++++++++------------ src/green/IGreensFunction.hpp | 2 +- src/utils/MathUtils.hpp | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/green/GreensFunction.hpp b/src/green/GreensFunction.hpp index 4015ed729..bbe90eb11 100644 --- a/src/green/GreensFunction.hpp +++ b/src/green/GreensFunction.hpp @@ -62,9 +62,9 @@ class GreensFunction : public IGreensFunction { * \param[in] p1 first point * \param[in] p2 second point */ - virtual double derivativeSource(const Eigen::Vector3d & normal_p1, - const Eigen::Vector3d & p1, - const Eigen::Vector3d & p2) const { + double derivativeSource(const Eigen::Vector3d & normal_p1, + const Eigen::Vector3d & p1, + const Eigen::Vector3d & p2) const { DerivativeTraits t1[3], t2[3]; t1[0] = p1(0); t1[1] = p1(1); @@ -87,9 +87,9 @@ class GreensFunction : public IGreensFunction { * \param[in] p1 first point * \param[in] p2 second point */ - virtual double derivativeProbe(const Eigen::Vector3d & normal_p2, - const Eigen::Vector3d & p1, - const Eigen::Vector3d & p2) const __final { + double derivativeProbe(const Eigen::Vector3d & normal_p2, + const Eigen::Vector3d & p1, + const Eigen::Vector3d & p2) const { DerivativeTraits t1[3], t2[3]; t1[0] = p1(0); t1[1] = p1(1); @@ -195,9 +195,9 @@ class GreensFunction : public IGreensFunction { * \param[in] p1 first point * \param[in] p2 second point */ - virtual double derivativeSource(const Eigen::Vector3d & normal_p1, - const Eigen::Vector3d & p1, - const Eigen::Vector3d & p2) const { + double derivativeSource(const Eigen::Vector3d & normal_p1, + const Eigen::Vector3d & p1, + const Eigen::Vector3d & p2) const { return threePointStencil( pcm::bind(&GreensFunction::kernelS, this, @@ -218,9 +218,9 @@ class GreensFunction : public IGreensFunction { * \param[in] p1 first point * \param[in] p2 second point */ - virtual double derivativeProbe(const Eigen::Vector3d & normal_p2, - const Eigen::Vector3d & p1, - const Eigen::Vector3d & p2) const __final { + double derivativeProbe(const Eigen::Vector3d & normal_p2, + const Eigen::Vector3d & p1, + const Eigen::Vector3d & p2) const { return threePointStencil( pcm::bind(&GreensFunction::kernelS, this, diff --git a/src/green/IGreensFunction.hpp b/src/green/IGreensFunction.hpp index 20c8ca57c..d148bdc20 100644 --- a/src/green/IGreensFunction.hpp +++ b/src/green/IGreensFunction.hpp @@ -127,7 +127,7 @@ class IGreensFunction { /*! Whether the Green's function describes a uniform environment */ virtual bool uniform() const = 0; - /*! Returns a dielectric permittivity profile */ + /*! Returns a dielectric permittivity */ virtual double permittivity() const = 0; /*! @{ Methods to compute the diagonal of the matrix representation of the S and D diff --git a/src/utils/MathUtils.hpp b/src/utils/MathUtils.hpp index 53f950333..0d194bc67 100644 --- a/src/utils/MathUtils.hpp +++ b/src/utils/MathUtils.hpp @@ -106,7 +106,7 @@ inline bool numericalZero(double value) { return (isZero(value, 1.0e-14)); } /*! \fn inline int sign(T val) * \param[in] val value whose sign should be determined - * \tparam type of the parameter val + * \tparam T of the parameter val * * This function implements the signum function and returns the sign of the passed * value: -1, 0 or 1 From 608e1039c47db7e5118a11b52fcb02000863824a Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Fri, 1 Dec 2017 15:13:40 -0500 Subject: [PATCH 24/28] Drop GCC build on Mac --- .ci/ci_build.sh | 2 +- .travis.yml | 8 ++++---- README.md | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.ci/ci_build.sh b/.ci/ci_build.sh index 2aaf3eeb9..1f5e9f777 100755 --- a/.ci/ci_build.sh +++ b/.ci/ci_build.sh @@ -2,7 +2,7 @@ # The return code will capture an error from ANY of the functions in the pipe set -euo pipefail -cmake --build . -- VERBOSE=1 | tee build.log | grep "Building" +cmake --build . -- --jobs=2 VERBOSE=1 | tee build.log | grep "Building" RESULT=$? if [ $RESULT -eq 0 ]; then diff --git a/.travis.yml b/.travis.yml index 50323c905..b3527fbdc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -61,17 +61,17 @@ matrix: env: - CXX_COMPILER='clang++' - C_COMPILER='clang' - - Fortran_COMPILER='gfortran-5' + - Fortran_COMPILER='gfortran-6' - BUILD_TYPE='release' - PYTHON='python2' - - HOMEBREW_GCC='gcc@5' + - HOMEBREW_GCC='gcc@6' - STATIC='--static' - RUN_DANGER=false - os: osx osx_image: xcode7.3 env: - - CXX_COMPILER='g++-7' - - C_COMPILER='gcc-7' + - CXX_COMPILER='clang++' + - C_COMPILER='clang' - Fortran_COMPILER='gfortran-7' - BUILD_TYPE='release' - PYTHON='python3' diff --git a/README.md b/README.md index 22a8cf981..6ec8fffc0 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,9 @@ Travis CI runs release builds using [ccache](https://ccache.samba.org/) to speed with their Xcode 7.3.1 image. The following compilers are used: - 1. Apple Clang 7.3.0, GFortran 5.5.0, Python 2.7 This build generates _only_ + 1. Apple Clang 7.3.0, GFortran 6.4.0, Python 2.7 This build generates _only_ the static library. - 2. GCC 7.2.0, Python 3.6 This build generates _both_ the shared and static + 2. Apple Clang 7.3.0, GFortran 7.2.0, Python 3.6 This build generates _both_ the shared and static libraries, linking executables to the former. The build needed for submission to [Coverity scan](https://scan.coverity.com/) From b63fa994e9b286c05b37185b63271a1f1fcabf07 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Fri, 8 Dec 2017 16:13:45 -0500 Subject: [PATCH 25/28] Add stub of in-house RK4 solver [ci skip] --- .gitattributes | 1 + src/utils/RungeKutta4.cpp | 134 ++++++++++++++++++++++++++++++++++++++ src/utils/RungeKutta4.hpp | 82 +++++++++++++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 src/utils/RungeKutta4.cpp create mode 100644 src/utils/RungeKutta4.hpp diff --git a/.gitattributes b/.gitattributes index 646fabd51..3835aa7b7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -50,6 +50,7 @@ src/utils/*.cpp licensefile=.githooks/LICENSE-C++ src/utils/cnpy.hpp !licensefile src/utils/cnpy.cpp !licensefile src/utils/Legendre.hpp !licensefile +src/utils/RungeKutta4.* !licensefile # tests tests/unit_tests.cpp licensefile=.githooks/LICENSE-C++ diff --git a/src/utils/RungeKutta4.cpp b/src/utils/RungeKutta4.cpp new file mode 100644 index 000000000..c35a40502 --- /dev/null +++ b/src/utils/RungeKutta4.cpp @@ -0,0 +1,134 @@ +/* + * The Runge-Kutta source code is Copyright(c) 2010 John Burkardt. + * + * This Runge-Kutta ODE solver is free software: you can redistribute it and/or + * modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Runge-Kutts ODE Solver is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with the code. If not, see . + * + * See also: + * https://people.sc.fsu.edu/~jburkardt/cpp_src/rk4/rk4.html + */ + +#include "rk4.hpp" + +#include +#include +#include +#include + +namespace pcm { +namespace utils { +using namespace std; + +double rk4(double t0, double u0, double dt, double f(double t, double u)) { + double f0; + double f1; + double f2; + double f3; + double t1; + double t2; + double t3; + double u; + double u1; + double u2; + double u3; + // + // Get four sample values of the derivative. + // + f0 = f(t0, u0); + + t1 = t0 + dt / 2.0; + u1 = u0 + dt * f0 / 2.0; + f1 = f(t1, u1); + + t2 = t0 + dt / 2.0; + u2 = u0 + dt * f1 / 2.0; + f2 = f(t2, u2); + + t3 = t0 + dt; + u3 = u0 + dt * f2; + f3 = f(t3, u3); + // + // Combine to estimate the solution at time T0 + DT. + // + u = u0 + dt * (f0 + 2.0 * f1 + 2.0 * f2 + f3) / 6.0; + + return u; +} + +double * rk4vec(double t0, + int m, + double u0[], + double dt, + double * f(double t, int m, double u[])) + +{ + double * f0; + double * f1; + double * f2; + double * f3; + int i; + double t1; + double t2; + double t3; + double * u; + double * u1; + double * u2; + double * u3; + // + // Get four sample values of the derivative. + // + f0 = f(t0, m, u0); + + t1 = t0 + dt / 2.0; + u1 = new double[m]; + for (i = 0; i < m; i++) { + u1[i] = u0[i] + dt * f0[i] / 2.0; + } + f1 = f(t1, m, u1); + + t2 = t0 + dt / 2.0; + u2 = new double[m]; + for (i = 0; i < m; i++) { + u2[i] = u0[i] + dt * f1[i] / 2.0; + } + f2 = f(t2, m, u2); + + t3 = t0 + dt; + u3 = new double[m]; + for (i = 0; i < m; i++) { + u3[i] = u0[i] + dt * f2[i]; + } + f3 = f(t3, m, u3); + // + // Combine them to estimate the solution. + // + u = new double[m]; + for (i = 0; i < m; i++) { + u[i] = u0[i] + dt * (f0[i] + 2.0 * f1[i] + 2.0 * f2[i] + f3[i]) / 6.0; + } + // + // Free memory. + // + delete[] f0; + delete[] f1; + delete[] f2; + delete[] f3; + delete[] u1; + delete[] u2; + delete[] u3; + + return u; +} +} // namespace utils +} // namespace pcm diff --git a/src/utils/RungeKutta4.hpp b/src/utils/RungeKutta4.hpp new file mode 100644 index 000000000..8759168a2 --- /dev/null +++ b/src/utils/RungeKutta4.hpp @@ -0,0 +1,82 @@ +/* + * The Runge-Kutta source code is Copyright(c) 2013 John Burkardt. + * + * This Runge-Kutta ODE solver is free software: you can redistribute it and/or + * modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Runge-Kutts ODE Solver is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with the code. If not, see . + * + * See also: + * https://people.sc.fsu.edu/~jburkardt/cpp_src/rk4/rk4.html + */ + +/*! \file RungeKutta4.hpp */ + +namespace pcm { +namespace utils { +/*! Right-hand side for a scalar ordinary-differential equation */ +typedef std::function ScalarODERHS; + +/*! \brief RK4 takes one Runge-Kutta step for a scalar ODE. + * \author John Burkardt, Roberto Di Remigio + * \param[in] t0 the current time. + * \param[in] u0 the solution estimate at the current time. + * \param[in] dt the time step. + * \param[in] F a function which evaluates the derivative, or right hand side of the + * problem. + * \return the fourth-order Runge-Kutta solution estimate at time t0+dt. + * + * It is assumed that an initial value problem, of the form + * + * du/dt = f( t, u ) + * u(t0) = u0 + * + * is being solved. + * + * If the user can supply current values of t, u, a stepsize dt, and a + * function to evaluate the derivative, this function can compute the + * fourth-order Runge Kutta estimate to the solution at time t+dt. + */ +double rk4(double t0, double u0, double dt, double f(double t, double u)); + +/*! Right-hand side for a vector ordinary-differential equation */ +typedef std::function VectorODERHS; + +/*! + * \brief Takes one Runge-Kutta step for a vector ODE. + * \author John Burkardt, Roberto Di Remigio + * \param[in] t0 the current time. + * \param[in] n the spatial dimension. + * \param[in] u0[M] the solution estimate at the current time. + * \param[in] dt the time step. + * \param[in] F a function which evaluates the derivative, or right hand side of the + * problem. + * \return the fourth-order Runge-Kutta solution estimate at time t0+dt. + * + * It is assumed that an initial value problem, of the form + * + * du/dt = f ( t, u ) + * u(t0) = u0 + * + * is being solved. + * + * If the user can supply current values of t, u, a stepsize dt, and a + * function to evaluate the derivative, this function can compute the + * fourth-order Runge Kutta estimate to the solution at time t+dt. + */ +double * rk4vec(double t0, + int n, + double u0[], + double dt, + double * f(double t, int n, double u[])); +} // namespace utils +} // namespace pcm From d83186a09280fdad67b8313f8dbc1e822719ff8f Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 28 Dec 2017 13:20:04 +0100 Subject: [PATCH 26/28] Indent CMakeLists.txt for easier diffs --- default.nix | 1 + src/bi_operators/CMakeLists.txt | 20 ++++++++--- src/cavity/CMakeLists.txt | 18 ++++++++-- src/green/CMakeLists.txt | 29 +++++++++++---- src/green/dielectric_profile/CMakeLists.txt | 11 +++++- src/interface/CMakeLists.txt | 11 ++++-- src/make_cmake_files.py | 20 +++++------ src/metal/CMakeLists.txt | 4 ++- src/pedra/CMakeLists.txt | 16 ++++----- src/solver/CMakeLists.txt | 17 +++++++-- src/utils/CMakeLists.txt | 40 ++++++++++++++++----- 11 files changed, 140 insertions(+), 47 deletions(-) diff --git a/default.nix b/default.nix index 7c0283191..a69519e7e 100644 --- a/default.nix +++ b/default.nix @@ -24,6 +24,7 @@ in gfortran graphviz lldb + python3Packages.docopt python3Packages.matplotlib python3Packages.numpy python3Packages.pyyaml diff --git a/src/bi_operators/CMakeLists.txt b/src/bi_operators/CMakeLists.txt index a6fa00e26..ead9af0c8 100644 --- a/src/bi_operators/CMakeLists.txt +++ b/src/bi_operators/CMakeLists.txt @@ -1,14 +1,26 @@ # List of headers -list(APPEND headers_list BIOperatorData.hpp BoundaryIntegralOperator.hpp IBoundaryIntegralOperator.hpp Collocation.hpp Purisima.hpp Numerical.hpp) +list(APPEND headers_list +BIOperatorData.hpp +BoundaryIntegralOperator.hpp +Collocation.hpp +IBoundaryIntegralOperator.hpp +Numerical.hpp +Purisima.hpp +) # List of sources -list(APPEND sources_list IBoundaryIntegralOperator.cpp Collocation.cpp Purisima.cpp Numerical.cpp) +list(APPEND sources_list +Collocation.cpp +IBoundaryIntegralOperator.cpp +Numerical.cpp +Purisima.cpp +) -add_library(bi_operators OBJECT ${headers_list} ${sources_list}) +add_library(bi_operators OBJECT ${sources_list} ${headers_list}) set_target_properties(bi_operators PROPERTIES POSITION_INDEPENDENT_CODE 1 ) add_dependencies(bi_operators generate-config-hpp) target_compile_options(bi_operators PRIVATE "$<$:${EXDIAG_CXX_FLAGS}>") # Sets install directory for all the headers in the list foreach(_header ${headers_list}) - install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/bi_operators) + install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/bi_operators) endforeach() diff --git a/src/cavity/CMakeLists.txt b/src/cavity/CMakeLists.txt index 5129548a5..81c4e4ebe 100644 --- a/src/cavity/CMakeLists.txt +++ b/src/cavity/CMakeLists.txt @@ -1,8 +1,20 @@ # List of headers -list(APPEND headers_list Cavity.hpp ICavity.hpp CavityData.hpp Element.hpp GePolCavity.hpp RestartCavity.hpp) +list(APPEND headers_list +Cavity.hpp +CavityData.hpp +Element.hpp +GePolCavity.hpp +ICavity.hpp +RestartCavity.hpp +) # List of sources -list(APPEND sources_list ICavity.cpp Element.cpp GePolCavity.cpp RestartCavity.cpp) +list(APPEND sources_list +Element.cpp +GePolCavity.cpp +ICavity.cpp +RestartCavity.cpp +) add_library(cavity OBJECT ${sources_list} ${headers_list}) set_target_properties(cavity PROPERTIES POSITION_INDEPENDENT_CODE 1 ) @@ -10,5 +22,5 @@ add_dependencies(cavity generate-config-hpp) target_compile_options(cavity PRIVATE "$<$:${EXDIAG_CXX_FLAGS}>") # Sets install directory for all the headers in the list foreach(_header ${headers_list}) - install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/cavity) + install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/cavity) endforeach() diff --git a/src/green/CMakeLists.txt b/src/green/CMakeLists.txt index 20ff8a85e..7182185d0 100644 --- a/src/green/CMakeLists.txt +++ b/src/green/CMakeLists.txt @@ -1,11 +1,28 @@ # List of headers -list(APPEND headers_list Green.hpp AnisotropicLiquid.hpp DerivativeTypes.hpp GreenData.hpp GreenUtils.hpp GreensFunction.hpp - IGreensFunction.hpp InterfacesImpl.hpp IonicLiquid.hpp - SphericalDiffuse.hpp - SphericalSharp.hpp UniformDielectric.hpp Vacuum.hpp) +list(APPEND headers_list +AnisotropicLiquid.hpp +DerivativeTypes.hpp +Green.hpp +GreenData.hpp +GreenUtils.hpp +GreensFunction.hpp +IGreensFunction.hpp +InterfacesImpl.hpp +IonicLiquid.hpp +SphericalDiffuse.hpp +SphericalSharp.hpp +UniformDielectric.hpp +Vacuum.hpp +) # List of sources -list(APPEND sources_list Vacuum.cpp UniformDielectric.cpp IonicLiquid.cpp AnisotropicLiquid.cpp SphericalDiffuse.cpp) +list(APPEND sources_list +AnisotropicLiquid.cpp +IonicLiquid.cpp +SphericalDiffuse.cpp +UniformDielectric.cpp +Vacuum.cpp +) include_directories(dielectric_profile) add_library(green OBJECT ${sources_list} ${headers_list}) @@ -14,7 +31,7 @@ add_dependencies(green generate-config-hpp) target_compile_options(green PRIVATE "$<$:${EXDIAG_CXX_FLAGS}>") # Sets install directory for all the headers in the list foreach(_header ${headers_list}) - install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/green) + install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/green) endforeach() add_subdirectory(dielectric_profile) diff --git a/src/green/dielectric_profile/CMakeLists.txt b/src/green/dielectric_profile/CMakeLists.txt index 2080a7769..a397ea7ac 100644 --- a/src/green/dielectric_profile/CMakeLists.txt +++ b/src/green/dielectric_profile/CMakeLists.txt @@ -1,5 +1,14 @@ # List of headers -list(APPEND _headers_list Anisotropic.hpp MembraneTanh.hpp Metal.hpp OneLayerErf.hpp OneLayerTanh.hpp Sharp.hpp Uniform.hpp Yukawa.hpp) +list(APPEND headers_list +Anisotropic.hpp +MembraneTanh.hpp +Metal.hpp +OneLayerErf.hpp +OneLayerTanh.hpp +Sharp.hpp +Uniform.hpp +Yukawa.hpp +) # Sets install directory for all the headers in the list foreach(_header ${_headers_list}) diff --git a/src/interface/CMakeLists.txt b/src/interface/CMakeLists.txt index 01bdf1ddb..e71d67103 100644 --- a/src/interface/CMakeLists.txt +++ b/src/interface/CMakeLists.txt @@ -1,8 +1,15 @@ # List of headers -list(APPEND headers_list Meddle.hpp Input.hpp) +list(APPEND headers_list +Input.hpp +Meddle.hpp +) # List of sources -list(APPEND sources_list Meddle.cpp Input.cpp PhysicalConstants.cpp) +list(APPEND sources_list +Input.cpp +Meddle.cpp +PhysicalConstants.cpp +) add_library(interface OBJECT ${sources_list} ${headers_list}) set_target_properties(interface PROPERTIES POSITION_INDEPENDENT_CODE 1 ) diff --git a/src/make_cmake_files.py b/src/make_cmake_files.py index fe925afcc..00f21b677 100644 --- a/src/make_cmake_files.py +++ b/src/make_cmake_files.py @@ -51,12 +51,12 @@ def glob_sources_cxx(dir_name): """Create a list of C++ headers and sources to be used in a CMakeLists.txt file.""" - headers = 'list(APPEND headers_list ' - headers += ' '.join('%s' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.hpp'))) + headers = 'list(APPEND headers_list\n' + headers += ''.join('%s\n' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.hpp'))) headers += ')\n\n' - sources = 'list(APPEND sources_list ' - sources += ' '.join('%s' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.cpp'))) + sources = 'list(APPEND sources_list\n' + sources += ''.join('%s\n' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.cpp'))) sources += ')\n\n' message = '# List of headers\n' + headers \ @@ -66,12 +66,12 @@ def glob_sources_cxx(dir_name): def glob_sources_c(dir_name): """Create a list of C headers and sources to be used in a CMakeLists.txt file.""" - headers = 'list(APPEND headers_list ' - headers += ' '.join('%s' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.h'))) + headers = 'list(APPEND headers_list \n' + headers += ''.join('%s\n' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.h'))) headers += ')\n\n' - sources = 'list(APPEND sources_list ' - sources += ' '.join('%s' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.c'))) + sources = 'list(APPEND sources_list\n' + sources += ''.join('%s\n' % ''.join(map(str, os.path.basename(x))) for x in sorted(glob.glob(dir_name + '/*.c'))) sources += ')\n\n' message = '# List of headers\n' + headers \ @@ -85,8 +85,8 @@ def glob_sources_fortran(dir_name): list_of_sources = [] for ftype in types: list_of_sources.extend(sorted(glob.glob(dir_name + '/' + ftype))) - sources = 'list(APPEND sources_list ' - sources += ' '.join('%s' % ''.join(map(str, os.path.basename(x))) for x in list_of_sources) + sources = 'list(APPEND sources_list\n' + sources += ''.join('%s\n' % ''.join(map(str, os.path.basename(x))) for x in list_of_sources) sources += ')\n\n' message = '# List of sources\n' + sources diff --git a/src/metal/CMakeLists.txt b/src/metal/CMakeLists.txt index 9d7536a24..1084c3d66 100644 --- a/src/metal/CMakeLists.txt +++ b/src/metal/CMakeLists.txt @@ -1,5 +1,7 @@ # List of sources -list(APPEND sources_list metal_sphere.F90) +list(APPEND sources_list +metal_sphere.F90 +) add_library(metal OBJECT ${sources_list}) set_target_properties(metal PROPERTIES POSITION_INDEPENDENT_CODE 1 ) diff --git a/src/pedra/CMakeLists.txt b/src/pedra/CMakeLists.txt index e5e841fbd..03ee10f1a 100644 --- a/src/pedra/CMakeLists.txt +++ b/src/pedra/CMakeLists.txt @@ -1,13 +1,13 @@ # List of sources list(APPEND sources_list - pedra_cavity.F90 - pedra_cavity_interface.F90 - pedra_dblas.f90 - pedra_dlapack.f90 - pedra_precision.f90 - pedra_print.f90 - pedra_symmetry.f90 - pedra_utils.f90 +pedra_cavity.F90 +pedra_cavity_interface.F90 +pedra_dblas.f90 +pedra_dlapack.f90 +pedra_precision.f90 +pedra_print.f90 +pedra_symmetry.f90 +pedra_utils.f90 ) add_library(pedra OBJECT ${sources_list}) diff --git a/src/solver/CMakeLists.txt b/src/solver/CMakeLists.txt index b1e18bd43..b4542dce3 100644 --- a/src/solver/CMakeLists.txt +++ b/src/solver/CMakeLists.txt @@ -1,8 +1,19 @@ # List of headers -list(APPEND headers_list Solver.hpp CPCMSolver.hpp IEFSolver.hpp ISolver.hpp SolverData.hpp SolverImpl.hpp) +list(APPEND headers_list +CPCMSolver.hpp +IEFSolver.hpp +ISolver.hpp +Solver.hpp +SolverData.hpp +SolverImpl.hpp +) # List of sources -list(APPEND sources_list CPCMSolver.cpp IEFSolver.cpp SolverImpl.cpp) +list(APPEND sources_list +CPCMSolver.cpp +IEFSolver.cpp +SolverImpl.cpp +) add_library(solver OBJECT ${sources_list} ${headers_list}) set_target_properties(solver PROPERTIES POSITION_INDEPENDENT_CODE 1 ) @@ -10,5 +21,5 @@ add_dependencies(solver generate-config-hpp) target_compile_options(solver PRIVATE "$<$:${EXDIAG_CXX_FLAGS}>") # Sets install directory for all the headers in the list foreach(_header ${headers_list}) - install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/solver) + install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/solver) endforeach() diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index f50fce611..ca8719864 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -1,14 +1,36 @@ # List of headers -list(APPEND headers_list Atom.hpp ChargeDistribution.hpp Factory.hpp - Legendre.hpp Logger.hpp LoggerImpl.hpp MathUtils.hpp Molecule.hpp - QuadratureRules.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp - Stencils.hpp Symmetry.hpp Timer.hpp cnpy.hpp) -set_source_files_properties(cnpy.hpp PROPERTIES COMPILE_FLAGS -w) +list(APPEND headers_list +Atom.hpp +ChargeDistribution.hpp +Factory.hpp +Legendre.hpp +Logger.hpp +LoggerImpl.hpp +MathUtils.hpp +Molecule.hpp +QuadratureRules.hpp +RungeKutta4.hpp +Solvent.hpp +Sphere.hpp +SplineFunction.hpp +Stencils.hpp +Symmetry.hpp +Timer.hpp +cnpy.hpp +) # List of sources -list(APPEND sources_list Atom.cpp ChargeDistribution.cpp - Molecule.cpp QuadratureRules.cpp Solvent.cpp Sphere.cpp Symmetry.cpp cnpy.cpp) -set_source_files_properties(cnpy.cpp PROPERTIES COMPILE_FLAGS -w) +list(APPEND sources_list +Atom.cpp +ChargeDistribution.cpp +Molecule.cpp +QuadratureRules.cpp +RungeKutta4.cpp +Solvent.cpp +Sphere.cpp +Symmetry.cpp +cnpy.cpp +) add_library(utils OBJECT ${sources_list} ${headers_list}) set_target_properties(utils PROPERTIES POSITION_INDEPENDENT_CODE 1 ) @@ -16,7 +38,7 @@ add_dependencies(utils generate-config-hpp) target_compile_options(utils PRIVATE "$<$:${EXDIAG_CXX_FLAGS}>") # Sets install directory for all the headers in the list foreach(_header ${headers_list}) - install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/utils) + install(FILES ${_header} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}/utils) endforeach() add_subdirectory(getkw) From 166f8b9c09cf2579d60585d7b04fcf08dc404c6b Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 28 Dec 2017 14:51:21 +0100 Subject: [PATCH 27/28] Fix licensing in Legendre.hpp --- src/utils/Legendre.hpp | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/src/utils/Legendre.hpp b/src/utils/Legendre.hpp index d47a6b9da..f7ddefdb6 100644 --- a/src/utils/Legendre.hpp +++ b/src/utils/Legendre.hpp @@ -1,26 +1,3 @@ -/** - * PCMSolver, an API for the Polarizable Continuum Model - * Copyright (C) 2017 Roberto Di Remigio, Luca Frediani and collaborators. - * - * This file is part of PCMSolver. - * - * PCMSolver is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PCMSolver is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with PCMSolver. If not, see . - * - * For information on the complete list of contributors to the - * PCMSolver API, see: - */ - //================================================================== /* * Legendre.hpp -- C++ functions to evaluate Legendre polynomials @@ -103,4 +80,4 @@ template inline T Pn(unsigned int n, const T & x) { return pn; } -} +} // namespace Legendre From 68e5a258592db2fa2a569b2c69771d220c75c367 Mon Sep 17 00:00:00 2001 From: Roberto Di Remigio Date: Thu, 28 Dec 2017 14:59:11 +0100 Subject: [PATCH 28/28] RungeKutta4 class not ready for consumption --- src/utils/CMakeLists.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index ca8719864..5b07e2e5f 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -9,7 +9,6 @@ LoggerImpl.hpp MathUtils.hpp Molecule.hpp QuadratureRules.hpp -RungeKutta4.hpp Solvent.hpp Sphere.hpp SplineFunction.hpp @@ -25,7 +24,6 @@ Atom.cpp ChargeDistribution.cpp Molecule.cpp QuadratureRules.cpp -RungeKutta4.cpp Solvent.cpp Sphere.cpp Symmetry.cpp