diff --git a/.github/workflows/deploy_branch.yml b/.github/workflows/deploy_branch.yml index 5264c81575..b424109974 100644 --- a/.github/workflows/deploy_branch.yml +++ b/.github/workflows/deploy_branch.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 20 diff --git a/.github/workflows/deploy_release.yml b/.github/workflows/deploy_release.yml index 543ad17caa..44f51057a1 100644 --- a/.github/workflows/deploy_release.yml +++ b/.github/workflows/deploy_release.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 20 diff --git a/.github/workflows/test_benchmark_collection_models.yml b/.github/workflows/test_benchmark_collection_models.yml index 0acd4bea59..fe946ba1c0 100644 --- a/.github/workflows/test_benchmark_collection_models.yml +++ b/.github/workflows/test_benchmark_collection_models.yml @@ -20,7 +20,7 @@ jobs: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 20 diff --git a/.github/workflows/test_performance.yml b/.github/workflows/test_performance.yml index 16f8018d49..b5c92449a6 100644 --- a/.github/workflows/test_performance.yml +++ b/.github/workflows/test_performance.yml @@ -22,7 +22,7 @@ jobs: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 20 diff --git a/.github/workflows/test_python_ver_matrix.yml b/.github/workflows/test_python_ver_matrix.yml index a3a6952bfe..0412483141 100644 --- a/.github/workflows/test_python_ver_matrix.yml +++ b/.github/workflows/test_python_ver_matrix.yml @@ -38,7 +38,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 20 diff --git a/.github/workflows/test_sbml_semantic_test_suite.yml b/.github/workflows/test_sbml_semantic_test_suite.yml index 7dad35396d..f08e4c5a7d 100644 --- a/.github/workflows/test_sbml_semantic_test_suite.yml +++ b/.github/workflows/test_sbml_semantic_test_suite.yml @@ -29,7 +29,7 @@ jobs: "1000-1250", "1251-1780"] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@master with: fetch-depth: 1 - name: apt diff --git a/CHANGELOG.md b/CHANGELOG.md index 26335a93d4..7cf659e6dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,35 @@ ## v0.X Series +### v0.11.23 (2022-01-11) + +Features: +* Added overload for Model::setParameterScale with vector by @dilpath in + https://github.com/AMICI-dev/AMICI/pull/1614 +* Removed assert_fun argument from gradient checking, improve output + by @dweindl, @FFroehlich in https://github.com/AMICI-dev/AMICI/pull/1609 +* Added get_expressions_as_dataframe by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1621 +* Added `id` field to ExpData and ReturnData by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1622 +* Included condition id in dataframes by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1623 + +Fixes: +* C++: Fixed SUNMatrixWrapper ctor for size 0 matrices by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1608 +* Python: Handle TemporaryDirectory cleanup failures on Windows by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1617 +* Python: pysb.Model.initial_conditions throws a DeprecationWarning by + @PaulJonasJost in https://github.com/AMICI-dev/AMICI/pull/1620 +* Fixed wrong array size in warnings by @dweindl in + https://github.com/AMICI-dev/AMICI/pull/1624 + +NOTE: AMICI 0.11.23 requires numpy<1.22.0 + +**Full Changelog**: +https://github.com/AMICI-dev/AMICI/compare/v0.11.22...v0.11.23 + ### v0.11.22 (2021-12-02) * **Require sympy>=1.9,pysb>=1.13.1** by @FFroehlich, @dweindl diff --git a/ThirdParty/gsl/gsl/gsl-lite.hpp b/ThirdParty/gsl/gsl/gsl-lite.hpp index 825087cabd..380fb2f34b 100644 --- a/ThirdParty/gsl/gsl/gsl-lite.hpp +++ b/ThirdParty/gsl/gsl/gsl-lite.hpp @@ -1,8 +1,9 @@ // // gsl-lite is based on GSL: Guidelines Support Library. -// For more information see https://github.com/martinmoene/gsl-lite +// For more information see https://github.com/gsl-lite/gsl-lite // -// Copyright (c) 2015-2018 Martin Moene +// Copyright (c) 2015-2019 Martin Moene +// Copyright (c) 2019-2021 Moritz Beutel // Copyright (c) 2015-2018 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). @@ -15,128 +16,462 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#pragma once - #ifndef GSL_GSL_LITE_HPP_INCLUDED #define GSL_GSL_LITE_HPP_INCLUDED -#include -#include -#include +#include // for exception, terminate(), uncaught_exceptions() #include -#include -#include -#include +#include // for addressof(), unique_ptr<>, shared_ptr<> +#include // for basic_ostream<> +#include // for ios_base, streamsize +#include // for logic_error #include -#include -#include +#include // for move(), forward<>(), swap() +#include // for size_t, ptrdiff_t, nullptr_t +#include // for abort() #define gsl_lite_MAJOR 0 -#define gsl_lite_MINOR 34 +#define gsl_lite_MINOR 40 #define gsl_lite_PATCH 0 #define gsl_lite_VERSION gsl_STRINGIFY(gsl_lite_MAJOR) "." gsl_STRINGIFY(gsl_lite_MINOR) "." gsl_STRINGIFY(gsl_lite_PATCH) +#define gsl_STRINGIFY( x ) gsl_STRINGIFY_( x ) +#define gsl_STRINGIFY_( x ) #x +#define gsl_CONCAT_( a, b ) gsl_CONCAT2_( a, b ) +#define gsl_CONCAT2_( a, b ) a##b +#define gsl_EVALF_( f ) f() + +// configuration argument checking: + +#define gsl_DETAIL_CFG_TOGGLE_VALUE_1 1 +#define gsl_DETAIL_CFG_TOGGLE_VALUE_0 1 +#define gsl_DETAIL_CFG_DEFAULTS_VERSION_VALUE_1 1 +#define gsl_DETAIL_CFG_DEFAULTS_VERSION_VALUE_0 1 +#define gsl_DETAIL_CFG_STD_VALUE_98 1 +#define gsl_DETAIL_CFG_STD_VALUE_3 1 +#define gsl_DETAIL_CFG_STD_VALUE_03 1 +#define gsl_DETAIL_CFG_STD_VALUE_11 1 +#define gsl_DETAIL_CFG_STD_VALUE_14 1 +#define gsl_DETAIL_CFG_STD_VALUE_17 1 +#define gsl_DETAIL_CFG_STD_VALUE_20 1 +#define gsl_DETAIL_CFG_NO_VALUE_ 1 +#define gsl_DETAIL_CFG_NO_VALUE_1 1 // many compilers treat the command-line parameter "-Dfoo" as equivalent to "-Dfoo=1", so we tolerate that +#define gsl_CHECK_CFG_TOGGLE_VALUE_( x ) gsl_CONCAT_( gsl_DETAIL_CFG_TOGGLE_VALUE_, x ) +#define gsl_CHECK_CFG_DEFAULTS_VERSION_VALUE_( x ) gsl_CONCAT_( gsl_DETAIL_CFG_DEFAULTS_VERSION_VALUE_, x ) +#define gsl_CHECK_CFG_STD_VALUE_( x ) gsl_CONCAT_( gsl_DETAIL_CFG_STD_VALUE_, x ) +#define gsl_CHECK_CFG_NO_VALUE_( x ) gsl_CONCAT_( gsl_DETAIL_CFG_NO_VALUE, gsl_CONCAT_( _, x ) ) + // gsl-lite backward compatibility: -#ifdef gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR +#if defined( gsl_CONFIG_DEFAULTS_VERSION ) +# if ! gsl_CHECK_CFG_DEFAULTS_VERSION_VALUE_( gsl_CONFIG_DEFAULTS_VERSION ) +# pragma message ("invalid configuration value gsl_CONFIG_DEFAULTS_VERSION=" gsl_STRINGIFY(gsl_CONFIG_DEFAULTS_VERSION) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_DEFAULTS_VERSION gsl_lite_MAJOR // default +#endif +# define gsl_CONFIG_DEFAULTS_VERSION_() gsl_CONFIG_DEFAULTS_VERSION + +#if defined( gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR ) +# pragma message ("invalid configuration value gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR=" gsl_STRINGIFY(gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR) ", must be 0 or 1") +# endif # define gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR -# pragma message ("gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR is deprecated since gsl-lite 0.7.0; replace with gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR, or consider span(with_container, cont).") +# pragma message ("gsl_CONFIG_ALLOWS_SPAN_CONTAINER_CTOR is deprecated since gsl-lite 0.7; replace with gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR, or consider span(with_container, cont).") +#endif + +#if defined( gsl_CONFIG_CONTRACT_LEVEL_ON ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_LEVEL_ON ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_LEVEL_ON=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_LEVEL_ON) "; macro must be defined without value") +# endif +# pragma message ("gsl_CONFIG_CONTRACT_LEVEL_ON is deprecated since gsl-lite 0.36; replace with gsl_CONFIG_CONTRACT_CHECKING_ON.") +# define gsl_CONFIG_CONTRACT_CHECKING_ON +#endif +#if defined( gsl_CONFIG_CONTRACT_LEVEL_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_LEVEL_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_LEVEL_OFF=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_LEVEL_OFF) "; macro must be defined without value") +# endif +# pragma message ("gsl_CONFIG_CONTRACT_LEVEL_OFF is deprecated since gsl-lite 0.36; replace with gsl_CONFIG_CONTRACT_CHECKING_OFF.") +# define gsl_CONFIG_CONTRACT_CHECKING_OFF +#endif +#if defined( gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY) "; macro must be defined without value") +# endif +# pragma message ("gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY is deprecated since gsl-lite 0.36; replace with gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF and gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF.") +# define gsl_CONFIG_CONTRACT_CHECKING_ON +# define gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF +# define gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF +#elif defined( gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY) "; macro must be defined without value") +# endif +# pragma message ("gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY is deprecated since gsl-lite 0.36; replace with gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF and gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF.") +# define gsl_CONFIG_CONTRACT_CHECKING_ON +# define gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF +# define gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF #endif // M-GSL compatibility: #if defined( GSL_THROW_ON_CONTRACT_VIOLATION ) -# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS 1 +# if ! gsl_CHECK_CFG_NO_VALUE_( GSL_THROW_ON_CONTRACT_VIOLATION ) +# pragma message ("invalid configuration value GSL_THROW_ON_CONTRACT_VIOLATION=" gsl_STRINGIFY(GSL_THROW_ON_CONTRACT_VIOLATION) "; macro must be defined without value") +# endif +# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS #endif #if defined( GSL_TERMINATE_ON_CONTRACT_VIOLATION ) -# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS 0 +# if ! gsl_CHECK_CFG_NO_VALUE_( GSL_TERMINATE_ON_CONTRACT_VIOLATION ) +# pragma message ("invalid configuration value GSL_TERMINATE_ON_CONTRACT_VIOLATION=" gsl_STRINGIFY(GSL_TERMINATE_ON_CONTRACT_VIOLATION) "; macro must be defined without value") +# endif +# define gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES #endif #if defined( GSL_UNENFORCED_ON_CONTRACT_VIOLATION ) -# define gsl_CONFIG_CONTRACT_LEVEL_OFF 1 +# if ! gsl_CHECK_CFG_NO_VALUE_( GSL_UNENFORCED_ON_CONTRACT_VIOLATION ) +# pragma message ("invalid configuration value GSL_UNENFORCED_ON_CONTRACT_VIOLATION=" gsl_STRINGIFY(GSL_UNENFORCED_ON_CONTRACT_VIOLATION) "; macro must be defined without value") +# endif +# define gsl_CONFIG_CONTRACT_CHECKING_OFF #endif // Configuration: Features -#ifndef gsl_FEATURE_WITH_CONTAINER_TO_STD -# define gsl_FEATURE_WITH_CONTAINER_TO_STD 99 +#if defined( gsl_FEATURE_WITH_CONTAINER_TO_STD ) +# if ! gsl_CHECK_CFG_STD_VALUE_( gsl_FEATURE_WITH_CONTAINER_TO_STD ) +# pragma message ("invalid configuration value gsl_FEATURE_WITH_CONTAINER_TO_STD=" gsl_STRINGIFY(gsl_FEATURE_WITH_CONTAINER_TO_STD) ", must be 98, 3, 11, 14, 17, or 20") +# endif +#else +# define gsl_FEATURE_WITH_CONTAINER_TO_STD 99 // default +#endif +#define gsl_FEATURE_WITH_CONTAINER_TO_STD_() gsl_FEATURE_WITH_CONTAINER_TO_STD + +#if defined( gsl_FEATURE_MAKE_SPAN_TO_STD ) +# if ! gsl_CHECK_CFG_STD_VALUE_( gsl_FEATURE_MAKE_SPAN_TO_STD ) +# pragma message ("invalid configuration value gsl_FEATURE_MAKE_SPAN_TO_STD=" gsl_STRINGIFY(gsl_FEATURE_MAKE_SPAN_TO_STD) ", must be 98, 3, 11, 14, 17, or 20") +# endif +#else +# define gsl_FEATURE_MAKE_SPAN_TO_STD 99 // default #endif +#define gsl_FEATURE_MAKE_SPAN_TO_STD_() gsl_FEATURE_MAKE_SPAN_TO_STD -#ifndef gsl_FEATURE_MAKE_SPAN_TO_STD -# define gsl_FEATURE_MAKE_SPAN_TO_STD 99 +#if defined( gsl_FEATURE_BYTE_SPAN_TO_STD ) +# if ! gsl_CHECK_CFG_STD_VALUE_( gsl_FEATURE_BYTE_SPAN_TO_STD ) +# pragma message ("invalid configuration value gsl_FEATURE_BYTE_SPAN_TO_STD=" gsl_STRINGIFY(gsl_FEATURE_BYTE_SPAN_TO_STD) ", must be 98, 3, 11, 14, 17, or 20") +# endif +#else +# define gsl_FEATURE_BYTE_SPAN_TO_STD 99 // default #endif +#define gsl_FEATURE_BYTE_SPAN_TO_STD_() gsl_FEATURE_BYTE_SPAN_TO_STD -#ifndef gsl_FEATURE_BYTE_SPAN_TO_STD -# define gsl_FEATURE_BYTE_SPAN_TO_STD 99 +#if defined( gsl_FEATURE_IMPLICIT_MACRO ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_FEATURE_IMPLICIT_MACRO ) +# pragma message ("invalid configuration value gsl_FEATURE_IMPLICIT_MACRO=" gsl_STRINGIFY(gsl_FEATURE_IMPLICIT_MACRO) ", must be 0 or 1") +# endif +#else +# define gsl_FEATURE_IMPLICIT_MACRO 0 // default #endif +#define gsl_FEATURE_IMPLICIT_MACRO_() gsl_FEATURE_IMPLICIT_MACRO -#ifndef gsl_FEATURE_IMPLICIT_MACRO -# define gsl_FEATURE_IMPLICIT_MACRO 1 +#if defined( gsl_FEATURE_OWNER_MACRO ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_FEATURE_OWNER_MACRO ) +# pragma message ("invalid configuration value gsl_FEATURE_OWNER_MACRO=" gsl_STRINGIFY(gsl_FEATURE_OWNER_MACRO) ", must be 0 or 1") +# endif +#else +# define gsl_FEATURE_OWNER_MACRO (gsl_CONFIG_DEFAULTS_VERSION == 0) // default #endif +#define gsl_FEATURE_OWNER_MACRO_() gsl_FEATURE_OWNER_MACRO -#ifndef gsl_FEATURE_OWNER_MACRO -# define gsl_FEATURE_OWNER_MACRO 1 +#if defined( gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD ) +# pragma message ("invalid configuration value gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD=" gsl_STRINGIFY(gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD) ", must be 0 or 1") +# endif +#else +# define gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD 0 // default #endif +# define gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD_() gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD -#ifndef gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD -# define gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD 0 +#if defined( gsl_FEATURE_GSL_LITE_NAMESPACE ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_FEATURE_GSL_LITE_NAMESPACE ) +# pragma message ("invalid configuration value gsl_FEATURE_GSL_LITE_NAMESPACE=" gsl_STRINGIFY(gsl_FEATURE_GSL_LITE_NAMESPACE) ", must be 0 or 1") +# endif +#else +# define gsl_FEATURE_GSL_LITE_NAMESPACE (gsl_CONFIG_DEFAULTS_VERSION >= 1) // default #endif +#define gsl_FEATURE_GSL_LITE_NAMESPACE_() gsl_FEATURE_GSL_LITE_NAMESPACE // Configuration: Other -#ifndef gsl_CONFIG_DEPRECATE_TO_LEVEL -# define gsl_CONFIG_DEPRECATE_TO_LEVEL 0 +#if defined( gsl_CONFIG_TRANSPARENT_NOT_NULL ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_TRANSPARENT_NOT_NULL ) +# pragma message ("invalid configuration value gsl_CONFIG_TRANSPARENT_NOT_NULL=" gsl_STRINGIFY(gsl_CONFIG_TRANSPARENT_NOT_NULL) ", must be 0 or 1") +# endif +# if gsl_CONFIG_TRANSPARENT_NOT_NULL && defined( gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF ) +# error configuration option gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF is meaningless if gsl_CONFIG_TRANSPARENT_NOT_NULL=1 +# endif +#else +# define gsl_CONFIG_TRANSPARENT_NOT_NULL (gsl_CONFIG_DEFAULTS_VERSION >= 1) // default +#endif +# define gsl_CONFIG_TRANSPARENT_NOT_NULL_() gsl_CONFIG_TRANSPARENT_NOT_NULL + +#if ! defined( gsl_CONFIG_DEPRECATE_TO_LEVEL ) +# if gsl_CONFIG_DEFAULTS_VERSION >= 1 +# define gsl_CONFIG_DEPRECATE_TO_LEVEL 6 +# else +# define gsl_CONFIG_DEPRECATE_TO_LEVEL 0 +# endif +#endif + +#if ! defined( gsl_CONFIG_SPAN_INDEX_TYPE ) +# define gsl_CONFIG_SPAN_INDEX_TYPE std::size_t #endif +# define gsl_CONFIG_SPAN_INDEX_TYPE_() gsl_CONFIG_SPAN_INDEX_TYPE -#ifndef gsl_CONFIG_SPAN_INDEX_TYPE -# define gsl_CONFIG_SPAN_INDEX_TYPE size_t +#if ! defined( gsl_CONFIG_INDEX_TYPE ) +# if gsl_CONFIG_DEFAULTS_VERSION >= 1 +// p0122r3 uses std::ptrdiff_t +# define gsl_CONFIG_INDEX_TYPE std::ptrdiff_t +# else +# define gsl_CONFIG_INDEX_TYPE gsl_CONFIG_SPAN_INDEX_TYPE +# endif #endif +# define gsl_CONFIG_INDEX_TYPE_() gsl_CONFIG_INDEX_TYPE -#ifndef gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR -# define gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR 0 +#if defined( gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR ) +# pragma message ("invalid configuration value gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR=" gsl_STRINGIFY(gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR (gsl_CONFIG_DEFAULTS_VERSION >= 1) // default #endif +#define gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR_() gsl_CONFIG_NOT_NULL_EXPLICIT_CTOR -#ifndef gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF -# define gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF 0 +#if defined( gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF ) +# pragma message ("invalid configuration value gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF=" gsl_STRINGIFY(gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF 0 // default #endif +#define gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF_() gsl_CONFIG_NOT_NULL_GET_BY_CONST_REF -#ifndef gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS -# define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS 0 +#if defined( gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS ) +# pragma message ("invalid configuration value gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS=" gsl_STRINGIFY(gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS 0 // default #endif +#define gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS_() gsl_CONFIG_CONFIRMS_COMPILATION_ERRORS -#ifndef gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON -# define gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON 1 +#if defined( gsl_CONFIG_ALLOWS_SPAN_COMPARISON ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_ALLOWS_SPAN_COMPARISON ) +# pragma message ("invalid configuration value gsl_CONFIG_ALLOWS_SPAN_COMPARISON=" gsl_STRINGIFY(gsl_CONFIG_ALLOWS_SPAN_COMPARISON) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_ALLOWS_SPAN_COMPARISON (gsl_CONFIG_DEFAULTS_VERSION == 0) // default #endif +#define gsl_CONFIG_ALLOWS_SPAN_COMPARISON_() gsl_CONFIG_ALLOWS_SPAN_COMPARISON -#ifndef gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR -# define gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR 0 +#if defined( gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON ) +# pragma message ("invalid configuration value gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON=" gsl_STRINGIFY(gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON) ", must be 0 or 1") +# endif +#else +# define gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON 1 // default #endif +#define gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON_() gsl_CONFIG_ALLOWS_NONSTRICT_SPAN_COMPARISON -#if defined( gsl_CONFIG_CONTRACT_LEVEL_ON ) -# define gsl_CONFIG_CONTRACT_LEVEL_MASK 0x11 -#elif defined( gsl_CONFIG_CONTRACT_LEVEL_OFF ) -# define gsl_CONFIG_CONTRACT_LEVEL_MASK 0x00 -#elif defined( gsl_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY ) -# define gsl_CONFIG_CONTRACT_LEVEL_MASK 0x01 -#elif defined( gsl_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY ) -# define gsl_CONFIG_CONTRACT_LEVEL_MASK 0x10 +#if defined( gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR ) +# pragma message ("invalid configuration value gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR=" gsl_STRINGIFY(gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR) ", must be 0 or 1") +# endif #else -# define gsl_CONFIG_CONTRACT_LEVEL_MASK 0x11 +# define gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR 0 // default #endif +#define gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR_() gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR -#if !defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) && \ - !defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) -# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS_V 0 -#elif defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) && \ - !defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) -# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS_V 1 -#elif !defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) && \ - defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) -# define gsl_CONFIG_CONTRACT_VIOLATION_THROWS_V 0 +#if defined( gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION ) +# if ! gsl_CHECK_CFG_TOGGLE_VALUE_( gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION ) +# pragma message ("invalid configuration value gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION=" gsl_STRINGIFY(gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION) ", must be 0 or 1") +# endif #else -# error only one of gsl_CONFIG_CONTRACT_VIOLATION_THROWS and gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES may be defined. +# define gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION (gsl_CONFIG_DEFAULTS_VERSION >= 1) // default +#endif +#define gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION_() gsl_CONFIG_NARROW_THROWS_ON_TRUNCATION + +#if defined( gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_AUDIT=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_AUDIT) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_CHECKING_ON ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_ON ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_ON=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_ON) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_CHECKING_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_CHECKING_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_CHECKING_OFF=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_CHECKING_OFF) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_VIOLATION_THROWS=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_VIOLATION_THROWS) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_VIOLATION_TRAPS=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_VIOLATION_TRAPS) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +# pragma message ("invalid configuration value gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER=" gsl_STRINGIFY(gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) +# pragma message ("invalid configuration value gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME=" gsl_STRINGIFY(gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE ) +# pragma message ("invalid configuration value gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE=" gsl_STRINGIFY(gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME) "; macro must be defined without value") +# endif +#endif +#if defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE ) +# if ! gsl_CHECK_CFG_NO_VALUE_( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE ) +# pragma message ("invalid configuration value gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE=" gsl_STRINGIFY(gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE) "; macro must be defined without value") +# endif +#endif + +#if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_THROWS ) +# error cannot use gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_THROWS because exceptions are not supported in device code; use gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS or gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS +#endif +#if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TERMINATES ) +# error gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TERMINATES is not supported; use gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS or gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS +#endif + +#if 1 < defined( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) + defined( gsl_CONFIG_CONTRACT_CHECKING_ON ) + defined( gsl_CONFIG_CONTRACT_CHECKING_OFF ) +# error only one of gsl_CONFIG_CONTRACT_CHECKING_AUDIT, gsl_CONFIG_CONTRACT_CHECKING_ON, and gsl_CONFIG_CONTRACT_CHECKING_OFF may be defined +#endif +#if 1 < defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT ) + defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON ) + defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF ) +# error only one of gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT, gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON, and gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF may be defined +#endif +#if 1 < defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +# error only one of gsl_CONFIG_CONTRACT_VIOLATION_THROWS, gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES, gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS, gsl_CONFIG_CONTRACT_VIOLATION_TRAPS, and gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER may be defined +#endif +#if 1 < defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS ) + defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS ) + defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER ) +# error only one of gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS, gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS, and gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER may be defined +#endif +#if 1 < defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) + defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE ) +# error only one of gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME and gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE may be defined +#endif +#if 1 < defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME ) + defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE ) +# error only one of gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME and gsl_CONFIG_UNENFORCED_DEVICE_CONTRACTS_ELIDE may be defined +#endif + +#if 0 == defined( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) + defined( gsl_CONFIG_CONTRACT_CHECKING_ON ) + defined( gsl_CONFIG_CONTRACT_CHECKING_OFF ) +// select default +# define gsl_CONFIG_CONTRACT_CHECKING_ON +#endif +#if 0 == defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT ) + defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON ) + defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF ) +// select default +# if defined( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) +# define gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT +# elif defined( gsl_CONFIG_CONTRACT_CHECKING_OFF ) +# define gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF +# else +# define gsl_CONFIG_DEVICE_CONTRACT_CHECKING_ON +# endif +#endif +#if 0 == defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) + defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +// select default +# define gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES +#endif +#if 0 == defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS ) + defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS ) + defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER ) +// select default +# if defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +# define gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER +# elif defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) +# define gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS +# else +# define gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS +# endif +#endif +#if 0 == defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) + defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE ) +// select default +# define gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE +#endif +#if 0 == defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME ) + defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE ) +// select default +# if defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) +# define gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME +# else +# define gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE +# endif #endif // C++ language version detection (C++20 is speculative): @@ -150,6 +485,12 @@ # endif #endif +// C++ standard library version: + +#ifndef gsl_CPLUSPLUS_STDLIB +# define gsl_CPLUSPLUS_STDLIB gsl_CPLUSPLUS +#endif + #define gsl_CPP98_OR_GREATER ( gsl_CPLUSPLUS >= 199711L ) #define gsl_CPP11_OR_GREATER ( gsl_CPLUSPLUS >= 201103L ) #define gsl_CPP14_OR_GREATER ( gsl_CPLUSPLUS >= 201402L ) @@ -164,53 +505,91 @@ #define gsl_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) // Compiler versions: -// -// MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0) -// MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002) -// MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003) -// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) -// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) -// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) -// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) -// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) -// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) -// MSVC++ 14.1 _MSC_VER >= 1910 (Visual Studio 2017) -#if defined(_MSC_VER ) && !defined(__clang__) -# define gsl_COMPILER_MSVC_VER (_MSC_VER ) -# define gsl_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) +// MSVC++ 6.0 _MSC_VER == 1200 gsl_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) +// MSVC++ 7.0 _MSC_VER == 1300 gsl_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) +// MSVC++ 7.1 _MSC_VER == 1310 gsl_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) +// MSVC++ 8.0 _MSC_VER == 1400 gsl_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) +// MSVC++ 9.0 _MSC_VER == 1500 gsl_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) +// MSVC++ 10.0 _MSC_VER == 1600 gsl_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) +// MSVC++ 11.0 _MSC_VER == 1700 gsl_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) +// MSVC++ 12.0 _MSC_VER == 1800 gsl_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) +// MSVC++ 14.0 _MSC_VER == 1900 gsl_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) +// MSVC++ 14.1 _MSC_VER >= 1910 gsl_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) +// MSVC++ 14.2 _MSC_VER >= 1920 gsl_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) + +#if defined( _MSC_VER ) && ! defined( __clang__ ) +# define gsl_COMPILER_MSVC_VER (_MSC_VER ) +# define gsl_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) +# define gsl_COMPILER_MSVC_VERSION_FULL (_MSC_VER - 100 * ( 5 + (_MSC_VER < 1900 ) ) ) #else -# define gsl_COMPILER_MSVC_VER 0 -# define gsl_COMPILER_MSVC_VERSION 0 +# define gsl_COMPILER_MSVC_VER 0 +# define gsl_COMPILER_MSVC_VERSION 0 +# define gsl_COMPILER_MSVC_VERSION_FULL 0 #endif #define gsl_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) -#if defined(__clang__) -# define gsl_COMPILER_CLANG_VERSION gsl_COMPILER_VERSION( __clang_major__, __clang_minor__, __clang_patchlevel__ ) +// AppleClang 7.0.0 __apple_build_version__ == 7000172 gsl_COMPILER_APPLECLANG_VERSION == 700 (Xcode 7.0, 7.0.1) (LLVM 3.7.0) +// AppleClang 7.0.0 __apple_build_version__ == 7000176 gsl_COMPILER_APPLECLANG_VERSION == 700 (Xcode 7.1) (LLVM 3.7.0) +// AppleClang 7.0.2 __apple_build_version__ == 7000181 gsl_COMPILER_APPLECLANG_VERSION == 702 (Xcode 7.2, 7.2.1) (LLVM 3.7.0) +// AppleClang 7.3.0 __apple_build_version__ == 7030029 gsl_COMPILER_APPLECLANG_VERSION == 730 (Xcode 7.3) (LLVM 3.8.0) +// AppleClang 7.3.0 __apple_build_version__ == 7030031 gsl_COMPILER_APPLECLANG_VERSION == 730 (Xcode 7.3.1) (LLVM 3.8.0) +// AppleClang 8.0.0 __apple_build_version__ == 8000038 gsl_COMPILER_APPLECLANG_VERSION == 800 (Xcode 8.0) (LLVM 3.9.0) +// AppleClang 8.0.0 __apple_build_version__ == 8000042 gsl_COMPILER_APPLECLANG_VERSION == 800 (Xcode 8.1, 8.2, 8.2.1) (LLVM 3.9.0) +// AppleClang 8.1.0 __apple_build_version__ == 8020038 gsl_COMPILER_APPLECLANG_VERSION == 810 (Xcode 8.3) (LLVM 3.9.0) +// AppleClang 8.1.0 __apple_build_version__ == 8020041 gsl_COMPILER_APPLECLANG_VERSION == 810 (Xcode 8.3.1) (LLVM 3.9.0) +// AppleClang 8.1.0 __apple_build_version__ == 8020042 gsl_COMPILER_APPLECLANG_VERSION == 810 (Xcode 8.3.2, 8.3.3) (LLVM 3.9.0) +// AppleClang 9.0.0 __apple_build_version__ == 9000037 gsl_COMPILER_APPLECLANG_VERSION == 900 (Xcode 9.0) (LLVM 4.0.0) +// AppleClang 9.0.0 __apple_build_version__ == 9000038 gsl_COMPILER_APPLECLANG_VERSION == 900 (Xcode 9.1) (LLVM 4.0.0) +// AppleClang 9.0.0 __apple_build_version__ == 9000039 gsl_COMPILER_APPLECLANG_VERSION == 900 (Xcode 9.2) (LLVM 4.0.0) +// AppleClang 9.1.0 __apple_build_version__ == 9020039 gsl_COMPILER_APPLECLANG_VERSION == 910 (Xcode 9.3, 9.3.1) (LLVM 5.0.2) +// AppleClang 9.1.0 __apple_build_version__ == 9020039 gsl_COMPILER_APPLECLANG_VERSION == 910 (Xcode 9.4, 9.4.1) (LLVM 5.0.2) +// AppleClang 10.0.0 __apple_build_version__ == 10001145 gsl_COMPILER_APPLECLANG_VERSION == 1000 (Xcode 10.0, 10.1) (LLVM 6.0.1) +// AppleClang 10.0.1 __apple_build_version__ == 10010046 gsl_COMPILER_APPLECLANG_VERSION == 1001 (Xcode 10.2, 10.2.1, 10.3) (LLVM 7.0.0) +// AppleClang 11.0.0 __apple_build_version__ == 11000033 gsl_COMPILER_APPLECLANG_VERSION == 1100 (Xcode 11.1, 11.2, 11.3, 11.3.1) (LLVM 8.0.0) +// AppleClang 11.0.3 __apple_build_version__ == 11030032 gsl_COMPILER_APPLECLANG_VERSION == 1103 (Xcode 11.4, 11.4.1, 11.5, 11.6) (LLVM 9.0.0) +// AppleClang 12.0.0 __apple_build_version__ == 12000032 gsl_COMPILER_APPLECLANG_VERSION == 1200 (Xcode 12.0–12.4) (LLVM 10.0.0) +// AppleClang 12.0.5 __apple_build_version__ == 12050022 gsl_COMPILER_APPLECLANG_VERSION == 1205 (Xcode 12.5) (LLVM 11.1.0) +// AppleClang 13.0.0 __apple_build_version__ == 13000029 gsl_COMPILER_APPLECLANG_VERSION == 1300 (Xcode 13.0) (LLVM 12.0.0) + +#if defined( __apple_build_version__ ) +# define gsl_COMPILER_APPLECLANG_VERSION gsl_COMPILER_VERSION( __clang_major__, __clang_minor__, __clang_patchlevel__ ) +# define gsl_COMPILER_CLANG_VERSION 0 +#elif defined( __clang__ ) +# define gsl_COMPILER_APPLECLANG_VERSION 0 +# define gsl_COMPILER_CLANG_VERSION gsl_COMPILER_VERSION( __clang_major__, __clang_minor__, __clang_patchlevel__ ) #else -# define gsl_COMPILER_CLANG_VERSION 0 +# define gsl_COMPILER_APPLECLANG_VERSION 0 +# define gsl_COMPILER_CLANG_VERSION 0 #endif -#if defined(__GNUC__) && !defined(__clang__) -# define gsl_COMPILER_GNUC_VERSION gsl_COMPILER_VERSION( __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ) +#if defined( __GNUC__ ) && ! defined( __clang__ ) && ! defined( __NVCOMPILER ) +# define gsl_COMPILER_GNUC_VERSION gsl_COMPILER_VERSION( __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ) #else -# define gsl_COMPILER_GNUC_VERSION 0 +# define gsl_COMPILER_GNUC_VERSION 0 #endif -// Method enabling (C++98, VC120 (VS2013) cannot use __VA_ARGS__) - -#define gsl_REQUIRES_0(VA) \ - template< bool B = (VA), typename std::enable_if::type = 0 > - -#define gsl_REQUIRES_T(VA) \ - , typename = typename std::enable_if< (VA), gsl::detail::enabler >::type +#if defined( __NVCC__ ) +# define gsl_COMPILER_NVCC_VERSION ( __CUDACC_VER_MAJOR__ * 10 + __CUDACC_VER_MINOR__ ) +#else +# define gsl_COMPILER_NVCC_VERSION 0 +#endif -#define gsl_REQUIRES_R(R, VA) \ - typename std::enable_if::type +// NVHPC 21.2 gsl_COMPILER_NVHPC_VERSION == 2120 +#if defined( __NVCOMPILER ) +# define gsl_COMPILER_NVHPC_VERSION gsl_COMPILER_VERSION( __NVCOMPILER_MAJOR__, __NVCOMPILER_MINOR__, __NVCOMPILER_PATCHLEVEL__ ) +#else +# define gsl_COMPILER_NVHPC_VERSION 0 +#endif -#define gsl_REQUIRES_A(VA) \ - , typename std::enable_if::type = nullptr +#if defined( __ARMCC_VERSION ) +# define gsl_COMPILER_ARMCC_VERSION ( __ARMCC_VERSION / 10000 ) +# define gsl_COMPILER_ARMCC_VERSION_FULL __ARMCC_VERSION +#else +# define gsl_COMPILER_ARMCC_VERSION 0 +# define gsl_COMPILER_ARMCC_VERSION_FULL 0 +#endif // Compiler non-strict aliasing: @@ -225,10 +604,10 @@ #define gsl_IN_STD( v ) ( ((v) == 98 ? 3 : (v)) >= gsl_CPLUSPLUS_V ) #define gsl_DEPRECATE_TO_LEVEL( level ) ( level <= gsl_CONFIG_DEPRECATE_TO_LEVEL ) -#define gsl_FEATURE_TO_STD( feature ) ( gsl_IN_STD( gsl_FEATURE( feature##_TO_STD ) ) ) -#define gsl_FEATURE( feature ) ( gsl_FEATURE_##feature ) -#define gsl_CONFIG( feature ) ( gsl_CONFIG_##feature ) -#define gsl_HAVE( feature ) ( gsl_HAVE_##feature ) +#define gsl_FEATURE_TO_STD( feature ) gsl_IN_STD( gsl_FEATURE( feature##_TO_STD ) ) +#define gsl_FEATURE( feature ) gsl_EVALF_( gsl_FEATURE_##feature##_ ) +#define gsl_CONFIG( feature ) gsl_EVALF_( gsl_CONFIG_##feature##_ ) +#define gsl_HAVE( feature ) gsl_EVALF_( gsl_HAVE_##feature##_ ) // Presence of wide character support: @@ -237,9 +616,72 @@ #else # define gsl_HAVE_WCHAR 1 #endif +#define gsl_HAVE_WCHAR_() gsl_HAVE_WCHAR + +// Compiling device code: + +#if defined( __CUDACC__ ) && defined( __CUDA_ARCH__ ) +# define gsl_DEVICE_CODE 1 +#else +# define gsl_DEVICE_CODE 0 +#endif + // Presence of language & library features: +#if gsl_COMPILER_CLANG_VERSION || gsl_COMPILER_APPLECLANG_VERSION +# ifdef __OBJC__ + // There are a bunch of inconsistencies about __EXCEPTIONS and __has_feature(cxx_exceptions) in Clang 3.4/3.5/3.6. + // We're interested in C++ exceptions, which can be checked by __has_feature(cxx_exceptions) in 3.5+. + // In pre-3.5, __has_feature(cxx_exceptions) can be true if ObjC exceptions are enabled, but C++ exceptions are disabled. + // The recommended way to check is `__EXCEPTIONS && __has_feature(cxx_exceptions)`. + // See https://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html#the-exceptions-macro + // Note: this is only relevant in Objective-C++, thus the ifdef. +# if __EXCEPTIONS && __has_feature(cxx_exceptions) +# define gsl_HAVE_EXCEPTIONS 1 +# else +# define gsl_HAVE_EXCEPTIONS 0 +# endif // __EXCEPTIONS && __has_feature(cxx_exceptions) +# else + // clang-cl doesn't define __EXCEPTIONS for MSVC compatibility (see https://reviews.llvm.org/D4065). + // Neither does Clang in MS-compatiblity mode. + // Let's hope no one tries to build Objective-C++ code using MS-compatibility mode or clang-cl. +# if __has_feature(cxx_exceptions) +# define gsl_HAVE_EXCEPTIONS 1 +# else +# define gsl_HAVE_EXCEPTIONS 0 +# endif +# endif +#elif defined( __GNUC__ ) +# if __GNUC__ < 5 +# ifdef __EXCEPTIONS +# define gsl_HAVE_EXCEPTIONS 1 +# else +# define gsl_HAVE_EXCEPTIONS 0 +# endif // __EXCEPTIONS +# else +# ifdef __cpp_exceptions +# define gsl_HAVE_EXCEPTIONS 1 +# else +# define gsl_HAVE_EXCEPTIONS 0 +# endif // __cpp_exceptions +# endif // __GNUC__ < 5 +#elif gsl_COMPILER_MSVC_VERSION +# ifdef _CPPUNWIND +# define gsl_HAVE_EXCEPTIONS 1 +# else +# define gsl_HAVE_EXCEPTIONS 0 +# endif // _CPPUNWIND +#else +// For all other compilers, assume exceptions are always enabled. +# define gsl_HAVE_EXCEPTIONS 1 +#endif +#define gsl_HAVE_EXCEPTIONS_() gsl_HAVE_EXCEPTIONS + +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) && ! gsl_HAVE_EXCEPTIONS +# error Cannot use gsl_CONFIG_CONTRACT_VIOLATION_THROWS if exceptions are disabled. +#endif // defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) && !gsl_HAVE( EXCEPTIONS ) + #ifdef _HAS_CPP0X # define gsl_HAS_CPP0X _HAS_CPP0X #else @@ -263,66 +705,158 @@ // Presence of C++11 language features: -#define gsl_HAVE_AUTO gsl_CPP11_100 -#define gsl_HAVE_NULLPTR gsl_CPP11_100 -#define gsl_HAVE_RVALUE_REFERENCE gsl_CPP11_100 - -#define gsl_HAVE_ENUM_CLASS gsl_CPP11_110 - -#define gsl_HAVE_ALIAS_TEMPLATE gsl_CPP11_120 +#define gsl_HAVE_C99_PREPROCESSOR gsl_CPP11_140 +#define gsl_HAVE_AUTO gsl_CPP11_100 +#define gsl_HAVE_RVALUE_REFERENCE gsl_CPP11_100 +#define gsl_HAVE_FUNCTION_REF_QUALIFIER ( gsl_CPP11_140 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 481 ) ) +#define gsl_HAVE_ENUM_CLASS gsl_CPP11_110 +#define gsl_HAVE_ALIAS_TEMPLATE gsl_CPP11_120 #define gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG gsl_CPP11_120 -#define gsl_HAVE_EXPLICIT gsl_CPP11_120 -#define gsl_HAVE_INITIALIZER_LIST gsl_CPP11_120 - -#define gsl_HAVE_CONSTEXPR_11 gsl_CPP11_140 -#define gsl_HAVE_IS_DEFAULT gsl_CPP11_140 -#define gsl_HAVE_IS_DELETE gsl_CPP11_140 -#define gsl_HAVE_NOEXCEPT gsl_CPP11_140 - -#if gsl_CPP11_OR_GREATER -// see above -#endif +#define gsl_HAVE_EXPLICIT gsl_CPP11_120 +#define gsl_HAVE_VARIADIC_TEMPLATE gsl_CPP11_120 +#define gsl_HAVE_IS_DELETE gsl_CPP11_120 +#define gsl_HAVE_CONSTEXPR_11 gsl_CPP11_140 +#define gsl_HAVE_IS_DEFAULT gsl_CPP11_140 +#define gsl_HAVE_NOEXCEPT gsl_CPP11_140 +#define gsl_HAVE_NORETURN ( gsl_CPP11_140 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 480 ) ) +#define gsl_HAVE_EXPRESSION_SFINAE gsl_CPP11_140 +#define gsl_HAVE_OVERRIDE_FINAL gsl_CPP11_110 + +#define gsl_HAVE_C99_PREPROCESSOR_() gsl_HAVE_C99_PREPROCESSOR +#define gsl_HAVE_AUTO_() gsl_HAVE_AUTO +#define gsl_HAVE_RVALUE_REFERENCE_() gsl_HAVE_RVALUE_REFERENCE +#define gsl_HAVE_FUNCTION_REF_QUALIFIER_() gsl_HAVE_FUNCTION_REF_QUALIFIER +#define gsl_HAVE_ENUM_CLASS_() gsl_HAVE_ENUM_CLASS +#define gsl_HAVE_ALIAS_TEMPLATE_() gsl_HAVE_ALIAS_TEMPLATE +#define gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG_() gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG +#define gsl_HAVE_EXPLICIT_() gsl_HAVE_EXPLICIT +#define gsl_HAVE_VARIADIC_TEMPLATE_() gsl_HAVE_VARIADIC_TEMPLATE +#define gsl_HAVE_IS_DELETE_() gsl_HAVE_IS_DELETE +#define gsl_HAVE_CONSTEXPR_11_() gsl_HAVE_CONSTEXPR_11 +#define gsl_HAVE_IS_DEFAULT_() gsl_HAVE_IS_DEFAULT +#define gsl_HAVE_NOEXCEPT_() gsl_HAVE_NOEXCEPT +#define gsl_HAVE_NORETURN_() gsl_HAVE_NORETURN +#define gsl_HAVE_EXPRESSION_SFINAE_() gsl_HAVE_EXPRESSION_SFINAE +#define gsl_HAVE_OVERRIDE_FINAL_() gsl_HAVE_OVERRIDE_FINAL // Presence of C++14 language features: -#define gsl_HAVE_CONSTEXPR_14 gsl_CPP14_000 -#define gsl_HAVE_DECLTYPE_AUTO gsl_CPP14_140 +#define gsl_HAVE_CONSTEXPR_14 ( gsl_CPP14_000 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 600 ) ) +#define gsl_HAVE_DECLTYPE_AUTO gsl_CPP14_140 +#define gsl_HAVE_DEPRECATED ( gsl_CPP14_140 && ! gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 142 ) ) + +#define gsl_HAVE_CONSTEXPR_14_() gsl_HAVE_CONSTEXPR_14 +#define gsl_HAVE_DECLTYPE_AUTO_() gsl_HAVE_DECLTYPE_AUTO +#define gsl_HAVE_DEPRECATED_() gsl_HAVE_DEPRECATED // Presence of C++17 language features: // MSVC: template parameter deduction guides since Visual Studio 2017 v15.7 #define gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE gsl_CPP17_000 -#define gsl_HAVE_DEDUCTION_GUIDES (gsl_CPP17_000 && ! gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 999 ) ) - -// Presence of C++ library features: - -#define gsl_HAVE_ADDRESSOF gsl_CPP17_000 -#define gsl_HAVE_ARRAY gsl_CPP11_110 -#define gsl_HAVE_TYPE_TRAITS gsl_CPP11_110 -#define gsl_HAVE_TR1_TYPE_TRAITS gsl_CPP11_110 +#define gsl_HAVE_DEDUCTION_GUIDES ( gsl_CPP17_000 && ! gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION_FULL, 1, 1414 ) ) +#define gsl_HAVE_NODISCARD gsl_CPP17_000 +#define gsl_HAVE_CONSTEXPR_17 gsl_CPP17_OR_GREATER -#define gsl_HAVE_CONTAINER_DATA_METHOD gsl_CPP11_140_CPP0X_90 -#define gsl_HAVE_STD_DATA gsl_CPP17_000 +#define gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE_() gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE +#define gsl_HAVE_DEDUCTION_GUIDES_() gsl_HAVE_DEDUCTION_GUIDES +#define gsl_HAVE_NODISCARD_() gsl_HAVE_NODISCARD +#define gsl_HAVE_CONSTEXPR_17_() gsl_HAVE_CONSTEXPR_17 -#define gsl_HAVE_SIZED_TYPES gsl_CPP11_140 +// Presence of C++20 language features: -#define gsl_HAVE_MAKE_SHARED gsl_CPP11_140_CPP0X_100 -#define gsl_HAVE_SHARED_PTR gsl_CPP11_140_CPP0X_100 -#define gsl_HAVE_UNIQUE_PTR gsl_CPP11_140_CPP0X_100 +#define gsl_HAVE_CONSTEXPR_20 gsl_CPP20_OR_GREATER -#define gsl_HAVE_MAKE_UNIQUE gsl_CPP14_120 +#define gsl_HAVE_CONSTEXPR_20_() gsl_HAVE_CONSTEXPR_20 -#define gsl_HAVE_UNCAUGHT_EXCEPTIONS gsl_CPP17_140 +// Presence of C++ library features: -#define gsl_HAVE_ADD_CONST gsl_HAVE_TYPE_TRAITS -#define gsl_HAVE_INTEGRAL_CONSTANT gsl_HAVE_TYPE_TRAITS -#define gsl_HAVE_REMOVE_CONST gsl_HAVE_TYPE_TRAITS -#define gsl_HAVE_REMOVE_REFERENCE gsl_HAVE_TYPE_TRAITS +#if gsl_BETWEEN( gsl_COMPILER_ARMCC_VERSION, 1, 600 ) +// Some versions of the ARM compiler apparently ship without a C++11 standard library despite having some C++11 support. +# define gsl_STDLIB_CPP98_OR_GREATER gsl_CPP98_OR_GREATER +# define gsl_STDLIB_CPP11_OR_GREATER 0 +# define gsl_STDLIB_CPP14_OR_GREATER 0 +# define gsl_STDLIB_CPP17_OR_GREATER 0 +# define gsl_STDLIB_CPP20_OR_GREATER 0 +#else +# define gsl_STDLIB_CPP98_OR_GREATER gsl_CPP98_OR_GREATER +# define gsl_STDLIB_CPP11_OR_GREATER gsl_CPP11_OR_GREATER +# define gsl_STDLIB_CPP14_OR_GREATER gsl_CPP14_OR_GREATER +# define gsl_STDLIB_CPP17_OR_GREATER gsl_CPP17_OR_GREATER +# define gsl_STDLIB_CPP20_OR_GREATER gsl_CPP20_OR_GREATER +#endif -#define gsl_HAVE_TR1_ADD_CONST gsl_HAVE_TR1_TYPE_TRAITS -#define gsl_HAVE_TR1_INTEGRAL_CONSTANT gsl_HAVE_TR1_TYPE_TRAITS -#define gsl_HAVE_TR1_REMOVE_CONST gsl_HAVE_TR1_TYPE_TRAITS -#define gsl_HAVE_TR1_REMOVE_REFERENCE gsl_HAVE_TR1_TYPE_TRAITS +#define gsl_STDLIB_CPP11_100 (gsl_STDLIB_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1600) +#define gsl_STDLIB_CPP11_110 (gsl_STDLIB_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1700) +#define gsl_STDLIB_CPP11_120 (gsl_STDLIB_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1800) +#define gsl_STDLIB_CPP11_140 (gsl_STDLIB_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1900) + +#define gsl_STDLIB_CPP14_000 (gsl_STDLIB_CPP14_OR_GREATER) +#define gsl_STDLIB_CPP14_120 (gsl_STDLIB_CPP14_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1800) +#define gsl_STDLIB_CPP14_140 (gsl_STDLIB_CPP14_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1900) + +#define gsl_STDLIB_CPP17_000 (gsl_STDLIB_CPP17_OR_GREATER) +#define gsl_STDLIB_CPP17_140 (gsl_STDLIB_CPP17_OR_GREATER || gsl_COMPILER_MSVC_VER >= 1900) + +#define gsl_STDLIB_CPP11_140_CPP0X_90 (gsl_STDLIB_CPP11_140 || (gsl_COMPILER_MSVC_VER >= 1500 && gsl_HAS_CPP0X)) +#define gsl_STDLIB_CPP11_140_CPP0X_100 (gsl_STDLIB_CPP11_140 || (gsl_COMPILER_MSVC_VER >= 1600 && gsl_HAS_CPP0X)) + +#define gsl_HAVE_ADDRESSOF gsl_STDLIB_CPP17_000 +#define gsl_HAVE_ARRAY gsl_STDLIB_CPP11_110 +#define gsl_HAVE_TYPE_TRAITS gsl_STDLIB_CPP11_110 +#define gsl_HAVE_TR1_TYPE_TRAITS gsl_STDLIB_CPP11_110 +#define gsl_HAVE_CONTAINER_DATA_METHOD gsl_STDLIB_CPP11_140_CPP0X_90 +#define gsl_HAVE_STD_DATA gsl_STDLIB_CPP17_000 +#ifdef __cpp_lib_ssize +# define gsl_HAVE_STD_SSIZE 1 +#else +# define gsl_HAVE_STD_SSIZE ( gsl_COMPILER_GNUC_VERSION >= 1000 && __cplusplus > 201703L ) +#endif +#define gsl_HAVE_HASH gsl_STDLIB_CPP11_120 +#define gsl_HAVE_SIZED_TYPES gsl_STDLIB_CPP11_140 +#define gsl_HAVE_MAKE_SHARED gsl_STDLIB_CPP11_140_CPP0X_100 +#define gsl_HAVE_SHARED_PTR gsl_STDLIB_CPP11_140_CPP0X_100 +#define gsl_HAVE_UNIQUE_PTR gsl_STDLIB_CPP11_140_CPP0X_100 +#define gsl_HAVE_MAKE_UNIQUE gsl_STDLIB_CPP14_120 +#define gsl_HAVE_MOVE_FORWARD gsl_STDLIB_CPP11_100 +#define gsl_HAVE_NULLPTR gsl_STDLIB_CPP11_100 +#define gsl_HAVE_UNCAUGHT_EXCEPTIONS gsl_STDLIB_CPP17_140 +#define gsl_HAVE_ADD_CONST gsl_HAVE_TYPE_TRAITS +#define gsl_HAVE_INITIALIZER_LIST gsl_STDLIB_CPP11_120 +#define gsl_HAVE_INTEGRAL_CONSTANT gsl_HAVE_TYPE_TRAITS +#define gsl_HAVE_REMOVE_CONST gsl_HAVE_TYPE_TRAITS +#define gsl_HAVE_REMOVE_REFERENCE gsl_HAVE_TYPE_TRAITS +#define gsl_HAVE_REMOVE_CVREF gsl_STDLIB_CPP20_OR_GREATER +#define gsl_HAVE_TR1_ADD_CONST gsl_HAVE_TR1_TYPE_TRAITS +#define gsl_HAVE_TR1_INTEGRAL_CONSTANT gsl_HAVE_TR1_TYPE_TRAITS +#define gsl_HAVE_TR1_REMOVE_CONST gsl_HAVE_TR1_TYPE_TRAITS +#define gsl_HAVE_TR1_REMOVE_REFERENCE gsl_HAVE_TR1_TYPE_TRAITS + +#define gsl_HAVE_ADDRESSOF_() gsl_HAVE_ADDRESSOF +#define gsl_HAVE_ARRAY_() gsl_HAVE_ARRAY +#define gsl_HAVE_TYPE_TRAITS_() gsl_HAVE_TYPE_TRAITS +#define gsl_HAVE_TR1_TYPE_TRAITS_() gsl_HAVE_TR1_TYPE_TRAITS +#define gsl_HAVE_CONTAINER_DATA_METHOD_() gsl_HAVE_CONTAINER_DATA_METHOD +#define gsl_HAVE_HASH_() gsl_HAVE_HASH +#define gsl_HAVE_STD_DATA_() gsl_HAVE_STD_DATA +#define gsl_HAVE_STD_SSIZE_() gsl_HAVE_STD_SSIZE +#define gsl_HAVE_SIZED_TYPES_() gsl_HAVE_SIZED_TYPES +#define gsl_HAVE_MAKE_SHARED_() gsl_HAVE_MAKE_SHARED +#define gsl_HAVE_MOVE_FORWARD_() gsl_HAVE_MOVE_FORWARD +#define gsl_HAVE_NULLPTR_() gsl_HAVE_NULLPTR // It's a language feature but needs library support, so we list it as a library feature. +#define gsl_HAVE_SHARED_PTR_() gsl_HAVE_SHARED_PTR +#define gsl_HAVE_UNIQUE_PTR_() gsl_HAVE_UNIQUE_PTR +#define gsl_HAVE_MAKE_UNIQUE_() gsl_HAVE_MAKE_UNIQUE +#define gsl_HAVE_UNCAUGHT_EXCEPTIONS_() gsl_HAVE_UNCAUGHT_EXCEPTIONS +#define gsl_HAVE_ADD_CONST_() gsl_HAVE_ADD_CONST +#define gsl_HAVE_INITIALIZER_LIST_() gsl_HAVE_INITIALIZER_LIST // It's a language feature but needs library support, so we list it as a library feature. +#define gsl_HAVE_INTEGRAL_CONSTANT_() gsl_HAVE_INTEGRAL_CONSTANT +#define gsl_HAVE_REMOVE_CONST_() gsl_HAVE_REMOVE_CONST +#define gsl_HAVE_REMOVE_REFERENCE_() gsl_HAVE_REMOVE_REFERENCE +#define gsl_HAVE_REMOVE_CVREF_() gsl_HAVE_REMOVE_CVREF +#define gsl_HAVE_TR1_ADD_CONST_() gsl_HAVE_TR1_ADD_CONST +#define gsl_HAVE_TR1_INTEGRAL_CONSTANT_() gsl_HAVE_TR1_INTEGRAL_CONSTANT +#define gsl_HAVE_TR1_REMOVE_CONST_() gsl_HAVE_TR1_REMOVE_CONST +#define gsl_HAVE_TR1_REMOVE_REFERENCE_() gsl_HAVE_TR1_REMOVE_REFERENCE // C++ feature usage: @@ -333,21 +867,33 @@ #endif #if gsl_HAVE( CONSTEXPR_11 ) -# define gsl_constexpr constexpr +# define gsl_constexpr constexpr #else -# define gsl_constexpr /*constexpr*/ +# define gsl_constexpr /*constexpr*/ #endif #if gsl_HAVE( CONSTEXPR_14 ) -# define gsl_constexpr14 constexpr +# define gsl_constexpr14 constexpr +#else +# define gsl_constexpr14 /*constexpr*/ +#endif + +#if gsl_HAVE( CONSTEXPR_17 ) +# define gsl_constexpr17 constexpr +#else +# define gsl_constexpr17 /*constexpr*/ +#endif + +#if gsl_HAVE( CONSTEXPR_20 ) +# define gsl_constexpr20 constexpr #else -# define gsl_constexpr14 /*constexpr*/ +# define gsl_constexpr20 /*constexpr*/ #endif #if gsl_HAVE( EXPLICIT ) -# define gsl_explicit explicit +# define gsl_explicit explicit #else -# define gsl_explicit /*explicit*/ +# define gsl_explicit /*explicit*/ #endif #if gsl_FEATURE( IMPLICIT_MACRO ) @@ -355,21 +901,28 @@ #endif #if gsl_HAVE( IS_DELETE ) -# define gsl_is_delete = delete +# define gsl_is_delete = delete #else # define gsl_is_delete #endif #if gsl_HAVE( IS_DELETE ) -# define gsl_is_delete_access public +# define gsl_is_delete_access public #else -# define gsl_is_delete_access private +# define gsl_is_delete_access private #endif -#if !gsl_HAVE( NOEXCEPT ) || gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) -# define gsl_noexcept /*noexcept*/ +#if gsl_HAVE( NOEXCEPT ) +# define gsl_noexcept noexcept +# define gsl_noexcept_if( expr ) noexcept( expr ) +#else +# define gsl_noexcept throw() +# define gsl_noexcept_if( expr ) /*noexcept( expr )*/ +#endif +#if defined( gsl_TESTING_ ) +# define gsl_noexcept_not_testing #else -# define gsl_noexcept noexcept +# define gsl_noexcept_not_testing gsl_noexcept #endif #if gsl_HAVE( NULLPTR ) @@ -378,19 +931,181 @@ # define gsl_nullptr NULL #endif +#if gsl_HAVE( NODISCARD ) +# define gsl_NODISCARD [[nodiscard]] +#else +# define gsl_NODISCARD +#endif + +#if gsl_HAVE( NORETURN ) +# define gsl_NORETURN [[noreturn]] +#elif defined(_MSC_VER) +# define gsl_NORETURN __declspec(noreturn) +#elif defined( __GNUC__ ) || gsl_COMPILER_ARMCC_VERSION +# define gsl_NORETURN __attribute__((noreturn)) +#else +# define gsl_NORETURN +#endif + +#if gsl_HAVE( DEPRECATED ) && ! defined( gsl_TESTING_ ) +# define gsl_DEPRECATED [[deprecated]] +# define gsl_DEPRECATED_MSG( msg ) [[deprecated( msg )]] +#else +# define gsl_DEPRECATED +# define gsl_DEPRECATED_MSG( msg ) +#endif + +#if gsl_HAVE( C99_PREPROCESSOR ) +# if gsl_CPP20_OR_GREATER +# define gsl_CONSTRAINT(...) __VA_ARGS__ +# else +# define gsl_CONSTRAINT(...) typename +# endif +#endif + +#if gsl_HAVE( TYPE_TRAITS ) +# define gsl_STATIC_ASSERT_( cond, msg ) static_assert( cond, msg ) +#else +# define gsl_STATIC_ASSERT_( cond, msg ) ( ( void )sizeof( char[1 - 2*!!( cond ) ] ) ) +#endif + +#if gsl_HAVE( TYPE_TRAITS ) + +#define gsl_DEFINE_ENUM_BITMASK_OPERATORS_( ENUM ) \ + gsl_NODISCARD gsl_api inline gsl_constexpr ENUM \ + operator~( ENUM val ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return ENUM( ~U( val ) ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr ENUM \ + operator|( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return ENUM( U( lhs ) | U( rhs ) ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr ENUM \ + operator&( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return ENUM( U( lhs ) & U( rhs ) ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr ENUM \ + operator^( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return ENUM( U( lhs ) ^ U( rhs ) ); \ + } \ + gsl_api inline gsl_constexpr14 ENUM & \ + operator|=( ENUM & lhs, ENUM rhs ) gsl_noexcept \ + { \ + return lhs = lhs | rhs; \ + } \ + gsl_api inline gsl_constexpr14 ENUM & \ + operator&=( ENUM & lhs, ENUM rhs ) gsl_noexcept \ + { \ + return lhs = lhs & rhs; \ + } \ + gsl_api inline gsl_constexpr14 ENUM & \ + operator^=( ENUM & lhs, ENUM rhs ) gsl_noexcept \ + { \ + return lhs = lhs ^ rhs; \ + } + +#define gsl_DEFINE_ENUM_RELATIONAL_OPERATORS_( ENUM ) \ + gsl_NODISCARD gsl_api inline gsl_constexpr bool \ + operator<( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return U( lhs ) < U( rhs ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr bool \ + operator>( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return U( lhs ) > U( rhs ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr bool \ + operator<=( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return U( lhs ) <= U( rhs ); \ + } \ + gsl_NODISCARD gsl_api inline gsl_constexpr bool \ + operator>=( ENUM lhs, ENUM rhs ) gsl_noexcept \ + { \ + typedef typename ::gsl::std11::underlying_type::type U; \ + return U( lhs ) >= U( rhs ); \ + } + + // + // Defines bitmask operators `|`, `&`, `^`, `~`, `|=`, `&=`, and `^=` for the given enum type. + // + // enum class Vegetables { tomato = 0b001, onion = 0b010, eggplant = 0b100 }; + // gsl_DEFINE_ENUM_BITMASK_OPERATORS( Vegetables ) + // +#define gsl_DEFINE_ENUM_BITMASK_OPERATORS( ENUM ) gsl_DEFINE_ENUM_BITMASK_OPERATORS_( ENUM ) + + // + // Defines relational operators `<`, `>`, `<=`, `>=` for the given enum type. + // + // enum class OperatorPrecedence { additive = 0, multiplicative = 1, power = 2 }; + // gsl_DEFINE_ENUM_RELATIONAL_OPERATORS( OperatorPrecedence ) + // +#define gsl_DEFINE_ENUM_RELATIONAL_OPERATORS( ENUM ) gsl_DEFINE_ENUM_RELATIONAL_OPERATORS_( ENUM ) + +#endif // gsl_HAVE( TYPE_TRAITS ) + #define gsl_DIMENSION_OF( a ) ( sizeof(a) / sizeof(0[a]) ) + +// Method enabling (C++98, VC120 (VS2013) cannot use __VA_ARGS__) + +#if gsl_HAVE( EXPRESSION_SFINAE ) +# define gsl_TRAILING_RETURN_TYPE_(T) auto +# define gsl_RETURN_DECLTYPE_(EXPR) -> decltype( EXPR ) +#else +# define gsl_TRAILING_RETURN_TYPE_(T) T +# define gsl_RETURN_DECLTYPE_(EXPR) +#endif + +// NOTE: When using SFINAE in gsl-lite, please note that overloads of function templates must always use SFINAE with non-type default arguments +// as explained in https://en.cppreference.com/w/cpp/types/enable_if#Notes. `gsl_ENABLE_IF_()` implements graceful fallback to default +// type arguments (for compilers that don't support non-type default arguments); please verify that this is appropriate in the given +// situation, and add additional checks if necessary. +// +// Also, please note that `gsl_ENABLE_IF_()` doesn't enforce the constraint at all if no compiler/library support is available (i.e. pre-C++11). + +#if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) +# if !gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 140 ) // VS 2013 seems to have trouble with SFINAE for default non-type arguments +# define gsl_ENABLE_IF_(VA) , typename std::enable_if< ( VA ), int >::type = 0 +# else +# define gsl_ENABLE_IF_(VA) , typename = typename std::enable_if< ( VA ), ::gsl::detail::enabler >::type +# endif +#else +# define gsl_ENABLE_IF_(VA) +#endif + + // Other features: -#define gsl_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR \ - ( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG && gsl_HAVE_CONTAINER_DATA_METHOD ) +#define gsl_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR ( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG && gsl_HAVE_CONTAINER_DATA_METHOD ) +#define gsl_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR_() gsl_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR -// Note: !defined(__NVCC__) doesn't work with nvcc here: -#define gsl_HAVE_UNCONSTRAINED_SPAN_CONTAINER_CTOR \ - ( gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR && (__NVCC__== 0) ) +#define gsl_HAVE_UNCONSTRAINED_SPAN_CONTAINER_CTOR ( gsl_CONFIG_ALLOWS_UNCONSTRAINED_SPAN_CONTAINER_CTOR && gsl_COMPILER_NVCC_VERSION == 0 ) +#define gsl_HAVE_UNCONSTRAINED_SPAN_CONTAINER_CTOR_() gsl_HAVE_UNCONSTRAINED_SPAN_CONTAINER_CTOR // GSL API (e.g. for CUDA platform): +// Guidelines for using `gsl_api`: +// +// NVCC imposes the restriction that a function annotated `__host__ __device__` cannot call host-only or device-only functions. +// This makes `gsl_api` inappropriate for generic functions that call unknown code, e.g. the template constructors of `span<>` +// or functions like `finally()` which accept an arbitrary function object. +// It is often preferable to annotate functions only with `gsl_constexpr` or `gsl_constexpr14`. The "extended constexpr" mode +// of NVCC (currently an experimental feature) will implicitly consider constexpr functions `__host__ __device__` functions +// but tolerates calls to host-only or device-only functions. + #ifndef gsl_api # ifdef __CUDACC__ # define gsl_api __host__ __device__ @@ -401,28 +1116,79 @@ // Additional includes: +#if ! gsl_CPP11_OR_GREATER +# include // for swap() before C++11 +#endif // ! gsl_CPP11_OR_GREATER + #if gsl_HAVE( ARRAY ) -# include +# include // indirectly includes reverse_iterator<> +#endif + +#if ! gsl_HAVE( ARRAY ) +# include // for reverse_iterator<> +#endif + +#if ! gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) || ! gsl_HAVE( AUTO ) +# include +#endif + +#if gsl_HAVE( INITIALIZER_LIST ) +# include +#endif + +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) || gsl_DEVICE_CODE +# include +#endif + +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) && gsl_COMPILER_MSVC_VERSION >= 110 // __fastfail() supported by VS 2012 and later +# include +#endif + +#if gsl_HAVE( ENUM_CLASS ) && ( gsl_COMPILER_ARMCC_VERSION || gsl_COMPILER_NVHPC_VERSION ) && !defined( _WIN32 ) +# include #endif #if gsl_HAVE( TYPE_TRAITS ) -# include +# include // for enable_if<>, + // add_const<>, add_pointer<>, common_type<>, make_signed<>, remove_cv<>, remove_const<>, remove_volatile<>, remove_reference<>, remove_cvref<>, remove_pointer<>, underlying_type<>, + // is_assignable<>, is_constructible<>, is_const<>, is_convertible<>, is_integral<>, is_pointer<>, is_signed<>, + // integral_constant<>, declval() #elif gsl_HAVE( TR1_TYPE_TRAITS ) -# include +# include // for add_const<>, remove_cv<>, remove_const<>, remove_volatile<>, remove_reference<>, integral_constant<> #endif -#if gsl_HAVE( SIZED_TYPES ) -# include -#endif +#if gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) + +// Declare __cxa_get_globals() or equivalent in namespace gsl::detail for uncaught_exceptions(): + +# if ! gsl_HAVE( UNCAUGHT_EXCEPTIONS ) +# if defined( _MSC_VER ) // MS-STL with either MSVC or clang-cl +namespace gsl { namespace detail { extern "C" char * __cdecl _getptd(); } } +# elif gsl_COMPILER_CLANG_VERSION || gsl_COMPILER_GNUC_VERSION || gsl_COMPILER_APPLECLANG_VERSION || gsl_COMPILER_NVHPC_VERSION +# if defined( __GLIBCXX__ ) || defined( __GLIBCPP__ ) // libstdc++: prototype from cxxabi.h +# include +# elif ! defined( BOOST_CORE_UNCAUGHT_EXCEPTIONS_HPP_INCLUDED_ ) // libc++: prototype from Boost? +# if defined( __FreeBSD__ ) || defined( __OpenBSD__ ) +namespace __cxxabiv1 { struct __cxa_eh_globals; extern "C" __cxa_eh_globals * __cxa_get_globals(); } +# else +namespace __cxxabiv1 { struct __cxa_eh_globals; extern "C" __cxa_eh_globals * __cxa_get_globals() gsl_noexcept; } +# endif +# endif + namespace gsl { namespace detail { using ::__cxxabiv1::__cxa_get_globals; } } +# endif +# endif // ! gsl_HAVE( UNCAUGHT_EXCEPTIONS ) +#endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) + // MSVC warning suppression macros: -#if gsl_COMPILER_MSVC_VERSION >= 140 +#if gsl_COMPILER_MSVC_VERSION >= 140 && ! gsl_COMPILER_NVCC_VERSION # define gsl_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] # define gsl_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress: code) ) # define gsl_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) # define gsl_RESTORE_MSVC_WARNINGS() __pragma(warning(pop )) #else +// TODO: define for Clang # define gsl_SUPPRESS_MSGSL_WARNING(expr) # define gsl_SUPPRESS_MSVC_WARNING(code, descr) # define gsl_DISABLE_MSVC_WARNINGS(codes) @@ -430,19 +1196,24 @@ #endif // Suppress the following MSVC GSL warnings: -// - C26410: gsl::r.32: the parameter 'ptr' is a reference to const unique pointer, use const T* or const T& instead -// - C26415: gsl::r.30: smart pointer parameter 'ptr' is used only to access contained pointer. Use T* or T& instead -// - C26418: gsl::r.36: shared pointer parameter 'ptr' is not copied or moved. Use T* or T& instead -// - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; -// use brace initialization, gsl::narrow_cast or gsl::narow -// - C26439, gsl::f.6 : special function 'function' can be declared 'noexcept' -// - C26440, gsl::f.6 : function 'function' can be declared 'noexcept' -// - C26473: gsl::t.1 : don't cast between pointer types where the source type and the target type are the same -// - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead -// - C26482, gsl::b.2 : only index into arrays using constant expressions -// - C26490: gsl::t.1 : don't use reinterpret_cast - -gsl_DISABLE_MSVC_WARNINGS( 26410 26415 26418 26472 26439 26440 26473 26481 26482 26490 ) +// - C26432: gsl::c.21 : if you define or delete any default operation in the type '...', define or delete them all +// - C26410: gsl::r.32 : the parameter 'ptr' is a reference to const unique pointer, use const T* or const T& instead +// - C26415: gsl::r.30 : smart pointer parameter 'ptr' is used only to access contained pointer. Use T* or T& instead +// - C26418: gsl::r.36 : shared pointer parameter 'ptr' is not copied or moved. Use T* or T& instead +// - C26472: gsl::t.1 : don't use a static_cast for arithmetic conversions; +// use brace initialization, gsl::narrow_cast or gsl::narrow +// - C26439: gsl::f.6 : special function 'function' can be declared 'noexcept' +// - C26440: gsl::f.6 : function 'function' can be declared 'noexcept' +// - C26455: gsl::f.6 : default constructor may not throw. Declare it 'noexcept' +// - C26473: gsl::t.1 : don't cast between pointer types where the source type and the target type are the same +// - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead +// - C26482: gsl::b.2 : only index into arrays using constant expressions +// - C26446: gdl::b.4 : prefer to use gsl::at() instead of unchecked subscript operator +// - C26490: gsl::t.1 : don't use reinterpret_cast +// - C26487: gsl::l.4 : don't return a pointer '('s result)' that may be invalid +// - C26457: es.48 : (void) should not be used to ignore return values, use 'std::ignore =' instead + +gsl_DISABLE_MSVC_WARNINGS( 26432 26410 26415 26418 26472 26439 26440 26455 26473 26481 26482 26446 26490 26487 26457 ) namespace gsl { @@ -451,6 +1222,35 @@ namespace gsl { template< class T > class span; +// C++98 emulation: + +namespace detail { + +// We implement `equal()` and `lexicographical_compare()` here to avoid having to pull in the header. +template< class InputIt1, class InputIt2 > +bool equal( InputIt1 first1, InputIt1 last1, InputIt2 first2 ) +{ + // Implementation borrowed from https://en.cppreference.com/w/cpp/algorithm/equal. + for ( ; first1 != last1; ++first1, ++first2 ) + { + if ( ! (*first1 == *first2 ) ) return false; + } + return true; +} +template< class InputIt1, class InputIt2 > +bool lexicographical_compare( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2 ) +{ + // Implementation borrowed from https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare. + for ( ; first1 != last1 && first2 != last2; ++first1, (void) ++first2 ) + { + if ( *first1 < *first2 ) return true; + if ( *first2 < *first1 ) return false; + } + return first1 == last1 && first2 != last2; +} + +} // namespace detail + // C++11 emulation: namespace std11 { @@ -497,66 +1297,375 @@ struct remove_cv #endif // gsl_HAVE( REMOVE_CONST ) -#if gsl_HAVE( INTEGRAL_CONSTANT ) +#if gsl_HAVE( REMOVE_REFERENCE ) -using std::integral_constant; -using std::true_type; -using std::false_type; +using std::remove_reference; -#elif gsl_HAVE( TR1_INTEGRAL_CONSTANT ) +#elif gsl_HAVE( TR1_REMOVE_REFERENCE ) -using std::tr1::integral_constant; +using std::tr1::remove_reference; + +#else + +template< class T > struct remove_reference { typedef T type; }; +template< class T > struct remove_reference { typedef T type; }; +# if gsl_HAVE( RVALUE_REFERENCE ) +template< class T > struct remove_reference { typedef T type; }; +# endif + +#endif // gsl_HAVE( REMOVE_REFERENCE ) + + +#if gsl_HAVE( INTEGRAL_CONSTANT ) + +using std::integral_constant; +using std::true_type; +using std::false_type; + +#elif gsl_HAVE( TR1_INTEGRAL_CONSTANT ) + +using std::tr1::integral_constant; using std::tr1::true_type; using std::tr1::false_type; #else -template< int v > struct integral_constant { enum { value = v }; }; -typedef integral_constant< true > true_type; -typedef integral_constant< false > false_type; +template< class T, T v > struct integral_constant { enum { value = v }; }; +typedef integral_constant< bool, true > true_type; +typedef integral_constant< bool, false > false_type; + +#endif + +#if gsl_HAVE( TYPE_TRAITS ) + +using std::underlying_type; + +#elif gsl_HAVE( TR1_TYPE_TRAITS ) + +using std::tr1::underlying_type; + +#else + +// We could try to define `underlying_type<>` for pre-C++11 here, but let's not until someone actually needs it. #endif } // namespace std11 +// C++14 emulation: + +namespace std14 { + +#if gsl_HAVE( UNIQUE_PTR ) +# if gsl_HAVE( MAKE_UNIQUE ) + +using std::make_unique; + +# elif gsl_HAVE( VARIADIC_TEMPLATE ) + +template< class T, class... Args > +gsl_NODISCARD std::unique_ptr +make_unique( Args &&... args ) +{ +# if gsl_HAVE( TYPE_TRAITS ) + static_assert( !std::is_array::value, "make_unique() is not part of C++14" ); +# endif + return std::unique_ptr( new T( std::forward( args )... ) ); +} + +# endif // gsl_HAVE( MAKE_UNIQUE ), gsl_HAVE( VARIADIC_TEMPLATE ) +#endif // gsl_HAVE( UNIQUE_PTR ) + +} // namespace std14 + +namespace detail { + +#if gsl_HAVE( VARIADIC_TEMPLATE ) + +template < bool V0, class T0, class... Ts > struct conjunction_ { using type = T0; }; +template < class T0, class T1, class... Ts > struct conjunction_ : conjunction_ { }; +template < bool V0, class T0, class... Ts > struct disjunction_ { using type = T0; }; +template < class T0, class T1, class... Ts > struct disjunction_ : disjunction_ { }; + +#endif + +template struct dependent_false : std11::integral_constant { }; + +} // namespace detail + +// C++17 emulation: + +namespace std17 { + +template< bool v > struct bool_constant : std11::integral_constant{}; + +#if gsl_CPP11_120 + +template < class... Ts > struct conjunction; +template < > struct conjunction< > : std11::true_type { }; +template < class T0, class... Ts > struct conjunction : detail::conjunction_::type { }; +template < class... Ts > struct disjunction; +template < > struct disjunction< > : std11::false_type { }; +template < class T0, class... Ts > struct disjunction : detail::disjunction_::type { }; +template < class T > struct negation : std11::integral_constant { }; + +# if gsl_CPP14_OR_GREATER + +template < class... Ts > constexpr bool conjunction_v = conjunction::value; +template < class... Ts > constexpr bool disjunction_v = disjunction::value; +template < class T > constexpr bool negation_v = negation::value; + +# endif // gsl_CPP14_OR_GREATER + +template< class... Ts > +struct make_void { typedef void type; }; + +template< class... Ts > +using void_t = typename make_void< Ts... >::type; + +#endif // gsl_CPP11_120 + +#if gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) + +template< class T, size_t N > +gsl_NODISCARD gsl_api inline gsl_constexpr auto +size( T const(&)[N] ) gsl_noexcept -> size_t +{ + return N; +} + +template< class C > +gsl_NODISCARD inline gsl_constexpr auto +size( C const & cont ) -> decltype( cont.size() ) +{ + return cont.size(); +} + +template< class T, size_t N > +gsl_NODISCARD gsl_api inline gsl_constexpr auto +data( T(&arr)[N] ) gsl_noexcept -> T* +{ + return &arr[0]; +} + +template< class C > +gsl_NODISCARD inline gsl_constexpr auto +data( C & cont ) -> decltype( cont.data() ) +{ + return cont.data(); +} + +template< class C > +gsl_NODISCARD inline gsl_constexpr auto +data( C const & cont ) -> decltype( cont.data() ) +{ + return cont.data(); +} + +template< class E > +gsl_NODISCARD inline gsl_constexpr auto +data( std::initializer_list il ) gsl_noexcept -> E const * +{ + return il.begin(); +} + +#endif // gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) + +} // namespace std17 + +// C++20 emulation: + +namespace std20 { + +#if gsl_CPP11_100 + +struct identity +{ + template < class T > + gsl_constexpr T && operator ()( T && arg ) const gsl_noexcept + { + return std::forward( arg ); + } +}; + +# if gsl_HAVE( ENUM_CLASS ) +enum class endian +{ +# if defined( _WIN32 ) + little = 0, + big = 1, + native = little +# elif gsl_COMPILER_GNUC_VERSION || gsl_COMPILER_CLANG_VERSION || gsl_COMPILER_APPLECLANG_VERSION + little = __ORDER_LITTLE_ENDIAN__, + big = __ORDER_BIG_ENDIAN__, + native = __BYTE_ORDER__ +# elif gsl_COMPILER_ARMCC_VERSION || gsl_COMPILER_NVHPC_VERSION + // from header file + little = __LITTLE_ENDIAN, + big = __BIG_ENDIAN, + native = __BYTE_ORDER +# else +// Do not define any endianness constants for unknown compilers. +# endif +}; +# endif // gsl_HAVE( ENUM_CLASS ) + +#endif // gsl_CPP11_100 + +template< class T > +struct type_identity +{ + typedef T type; +}; +#if gsl_HAVE( ALIAS_TEMPLATE ) +template< class T > +using type_identity_t = typename type_identity::type; +#endif // gsl_HAVE( ALIAS_TEMPLATE ) + +#if gsl_HAVE( STD_SSIZE ) + +using std::ssize; + +#elif gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) + +template < class C > +gsl_NODISCARD gsl_constexpr auto +ssize( C const & c ) + -> typename std::common_type::type>::type +{ + using R = typename std::common_type::type>::type; + return static_cast( c.size() ); +} + +template +gsl_NODISCARD gsl_constexpr auto +ssize( T const(&)[N] ) gsl_noexcept -> std::ptrdiff_t +{ + return std::ptrdiff_t( N ); +} + +#endif // gsl_HAVE( STD_SSIZE ) + +#if gsl_HAVE( REMOVE_CVREF ) + +using std::remove_cvref; + +#else + +template< class T > struct remove_cvref { typedef typename std11::remove_cv< typename std11::remove_reference< T >::type >::type type; }; + +#endif // gsl_HAVE( REMOVE_CVREF ) + +} // namespace std20 + namespace detail { -/// for nsel_REQUIRES_T +/// for gsl_ENABLE_IF_() /*enum*/ class enabler{}; #if gsl_HAVE( TYPE_TRAITS ) template< class Q > -struct is_span_oracle : std11::false_type{}; +struct is_span_oracle : std::false_type{}; template< class T> -struct is_span_oracle< span > : std11::true_type{}; +struct is_span_oracle< span > : std::true_type{}; template< class Q > -struct is_span : is_span_oracle< typename std11::remove_cv::type >{}; +struct is_span : is_span_oracle< typename std::remove_cv::type >{}; template< class Q > -struct is_std_array_oracle : std11::false_type{}; +struct is_std_array_oracle : std::false_type{}; -#if gsl_HAVE( ARRAY ) +# if gsl_HAVE( ARRAY ) template< class T, std::size_t Extent > -struct is_std_array_oracle< std::array > : std11::true_type{}; +struct is_std_array_oracle< std::array > : std::true_type{}; -#endif +# endif template< class Q > -struct is_std_array : is_std_array_oracle< typename std11::remove_cv::type >{}; +struct is_std_array : is_std_array_oracle< typename std::remove_cv::type >{}; template< class Q > -struct is_array : std11::false_type {}; +struct is_array : std::false_type{}; template< class T > -struct is_array : std11::true_type {}; +struct is_array : std::true_type{}; template< class T, std::size_t N > -struct is_array : std11::true_type {}; +struct is_array : std::true_type{}; + +# if gsl_CPP11_140 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 500 ) + +template< class, class = void > +struct has_size_and_data : std::false_type{}; + +template< class C > +struct has_size_and_data +< + C, std17::void_t< + decltype( std17::size(std::declval()) ), + decltype( std17::data(std::declval()) ) > +> : std::true_type{}; + +template< class, class, class = void > +struct is_compatible_element : std::false_type {}; + +template< class C, class E > +struct is_compatible_element +< + C, E, std17::void_t< + decltype( std17::data(std::declval()) ), + typename std::remove_pointer() ) )>::type(*)[] > +> : std::is_convertible< typename std::remove_pointer() ) )>::type(*)[], E(*)[] >{}; + +template< class C > +struct is_container : std17::bool_constant +< + ! is_span< C >::value + && ! is_array< C >::value + && ! is_std_array< C >::value + && has_size_and_data< C >::value +>{}; + +template< class C, class E > +struct is_compatible_container : std17::bool_constant +< + is_container::value + && is_compatible_element::value +>{}; + +# else // ^^^ gsl_CPP11_140 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 500 ) ^^^ / vvv ! gsl_CPP11_140 || gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 500 ) vvv + +template< + class C, class E + , typename = typename std::enable_if< + ! is_span< C >::value + && ! is_array< C >::value + && ! is_std_array< C >::value + && ( std::is_convertible< typename std::remove_pointer() ) )>::type(*)[], E(*)[] >::value) + // && has_size_and_data< C >::value + , enabler>::type + , class = decltype( std17::size(std::declval()) ) + , class = decltype( std17::data(std::declval()) ) +> +# if gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 140 ) +// VS2013 has insufficient support for expression SFINAE; we cannot make `is_compatible_container<>` a proper type trait here +struct is_compatible_container : std::true_type { }; +# else +struct is_compatible_container_r { is_compatible_container_r(int); }; +template< class C, class E > +std::true_type is_compatible_container_f( is_compatible_container_r ); +template< class C, class E > +std::false_type is_compatible_container_f( ... ); + +template< class C, class E > +struct is_compatible_container : decltype( is_compatible_container_f< C, E >( 0 ) ) { }; +# endif // gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 140 ) + +# endif // gsl_CPP11_140 && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 1, 500 ) #endif // gsl_HAVE( TYPE_TRAITS ) @@ -566,8 +1675,17 @@ struct is_array : std11::true_type {}; // GSL.util: utilities // -// index type for all container indexes/subscripts/sizes -typedef gsl_CONFIG_SPAN_INDEX_TYPE index; // p0122r3 uses std::ptrdiff_t +// Integer type for indices (e.g. in a loop). +typedef gsl_CONFIG_INDEX_TYPE index; + +// Integer type for dimensions. +typedef gsl_CONFIG_INDEX_TYPE dim; + +// Integer type for array strides. +typedef gsl_CONFIG_INDEX_TYPE stride; + +// Integer type for pointer, iterator, or index differences. +typedef gsl_CONFIG_INDEX_TYPE diff; // // GSL.owner: ownership pointers @@ -575,27 +1693,24 @@ typedef gsl_CONFIG_SPAN_INDEX_TYPE index; // p0122r3 uses std::ptrdiff_t #if gsl_HAVE( SHARED_PTR ) using std::unique_ptr; using std::shared_ptr; - using std::make_shared; -# if gsl_HAVE( MAKE_UNIQUE ) - using std::make_unique; -# endif #endif #if gsl_HAVE( ALIAS_TEMPLATE ) -# if gsl_HAVE( TYPE_TRAITS ) template< class T - gsl_REQUIRES_T( std::is_pointer::value ) +#if gsl_HAVE( TYPE_TRAITS ) + , typename = typename std::enable_if< std::is_pointer::value >::type +#endif > using owner = T; -# else - template< class T > using owner = T; -# endif -#else +#elif gsl_CONFIG( DEFAULTS_VERSION ) == 0 + // TODO vNext: remove template< class T > struct owner { typedef T type; }; #endif -#define gsl_HAVE_OWNER_TEMPLATE gsl_HAVE_ALIAS_TEMPLATE +#define gsl_HAVE_OWNER_TEMPLATE gsl_HAVE_ALIAS_TEMPLATE +#define gsl_HAVE_OWNER_TEMPLATE_() gsl_HAVE_OWNER_TEMPLATE +// TODO vNext: remove #if gsl_FEATURE( OWNER_MACRO ) # if gsl_HAVE( OWNER_TEMPLATE ) # define Owner(t) ::gsl::owner @@ -608,82 +1723,263 @@ typedef gsl_CONFIG_SPAN_INDEX_TYPE index; // p0122r3 uses std::ptrdiff_t // GSL.assert: assertions // -#define gsl_ELIDE_CONTRACT_EXPECTS ( 0 == ( gsl_CONFIG_CONTRACT_LEVEL_MASK & 0x01 ) ) -#define gsl_ELIDE_CONTRACT_ENSURES ( 0 == ( gsl_CONFIG_CONTRACT_LEVEL_MASK & 0x10 ) ) +#if gsl_HAVE( TYPE_TRAITS ) +# define gsl_ELIDE_( x ) static_assert( ::std::is_constructible::value, "argument of contract check must be convertible to bool" ) +#else +# define gsl_ELIDE_( x ) +#endif +#define gsl_NO_OP_() ( static_cast( 0 ) ) -#if gsl_ELIDE_CONTRACT_EXPECTS -# define Expects( x ) /* Expects elided */ -#elif gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) -# define Expects( x ) ::gsl::fail_fast_assert( (x), "GSL: Precondition failure at " __FILE__ ":" gsl_STRINGIFY(__LINE__) ); +#if gsl_COMPILER_NVHPC_VERSION +// Suppress "controlling expression is constant" warning when using `gsl_Expects()`, `gsl_Ensures()`, `gsl_Assert()`, etc. +# define gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ _Pragma("diag_suppress 236") +# define gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ _Pragma("diag_default 236") #else -# define Expects( x ) ::gsl::fail_fast_assert( (x) ) +# define gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ +# define gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ +#endif + +#if gsl_DEVICE_CODE +# if defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME ) +# if gsl_COMPILER_NVCC_VERSION >= 113 +# define gsl_ASSUME_( x ) ( ( x ) ? static_cast(0) : __builtin_unreachable() ) +# define gsl_ASSUME_UNREACHABLE_() __builtin_unreachable() +# else // unknown device compiler +# error gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ASSUME: gsl-lite does not know how to generate UB optimization hints in device code for this compiler; use gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE instead +# endif +# define gsl_CONTRACT_UNENFORCED_( x ) gsl_ASSUME_( x ) +# else // defined( gsl_CONFIG_DEVICE_UNENFORCED_CONTRACTS_ELIDE ) [default] +# define gsl_CONTRACT_UNENFORCED_( x ) gsl_ELIDE_( x ) +# endif +#else // host code +# if defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME ) +# if gsl_COMPILER_MSVC_VERSION >= 140 +# define gsl_ASSUME_( x ) __assume( x ) +# define gsl_ASSUME_UNREACHABLE_() __assume( 0 ) +# elif gsl_COMPILER_GNUC_VERSION +# define gsl_ASSUME_( x ) ( ( x ) ? static_cast(0) : __builtin_unreachable() ) +# define gsl_ASSUME_UNREACHABLE_() __builtin_unreachable() +# elif defined(__has_builtin) +# if __has_builtin(__builtin_unreachable) +# define gsl_ASSUME_( x ) ( ( x ) ? static_cast(0) : __builtin_unreachable() ) +# define gsl_ASSUME_UNREACHABLE_() __builtin_unreachable() +# else +# error gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME: gsl-lite does not know how to generate UB optimization hints for this compiler; use gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE instead +# endif +# else +# error gsl_CONFIG_UNENFORCED_CONTRACTS_ASSUME: gsl-lite does not know how to generate UB optimization hints for this compiler; use gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE instead +# endif +# define gsl_CONTRACT_UNENFORCED_( x ) gsl_ASSUME_( x ) +# else // defined( gsl_CONFIG_UNENFORCED_CONTRACTS_ELIDE ) [default] +# define gsl_CONTRACT_UNENFORCED_( x ) gsl_ELIDE_( x ) +# endif +#endif // gsl_DEVICE_CODE + +#if gsl_DEVICE_CODE +# if gsl_COMPILER_NVCC_VERSION +# define gsl_TRAP_() __trap() +# elif defined(__has_builtin) +# if __has_builtin(__builtin_trap) +# define gsl_TRAP_() __builtin_trap() +# else +# error gsl-lite does not know how to generate a trap instruction for this device compiler +# endif +# else +# error gsl-lite does not know how to generate a trap instruction for this device compiler +# endif +# if defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_TRAPS ) +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( x ) ? static_cast(0) : gsl_TRAP_() gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( gsl_TRAP_() ) +# elif defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_CALLS_HANDLER ) +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( x ) ? static_cast(0) : ::gsl::fail_fast_assert_handler( #x, str, __FILE__, __LINE__ ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( ::gsl::fail_fast_assert_handler( "", "GSL: failure", __FILE__, __LINE__ ), gsl_TRAP_() ) /* do not let the custom assertion handler continue execution */ +# else // defined( gsl_CONFIG_DEVICE_CONTRACT_VIOLATION_ASSERTS ) [default] +# if ! defined( NDEBUG ) +# define gsl_CONTRACT_CHECK_( str, x ) assert( str && ( x ) ) +# else +# define gsl_CONTRACT_CHECK_( str, x ) ( ( x ) ? static_cast(0) : gsl_TRAP_() ) +# endif +# define gsl_FAILFAST_() ( gsl_TRAP_() ) +# endif +#else // host code +# if defined( gsl_CONFIG_CONTRACT_VIOLATION_TRAPS ) +# if gsl_COMPILER_MSVC_VERSION >= 110 // __fastfail() supported by VS 2012 and later +# define gsl_TRAP_() __fastfail( 0 ) /* legacy failure code for buffer-overrun errors, cf. winnt.h, "Fast fail failure codes" */ +# elif gsl_COMPILER_GNUC_VERSION +# define gsl_TRAP_() __builtin_trap() +# elif defined(__has_builtin) +# if __has_builtin(__builtin_trap) +# define gsl_TRAP_() __builtin_trap() +# else +# error gsl_CONFIG_CONTRACT_VIOLATION_TRAPS: gsl-lite does not know how to generate a trap instruction for this compiler; use gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES instead +# endif +# else +# error gsl_CONFIG_CONTRACT_VIOLATION_TRAPS: gsl-lite does not know how to generate a trap instruction for this compiler; use gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES instead +# endif +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( x ) ? static_cast(0) : gsl_TRAP_() gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# if gsl_COMPILER_MSVC_VERSION +# define gsl_FAILFAST_() ( gsl_TRAP_(), ::gsl::detail::fail_fast_terminate() ) +# else +# define gsl_FAILFAST_() ( gsl_TRAP_() ) +# endif +# elif defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( x ) ? static_cast(0) : ::gsl::fail_fast_assert_handler( #x, str, __FILE__, __LINE__ ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( ::gsl::fail_fast_assert_handler( "", "GSL: failure", __FILE__, __LINE__ ), ::gsl::detail::fail_fast_terminate() ) /* do not let the custom assertion handler continue execution */ +# elif defined( gsl_CONFIG_CONTRACT_VIOLATION_ASSERTS ) +# if ! defined( NDEBUG ) +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ assert( str && ( x ) ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ assert( ! "GSL: failure" ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_, ::gsl::detail::fail_fast_abort() ) +# else +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( x ) ? static_cast(0) : ::gsl::detail::fail_fast_abort() gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( ::gsl::detail::fail_fast_abort() ) +# endif +# elif defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( ( x ) ? static_cast(0) : ::gsl::detail::fail_fast_throw( str ": '" #x "' at " __FILE__ ":" gsl_STRINGIFY(__LINE__) ) ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( ::gsl::detail::fail_fast_throw( "GSL: failure at " __FILE__ ":" gsl_STRINGIFY(__LINE__) ) ) +# else // defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) [default] +# define gsl_CONTRACT_CHECK_( str, x ) ( gsl_SUPPRESS_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ( ( x ) ? static_cast(0) : ::gsl::detail::fail_fast_terminate() ) gsl_RESTORE_NVHPC_CONTROLLING_EXPRESSION_IS_CONSTANT_ ) +# define gsl_FAILFAST_() ( ::gsl::detail::fail_fast_terminate() ) +# endif +#endif // gsl_DEVICE_CODE + +#if ( !gsl_DEVICE_CODE && defined( gsl_CONFIG_CONTRACT_CHECKING_OFF ) ) || ( gsl_DEVICE_CODE && defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_OFF ) ) +# define gsl_CHECK_CONTRACTS_ 0 +# define gsl_CHECK_DEBUG_CONTRACTS_ 0 +# define gsl_CHECK_AUDIT_CONTRACTS_ 0 +#elif ( !gsl_DEVICE_CODE && defined( gsl_CONFIG_CONTRACT_CHECKING_AUDIT ) ) || ( gsl_DEVICE_CODE && defined( gsl_CONFIG_DEVICE_CONTRACT_CHECKING_AUDIT ) ) +# define gsl_CHECK_CONTRACTS_ 1 +# define gsl_CHECK_DEBUG_CONTRACTS_ 1 +# define gsl_CHECK_AUDIT_CONTRACTS_ 1 +#else // gsl_CONFIG_[DEVICE_]CONTRACT_CHECKING_ON [default] +# define gsl_CHECK_CONTRACTS_ 1 +# if !defined( NDEBUG ) +# define gsl_CHECK_DEBUG_CONTRACTS_ 1 +# else // defined( NDEBUG ) +# define gsl_CHECK_DEBUG_CONTRACTS_ 0 +# endif +# define gsl_CHECK_AUDIT_CONTRACTS_ 0 #endif -#if gsl_ELIDE_CONTRACT_EXPECTS -# define gsl_EXPECTS_UNUSED_PARAM( x ) /* Make param unnamed if Expects elided */ +#if gsl_CHECK_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF ) +# define gsl_Expects( x ) gsl_CONTRACT_CHECK_( "GSL: Precondition failure", x ) +#else +# define gsl_Expects( x ) gsl_CONTRACT_UNENFORCED_( x ) +#endif +#define Expects( x ) gsl_Expects( x ) +#if gsl_CHECK_DEBUG_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF ) +# define gsl_ExpectsDebug( x ) gsl_CONTRACT_CHECK_( "GSL: Precondition failure (debug)", x ) +#else +# define gsl_ExpectsDebug( x ) gsl_ELIDE_( x ) +#endif +#if gsl_CHECK_AUDIT_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_EXPECTS_OFF ) +# define gsl_ExpectsAudit( x ) gsl_CONTRACT_CHECK_( "GSL: Precondition failure (audit)", x ) #else -# define gsl_EXPECTS_UNUSED_PARAM( x ) x +# define gsl_ExpectsAudit( x ) gsl_ELIDE_( x ) #endif -#if gsl_ELIDE_CONTRACT_ENSURES -# define Ensures( x ) /* Ensures elided */ -#elif gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) -# define Ensures( x ) ::gsl::fail_fast_assert( (x), "GSL: Postcondition failure at " __FILE__ ":" gsl_STRINGIFY(__LINE__) ); +#if gsl_CHECK_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF ) +# define gsl_Ensures( x ) gsl_CONTRACT_CHECK_( "GSL: Postcondition failure", x ) +#else +# define gsl_Ensures( x ) gsl_CONTRACT_UNENFORCED_( x ) +#endif +#define Ensures( x ) gsl_Ensures( x ) +#if gsl_CHECK_DEBUG_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF ) +# define gsl_EnsuresDebug( x ) gsl_CONTRACT_CHECK_( "GSL: Postcondition failure (debug)", x ) +#else +# define gsl_EnsuresDebug( x ) gsl_ELIDE_( x ) +#endif +#if gsl_CHECK_AUDIT_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ENSURES_OFF ) +# define gsl_EnsuresAudit( x ) gsl_CONTRACT_CHECK_( "GSL: Postcondition failure (audit)", x ) #else -# define Ensures( x ) ::gsl::fail_fast_assert( (x) ) +# define gsl_EnsuresAudit( x ) gsl_ELIDE_( x ) #endif -#define gsl_STRINGIFY( x ) gsl_STRINGIFY_( x ) -#define gsl_STRINGIFY_( x ) #x +#if gsl_CHECK_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF ) +# define gsl_Assert( x ) gsl_CONTRACT_CHECK_( "GSL: Assertion failure", x ) +#else +# define gsl_Assert( x ) gsl_CONTRACT_UNENFORCED_( x ) +#endif +#if gsl_CHECK_DEBUG_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF ) +# define gsl_AssertDebug( x ) gsl_CONTRACT_CHECK_( "GSL: Assertion failure (debug)", x ) +#else +# define gsl_AssertDebug( x ) gsl_ELIDE_( x ) +#endif +#if gsl_CHECK_AUDIT_CONTRACTS_ && !defined( gsl_CONFIG_CONTRACT_CHECKING_ASSERT_OFF ) +# define gsl_AssertAudit( x ) gsl_CONTRACT_CHECK_( "GSL: Assertion failure (audit)", x ) +#else +# define gsl_AssertAudit( x ) gsl_ELIDE_( x ) +#endif + +#define gsl_FailFast() gsl_FAILFAST_() + +#undef gsl_CHECK_CONTRACTS_ +#undef gsl_CHECK_DEBUG_CONTRACTS_ +#undef gsl_CHECK_AUDIT_CONTRACTS_ + struct fail_fast : public std::logic_error { - gsl_api explicit fail_fast( char const * const message ) + explicit fail_fast( char const * message ) : std::logic_error( message ) {} }; -// workaround for gcc 5 throw/terminate constexpr bug: - -#if gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 430, 600 ) && gsl_HAVE( CONSTEXPR_14 ) +namespace detail { -# if gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) -gsl_api inline gsl_constexpr14 auto fail_fast_assert( bool cond, char const * const message ) -> void +#if gsl_HAVE( EXCEPTIONS ) +gsl_NORETURN inline void fail_fast_throw( char const * message ) { - !cond ? throw fail_fast( message ) : 0; + throw fail_fast( message ); } - -# else - -gsl_api inline gsl_constexpr14 auto fail_fast_assert( bool cond ) -> void +#endif // gsl_HAVE( EXCEPTIONS ) +gsl_NORETURN inline void fail_fast_terminate() gsl_noexcept { - struct F { static gsl_constexpr14 void f(){}; }; - - !cond ? std::terminate() : F::f(); + std::terminate(); +} +gsl_NORETURN inline void fail_fast_abort() gsl_noexcept +{ + std::abort(); } -# endif +} // namespace detail -#else // workaround +// Should be defined by user +gsl_api void fail_fast_assert_handler( char const * const expression, char const * const message, char const * const file, int line ); -# if gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#if defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) -gsl_api inline gsl_constexpr14 void fail_fast_assert( bool cond, char const * const message ) +# if gsl_HAVE( EXCEPTIONS ) +gsl_DEPRECATED_MSG("don't call gsl::fail_fast_assert() directly; use contract checking macros instead") +gsl_constexpr14 inline +void fail_fast_assert( bool cond, char const * const message ) { if ( !cond ) throw fail_fast( message ); } +# endif // gsl_HAVE( EXCEPTIONS ) -# else +#elif defined( gsl_CONFIG_CONTRACT_VIOLATION_CALLS_HANDLER ) + +gsl_DEPRECATED_MSG("don't call gsl::fail_fast_assert() directly; use contract checking macros instead") +gsl_api gsl_constexpr14 inline +void fail_fast_assert( bool cond, char const * const expression, char const * const message, char const * const file, int line ) +{ + if ( !cond ) + ::gsl::fail_fast_assert_handler( expression, message, file, line ); +} + +#else // defined( gsl_CONFIG_CONTRACT_VIOLATION_TERMINATES ) [default] -gsl_api inline gsl_constexpr14 void fail_fast_assert( bool cond ) gsl_noexcept +gsl_DEPRECATED_MSG("don't call gsl::fail_fast_assert() directly; use contract checking macros instead") +gsl_constexpr14 inline +void fail_fast_assert( bool cond ) gsl_noexcept { if ( !cond ) std::terminate(); } -# endif -#endif // workaround +#endif + // // GSL.util: utilities @@ -694,74 +1990,71 @@ gsl_api inline gsl_constexpr14 void fail_fast_assert( bool cond ) gsl_noexcept // Add uncaught_exceptions for pre-2017 MSVC, GCC and Clang // Return unsigned char to save stack space, uncaught_exceptions can only increase by 1 in a scope -namespace detail { - -inline unsigned char to_uchar( unsigned x ) gsl_noexcept -{ - return static_cast( x ); -} - -} // namespace detail - namespace std11 { -#if gsl_HAVE( UNCAUGHT_EXCEPTIONS ) +# if gsl_HAVE( UNCAUGHT_EXCEPTIONS ) inline unsigned char uncaught_exceptions() gsl_noexcept { - return detail::to_uchar( std::uncaught_exceptions() ); + return static_cast( std::uncaught_exceptions() ); } -#elif gsl_COMPILER_MSVC_VERSION +# else // ! gsl_HAVE( UNCAUGHT_EXCEPTIONS ) +# if defined( _MSC_VER ) // MS-STL with either MSVC or clang-cl -extern "C" char * __cdecl _getptd(); inline unsigned char uncaught_exceptions() gsl_noexcept { - return detail::to_uchar( *reinterpret_cast(_getptd() + (sizeof(void*) == 8 ? 0x100 : 0x90) ) ); + return static_cast( *reinterpret_cast( detail::_getptd() + (sizeof(void *) == 8 ? 0x100 : 0x90 ) ) ); } -#elif gsl_COMPILER_CLANG_VERSION || gsl_COMPILER_GNUC_VERSION +# elif gsl_COMPILER_CLANG_VERSION || gsl_COMPILER_GNUC_VERSION || gsl_COMPILER_APPLECLANG_VERSION || gsl_COMPILER_NVHPC_VERSION -extern "C" char * __cxa_get_globals(); inline unsigned char uncaught_exceptions() gsl_noexcept { - return detail::to_uchar( *reinterpret_cast(__cxa_get_globals() + sizeof(void*) ) ); + return static_cast( ( *reinterpret_cast( reinterpret_cast(detail::__cxa_get_globals()) + sizeof(void *) ) ) ); } -#endif + +# endif +# endif + } // namespace std11 -#endif -#if gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 110 +#endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) + +#if gsl_STDLIB_CPP11_110 + +gsl_DISABLE_MSVC_WARNINGS( 4702 ) // unreachable code template< class F > class final_action { public: - gsl_api explicit final_action( F action ) gsl_noexcept + explicit final_action( F action ) gsl_noexcept : action_( std::move( action ) ) , invoke_( true ) {} - gsl_api final_action( final_action && other ) gsl_noexcept + final_action( final_action && other ) gsl_noexcept : action_( std::move( other.action_ ) ) , invoke_( other.invoke_ ) { other.invoke_ = false; } - gsl_api virtual ~final_action() gsl_noexcept + gsl_SUPPRESS_MSGSL_WARNING(f.6) + virtual ~final_action() gsl_noexcept { if ( invoke_ ) action_(); } gsl_is_delete_access: - gsl_api final_action( final_action const & ) gsl_is_delete; - gsl_api final_action & operator=( final_action const & ) gsl_is_delete; - gsl_api final_action & operator=( final_action && ) gsl_is_delete; + final_action( final_action const & ) gsl_is_delete; + final_action & operator=( final_action const & ) gsl_is_delete; + final_action & operator=( final_action && ) gsl_is_delete; protected: - gsl_api void dismiss() gsl_noexcept + void dismiss() gsl_noexcept { invoke_ = false; } @@ -772,55 +2065,59 @@ class final_action }; template< class F > -gsl_api inline final_action finally( F const & action ) gsl_noexcept +gsl_NODISCARD inline final_action +finally( F const & action ) gsl_noexcept { return final_action( action ); } template< class F > -gsl_api inline final_action finally( F && action ) gsl_noexcept +gsl_NODISCARD inline final_action +finally( F && action ) gsl_noexcept { return final_action( std::forward( action ) ); } -#if gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) +# if gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) template< class F > class final_action_return : public final_action { public: - gsl_api explicit final_action_return( F && action ) gsl_noexcept + explicit final_action_return( F && action ) gsl_noexcept : final_action( std::move( action ) ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api final_action_return( final_action_return && other ) gsl_noexcept + final_action_return( final_action_return && other ) gsl_noexcept : final_action( std::move( other ) ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api ~final_action_return() override + ~final_action_return() override { if ( std11::uncaught_exceptions() != exception_count ) this->dismiss(); } gsl_is_delete_access: - gsl_api final_action_return( final_action_return const & ) gsl_is_delete; - gsl_api final_action_return & operator=( final_action_return const & ) gsl_is_delete; + final_action_return( final_action_return const & ) gsl_is_delete; + final_action_return & operator=( final_action_return const & ) gsl_is_delete; private: unsigned char exception_count; }; template< class F > -gsl_api inline final_action_return on_return( F const & action ) gsl_noexcept +gsl_NODISCARD inline final_action_return +on_return( F const & action ) gsl_noexcept { return final_action_return( action ); } template< class F > -gsl_api inline final_action_return on_return( F && action ) gsl_noexcept +gsl_NODISCARD inline final_action_return +on_return( F && action ) gsl_noexcept { return final_action_return( std::forward( action ) ); } @@ -829,77 +2126,81 @@ template< class F > class final_action_error : public final_action { public: - gsl_api explicit final_action_error( F && action ) gsl_noexcept + explicit final_action_error( F && action ) gsl_noexcept : final_action( std::move( action ) ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api final_action_error( final_action_error && other ) gsl_noexcept + final_action_error( final_action_error && other ) gsl_noexcept : final_action( std::move( other ) ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api ~final_action_error() override + ~final_action_error() override { if ( std11::uncaught_exceptions() == exception_count ) this->dismiss(); } gsl_is_delete_access: - gsl_api final_action_error( final_action_error const & ) gsl_is_delete; - gsl_api final_action_error & operator=( final_action_error const & ) gsl_is_delete; + final_action_error( final_action_error const & ) gsl_is_delete; + final_action_error & operator=( final_action_error const & ) gsl_is_delete; private: unsigned char exception_count; }; template< class F > -gsl_api inline final_action_error on_error( F const & action ) gsl_noexcept +gsl_NODISCARD inline final_action_error +on_error( F const & action ) gsl_noexcept { return final_action_error( action ); } template< class F > -gsl_api inline final_action_error on_error( F && action ) gsl_noexcept +gsl_NODISCARD inline final_action_error +on_error( F && action ) gsl_noexcept { return final_action_error( std::forward( action ) ); } -#endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) +# endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) + +gsl_RESTORE_MSVC_WARNINGS() -#else // gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 110 +#else // ! gsl_STDLIB_CPP11_110 class final_action { public: typedef void (*Action)(); - gsl_api final_action( Action action ) + final_action( Action action ) : action_( action ) , invoke_( true ) {} - gsl_api final_action( final_action const & other ) + final_action( final_action const & other ) : action_( other.action_ ) , invoke_( other.invoke_ ) { other.invoke_ = false; } - gsl_api virtual ~final_action() + virtual ~final_action() { if ( invoke_ ) action_(); } protected: - gsl_api void dismiss() + void dismiss() { invoke_ = false; } private: - gsl_api final_action & operator=( final_action const & ); + final_action & operator=( final_action const & ); private: Action action_; @@ -907,7 +2208,7 @@ class final_action }; template< class F > -gsl_api inline final_action finally( F const & f ) +inline final_action finally( F const & f ) { return final_action(( f )); } @@ -917,26 +2218,26 @@ gsl_api inline final_action finally( F const & f ) class final_action_return : public final_action { public: - gsl_api explicit final_action_return( Action action ) + explicit final_action_return( Action action ) : final_action( action ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api ~final_action_return() + ~final_action_return() { if ( std11::uncaught_exceptions() != exception_count ) this->dismiss(); } private: - gsl_api final_action_return & operator=( final_action_return const & ); + final_action_return & operator=( final_action_return const & ); private: unsigned char exception_count; }; template< class F > -gsl_api inline final_action_return on_return( F const & action ) +inline final_action_return on_return( F const & action ) { return final_action_return( action ); } @@ -944,72 +2245,120 @@ gsl_api inline final_action_return on_return( F const & action ) class final_action_error : public final_action { public: - gsl_api explicit final_action_error( Action action ) + explicit final_action_error( Action action ) : final_action( action ) , exception_count( std11::uncaught_exceptions() ) {} - gsl_api ~final_action_error() + ~final_action_error() { if ( std11::uncaught_exceptions() == exception_count ) this->dismiss(); } private: - gsl_api final_action_error & operator=( final_action_error const & ); + final_action_error & operator=( final_action_error const & ); private: unsigned char exception_count; }; template< class F > -gsl_api inline final_action_error on_error( F const & action ) +inline final_action_error on_error( F const & action ) { return final_action_error( action ); } -#endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) +# endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) -#endif // gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION == 110 +#endif // gsl_STDLIB_CPP11_110 -#if gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 120 +#if gsl_STDLIB_CPP11_120 template< class T, class U > -gsl_api inline gsl_constexpr T narrow_cast( U && u ) gsl_noexcept +gsl_NODISCARD gsl_api inline gsl_constexpr T +narrow_cast( U && u ) gsl_noexcept { return static_cast( std::forward( u ) ); } -#else +#else // ! gsl_STDLIB_CPP11_120 template< class T, class U > -gsl_api inline T narrow_cast( U u ) gsl_noexcept +gsl_api inline T +narrow_cast( U u ) gsl_noexcept { return static_cast( u ); } -#endif // gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 120 +#endif // gsl_STDLIB_CPP11_120 -struct narrowing_error : public std::exception {}; +struct narrowing_error : public std::exception +{ + char const * what() const gsl_noexcept +#if gsl_HAVE( OVERRIDE_FINAL ) + override +#endif + { + return "narrowing_error"; + } +}; #if gsl_HAVE( TYPE_TRAITS ) -namespace detail -{ +namespace detail { + template< class T, class U > - struct is_same_signedness : public std::integral_constant::value == std::is_signed::value> - {}; -} + struct is_same_signedness : public std::integral_constant::value == std::is_signed::value> {}; + +# if gsl_COMPILER_NVCC_VERSION || gsl_COMPILER_NVHPC_VERSION + // We do this to circumvent NVCC warnings about pointless unsigned comparisons with 0. + template< class T > + gsl_constexpr gsl_api bool is_negative( T value, std::true_type /*isSigned*/ ) gsl_noexcept + { + return value < T(); + } + template< class T > + gsl_constexpr gsl_api bool is_negative( T /*value*/, std::false_type /*isUnsigned*/ ) gsl_noexcept + { + return false; + } + template< class T, class U > + gsl_constexpr gsl_api bool have_same_sign( T, U, std::true_type /*isSameSignedness*/ ) gsl_noexcept + { + return true; + } + template< class T, class U > + gsl_constexpr gsl_api bool have_same_sign( T t, U u, std::false_type /*isSameSignedness*/ ) gsl_noexcept + { + return detail::is_negative( t, std::is_signed() ) == detail::is_negative( u, std::is_signed() ); + } +# endif // gsl_COMPILER_NVCC_VERSION || gsl_COMPILER_NVHPC_VERSION + +} // namespace detail + #endif template< class T, class U > -gsl_api inline T narrow( U u ) +gsl_NODISCARD +#if !gsl_CONFIG( NARROW_THROWS_ON_TRUNCATION ) && !defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) +gsl_api +#endif +inline T +narrow( U u ) { - T t = narrow_cast( u ); +#if gsl_CONFIG( NARROW_THROWS_ON_TRUNCATION ) && ! gsl_HAVE( EXCEPTIONS ) + gsl_STATIC_ASSERT_( detail::dependent_false< T >::value, + "According to the GSL specification, narrow<>() throws an exception of type narrowing_error on truncation. Therefore " + "it cannot be used if exceptions are disabled. Consider using narrow_failfast<>() instead which raises a precondition " + "violation if the given value cannot be represented in the target type." ); +#endif + + T t = static_cast( u ); if ( static_cast( t ) != u ) { -#if gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#if gsl_HAVE( EXCEPTIONS ) && ( gsl_CONFIG( NARROW_THROWS_ON_TRUNCATION ) || defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) ) throw narrowing_error(); #else std::terminate(); @@ -1017,68 +2366,114 @@ gsl_api inline T narrow( U u ) } #if gsl_HAVE( TYPE_TRAITS ) -# if gsl_COMPILER_MSVC_VERSION - // Suppress MSVC level 4 warning C4127 (conditional expression is constant) - if ( 0, ! detail::is_same_signedness::value && ( ( t < T() ) != ( u < U() ) ) ) +# if gsl_COMPILER_NVCC_VERSION || gsl_COMPILER_NVHPC_VERSION + if ( ! detail::have_same_sign( t, u, detail::is_same_signedness() ) ) # else - if ( ! detail::is_same_signedness::value && ( ( t < T() ) != ( u < U() ) ) ) + gsl_SUPPRESS_MSVC_WARNING( 4127, "conditional expression is constant" ) + if ( ! detail::is_same_signedness::value && ( t < T() ) != ( u < U() ) ) # endif #else // Don't assume T() works: + gsl_SUPPRESS_MSVC_WARNING( 4127, "conditional expression is constant" ) +# if gsl_COMPILER_NVHPC_VERSION + // Suppress: pointless comparison of unsigned integer with zero. +# pragma diag_suppress 186 +# endif if ( ( t < 0 ) != ( u < 0 ) ) +# if gsl_COMPILER_NVHPC_VERSION + // Restore: pointless comparison of unsigned integer with zero. +# pragma diag_default 186 +# endif + #endif { -#if gsl_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#if gsl_HAVE( EXCEPTIONS ) && ( gsl_CONFIG( NARROW_THROWS_ON_TRUNCATION ) || defined( gsl_CONFIG_CONTRACT_VIOLATION_THROWS ) ) throw narrowing_error(); #else std::terminate(); #endif } + + return t; +} + +template< class T, class U > +gsl_NODISCARD gsl_api inline T +narrow_failfast( U u ) +{ + T t = static_cast( u ); + + gsl_Expects( static_cast( t ) == u ); + +#if gsl_HAVE( TYPE_TRAITS ) +# if gsl_COMPILER_NVCC_VERSION || gsl_COMPILER_NVHPC_VERSION + gsl_Expects( ::gsl::detail::have_same_sign( t, u, ::gsl::detail::is_same_signedness() ) ); +# else + gsl_SUPPRESS_MSVC_WARNING( 4127, "conditional expression is constant" ) + gsl_Expects( ( ::gsl::detail::is_same_signedness::value || ( t < T() ) == ( u < U() ) ) ); +# endif +#else + // Don't assume T() works: + gsl_SUPPRESS_MSVC_WARNING( 4127, "conditional expression is constant" ) +# if gsl_COMPILER_NVHPC_VERSION + // Suppress: pointless comparison of unsigned integer with zero. +# pragma diag_suppress 186 +# endif + gsl_Expects( ( t < 0 ) == ( u < 0 ) ); +# if gsl_COMPILER_NVHPC_VERSION + // Restore: pointless comparison of unsigned integer with zero. +# pragma diag_default 186 +# endif +#endif + return t; } + // // at() - Bounds-checked way of accessing static arrays, std::array, std::vector. // template< class T, size_t N > -gsl_api inline gsl_constexpr14 T & at( T(&arr)[N], size_t index ) +gsl_NODISCARD gsl_api inline gsl_constexpr14 T & +at( T(&arr)[N], size_t pos ) { - Expects( index < N ); - return arr[index]; + gsl_Expects( pos < N ); + return arr[pos]; } -#if gsl_HAVE( ARRAY ) - -template< class T, size_t N > -gsl_api inline gsl_constexpr14 T & at( std::array & arr, size_t index ) +template< class Container > +gsl_NODISCARD gsl_api inline gsl_constexpr14 typename Container::value_type & +at( Container & cont, size_t pos ) { - Expects( index < N ); - return arr[index]; + gsl_Expects( pos < cont.size() ); + return cont[pos]; } -#endif template< class Container > -gsl_api inline gsl_constexpr14 typename Container::value_type & at( Container & cont, size_t index ) +gsl_NODISCARD gsl_api inline gsl_constexpr14 typename Container::value_type const & +at( Container const & cont, size_t pos ) { - Expects( index < cont.size() ); - return cont[index]; + gsl_Expects( pos < cont.size() ); + return cont[pos]; } #if gsl_HAVE( INITIALIZER_LIST ) template< class T > -gsl_api inline const gsl_constexpr14 T & at( std::initializer_list cont, size_t index ) +gsl_NODISCARD gsl_api inline const gsl_constexpr14 T +at( std::initializer_list cont, size_t pos ) { - Expects( index < cont.size() ); - return *( cont.begin() + index ); + gsl_Expects( pos < cont.size() ); + return *( cont.begin() + pos ); } #endif template< class T > -gsl_api inline gsl_constexpr T & at( span s, size_t index ) +gsl_NODISCARD gsl_api inline gsl_constexpr14 T & +at( span s, size_t pos ) { - return s.at( index ); + return s[ pos ]; } // @@ -1088,109 +2483,772 @@ gsl_api inline gsl_constexpr T & at( span s, size_t index ) // // not_null<> - Wrap any indirection and enforce non-null. // + template< class T > -class not_null +class not_null; + +namespace detail { + +// helper class to figure out the pointed-to type of a pointer +#if gsl_STDLIB_CPP11_OR_GREATER +template< class T, class E = void > +struct element_type_helper { -#if gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) -# define gsl_not_null_explicit explicit -#else -# define gsl_not_null_explicit /*explicit*/ -#endif + // For types without a member element_type (this will handle raw pointers) + typedef typename std::remove_reference< decltype( *std::declval() ) >::type type; +}; + +template< class T > +struct element_type_helper< T, std17::void_t< typename T::element_type > > +{ + // For types with a member element_type + typedef typename T::element_type type; +}; +#else // ! gsl_STDLIB_CPP11_OR_GREATER +// Pre-C++11, we cannot have decltype, so we cannot handle types without a member element_type +template< class T, class E = void > +struct element_type_helper +{ + typedef typename T::element_type type; +}; + +template< class T > +struct element_type_helper< T* > +{ + typedef T type; +}; +#endif // gsl_STDLIB_CPP11_OR_GREATER + +template< class T > +struct is_not_null_or_bool_oracle : std11::false_type { }; +template< class T > +struct is_not_null_or_bool_oracle< not_null > : std11::true_type { }; +template<> +struct is_not_null_or_bool_oracle< bool > : std11::true_type { }; + + +template< class T, bool IsCopyable = true > +struct not_null_data; +#if gsl_HAVE( MOVE_FORWARD ) +template< class T > +struct not_null_data< T, false > +{ + T ptr_; + + gsl_api gsl_constexpr14 not_null_data( T && _ptr ) gsl_noexcept + : ptr_( std::move( _ptr ) ) + { + } + + gsl_api gsl_constexpr14 not_null_data( not_null_data && other ) gsl_noexcept + : ptr_( std::move( other.ptr_ ) ) + { + } + gsl_api gsl_constexpr14 not_null_data & operator=( not_null_data && other ) gsl_noexcept + { + ptr_ = std::move( other.ptr_ ); + return *this; + } + +gsl_is_delete_access: + not_null_data( not_null_data const & ) gsl_is_delete; + not_null_data & operator=( not_null_data const & ) gsl_is_delete; +}; +# if gsl_CONFIG_DEFAULTS_VERSION >= 1 +# endif // gsl_CONFIG_DEFAULTS_VERSION >= 1 +#endif // gsl_HAVE( MOVE_FORWARD ) +template< class T > +struct not_null_data< T, true > +{ + T ptr_; + + gsl_api gsl_constexpr14 not_null_data( T const & _ptr ) gsl_noexcept + : ptr_( _ptr ) + { + } + +#if gsl_HAVE( MOVE_FORWARD ) + gsl_api gsl_constexpr14 not_null_data( T && _ptr ) gsl_noexcept + : ptr_( std::move( _ptr ) ) + { + } + + gsl_api gsl_constexpr14 not_null_data( not_null_data && other ) gsl_noexcept + : ptr_( std::move( other.ptr_ ) ) + { + } + gsl_api gsl_constexpr14 not_null_data & operator=( not_null_data && other ) gsl_noexcept + { + ptr_ = std::move( other.ptr_ ); + return *this; + } +#endif // gsl_HAVE( MOVE_FORWARD ) -#if gsl_CONFIG( NOT_NULL_GET_BY_CONST_REF ) - typedef T const & get_result_t; + gsl_api gsl_constexpr14 not_null_data( not_null_data const & other ) + : ptr_( other.ptr_ ) + { + gsl_Expects( ptr_ != gsl_nullptr ); + } + gsl_api gsl_constexpr14 not_null_data & operator=( not_null_data const & other ) + { + gsl_Expects( other.ptr_ != gsl_nullptr ); + ptr_ = other.ptr_; + return *this; + } +}; +#if gsl_CONFIG_DEFAULTS_VERSION >= 1 +template< class T > +struct not_null_data< T *, true > +{ + T * ptr_; + + gsl_api gsl_constexpr14 not_null_data( T * _ptr ) gsl_noexcept + : ptr_( _ptr ) + { + } +}; +#endif // gsl_CONFIG_DEFAULTS_VERSION >= 1 +template< class T > +struct is_copyable +#if gsl_HAVE( TYPE_TRAITS ) +: std11::integral_constant< bool, std::is_copy_constructible::value && std::is_copy_assignable::value > #else - typedef T get_result_t; +: std11::true_type #endif +{ +}; +#if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( UNIQUE_PTR ) && gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 140 ) +// Type traits are buggy in VC++ 2013, so we explicitly declare `unique_ptr<>` non-copyable. +template< class T, class Deleter > +struct is_copyable< std::unique_ptr< T, Deleter > > : std11::false_type +{ +}; +#endif + +template< class T > +struct not_null_accessor; + +} // namespace detail + +template< class T > +class not_null +{ +private: + detail::not_null_data< T, detail::is_copyable< T >::value > data_; + + // need to access `not_null::data_` + template< class U > + friend class not_null; + + template< class U > + friend struct detail::not_null_accessor; public: + typedef typename detail::element_type_helper::type element_type; + #if gsl_HAVE( TYPE_TRAITS ) - static_assert( std::is_assignable::value, "T cannot be assigned nullptr." ); + static_assert( std::is_assignable::type>::type&, std::nullptr_t>::value, "T cannot be assigned nullptr." ); #endif +#if gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) +# if gsl_HAVE( MOVE_FORWARD ) + template< class U + // In Clang 3.x, `is_constructible>, unique_ptr>` tries to instantiate the copy constructor of `unique_ptr<>`, triggering an error. + // Note that Apple Clang's `__clang_major__` etc. are different from regular Clang. +# if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value ), int >::type = 0 +# endif + > + gsl_api gsl_constexpr14 explicit not_null( U other ) + : data_( T( std::move( other ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# else // a.k.a. ! gsl_HAVE( MOVE_FORWARD ) + template< class U > + gsl_api gsl_constexpr14 explicit not_null( U const& other ) + : data_( T( other ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# endif // gsl_HAVE( MOVE_FORWARD ) +#else // a.k.a. !gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) +# if gsl_HAVE( MOVE_FORWARD ) + // In Clang 3.x, `is_constructible>, unique_ptr>` tries to instantiate the copy constructor of `unique_ptr<>`, triggering an error. + // Note that Apple Clang's `__clang_major__` etc. are different from regular Clang. +# if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value ), int >::type = 0 + > + gsl_api gsl_constexpr14 explicit not_null( U other ) + : data_( T( std::move( other ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + template< class U -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_constructible::value )) -#endif + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_convertible::value ), int >::type = 0 > - gsl_api gsl_constexpr14 gsl_not_null_explicit -#if gsl_HAVE( RVALUE_REFERENCE ) - not_null( U && u ) - : ptr_( std::forward( u ) ) + gsl_api gsl_constexpr14 not_null( U other ) + : data_( std::move( other ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# else // a.k.a. !( gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + // If type_traits are not available, then we can't distinguish `is_convertible<>` and `is_constructible<>`, so we unconditionally permit implicit construction. + template< class U > + gsl_api gsl_constexpr14 not_null( U other ) + : data_( T( std::move( other ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# endif // gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) +# else // a.k.a. ! gsl_HAVE( MOVE_FORWARD ) + template< class U > + gsl_api gsl_constexpr14 not_null( U const& other ) + : data_( T( other ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# endif // gsl_HAVE( MOVE_FORWARD ) +#endif // gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) + +public: +#if gsl_HAVE( MOVE_FORWARD ) + // In Clang 3.x, `is_constructible>, unique_ptr>` tries to instantiate the copy constructor of `unique_ptr<>`, triggering an error. + // Note that Apple Clang's `__clang_major__` etc. are different from regular Clang. +# if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value ), int >::type = 0 + > + gsl_api gsl_constexpr14 explicit not_null( not_null other ) + : data_( T( std::move( other.data_.ptr_ ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_convertible::value ), int >::type = 0 + > + gsl_api gsl_constexpr14 not_null( not_null other ) + : data_( T( std::move( other.data_.ptr_ ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# else // a.k.a. ! ( gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + // If type_traits are not available, then we can't distinguish `is_convertible<>` and `is_constructible<>`, so we unconditionally permit implicit construction. + template< class U > + gsl_api gsl_constexpr14 not_null( not_null other ) + : data_( T( std::move( other.data_.ptr_ ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + template< class U > + gsl_api gsl_constexpr14 not_null& operator=( not_null other ) + { + gsl_Expects( other.data_.ptr_ != gsl_nullptr ); + data_.ptr_ = std::move( other.data_.ptr_ ); + return *this; + } +# endif // gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) +#else // a.k.a. ! gsl_HAVE( MOVE_FORWARD ) + template< class U > + gsl_api gsl_constexpr14 not_null( not_null const& other ) + : data_( T( other.data_.ptr_ ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + template< class U > + gsl_api gsl_constexpr14 not_null& operator=( not_null const & other ) + { + gsl_Expects( other.data_.ptr_ != gsl_nullptr ); + data_.ptr_ = other.data_.ptr_; + return *this; + } +#endif // gsl_HAVE( MOVE_FORWARD ) + +#if gsl_CONFIG( TRANSPARENT_NOT_NULL ) + gsl_NODISCARD gsl_api gsl_constexpr14 element_type * + get() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return data_.ptr_.get(); + } #else - not_null( U const & u ) - : ptr_( u ) +# if gsl_CONFIG( NOT_NULL_GET_BY_CONST_REF ) + gsl_NODISCARD gsl_api gsl_constexpr14 T const & + get() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return data_.ptr_; + } +# else + gsl_NODISCARD gsl_api gsl_constexpr14 T + get() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return data_.ptr_; + } +# endif #endif + + // We want an implicit conversion operator that can be used to convert from both lvalues (by + // const reference or by copy) and rvalues (by move). So it seems like we could define + // + // template< class U > + // operator U const &() const & { ... } + // template< class U > + // operator U &&() && { ... } + // + // However, having two conversion operators with different return types renders the assignment + // operator of the result type ambiguous: + // + // not_null> p( ... ); + // std::unique_ptr q; + // q = std::move( p ); // ambiguous + // + // To avoid this ambiguity, we have both overloads of the conversion operator return `U` + // rather than `U const &` or `U &&`. This implies that converting an lvalue always induces + // a copy, which can cause unnecessary copies or even fail to compile in some situations: + // + // not_null> sp( ... ); + // std::shared_ptr const & rs = sp; // unnecessary copy + // std::unique_ptr const & ru = p; // error: cannot copy `unique_ptr` + // + // However, these situations are rather unusual, and the following, more frequent situations + // remain unimpaired: + // + // std::shared_ptr vs = sp; // no extra copy + // std::unique_ptr vu = std::move( p ); + +#if gsl_HAVE( MOVE_FORWARD ) && gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) + // explicit conversion operator + + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 + > + gsl_NODISCARD gsl_api gsl_constexpr14 explicit + operator U() const +# if gsl_HAVE( FUNCTION_REF_QUALIFIER ) + & +# endif { - Expects( ptr_ != gsl_nullptr ); + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return U( data_.ptr_ ); } -#undef gsl_not_null_explicit +# if gsl_HAVE( FUNCTION_REF_QUALIFIER ) + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 + > + gsl_NODISCARD gsl_api gsl_constexpr14 explicit + operator U() && + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return U( std::move( data_.ptr_ ) ); + } +# endif -#if gsl_HAVE( IS_DEFAULT ) - gsl_api ~not_null() = default; - gsl_api gsl_constexpr not_null( not_null && other ) = default; - gsl_api gsl_constexpr not_null( not_null const & other ) = default; - gsl_api not_null & operator=( not_null && other ) = default; - gsl_api not_null & operator=( not_null const & other ) = default; -#else - gsl_api ~not_null() {}; - gsl_api gsl_constexpr not_null( not_null const & other ) : ptr_ ( other.ptr_ ) {} - gsl_api not_null & operator=( not_null const & other ) { ptr_ = other.ptr_; return *this; } -# if gsl_HAVE( RVALUE_REFERENCE ) - gsl_api gsl_constexpr not_null( not_null && other ) : ptr_( std::move( other.get() ) ) {} - gsl_api not_null & operator=( not_null && other ) { ptr_ = std::move( other.get() ); return *this; } + // implicit conversion operator + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 + > + gsl_NODISCARD gsl_api gsl_constexpr14 + operator U() const +# if gsl_HAVE( FUNCTION_REF_QUALIFIER ) + & # endif + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return data_.ptr_; + } +# if gsl_HAVE( FUNCTION_REF_QUALIFIER ) + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 + > + gsl_NODISCARD gsl_api gsl_constexpr14 + operator U() && + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return std::move( data_.ptr_ ); + } +# endif +#else // a.k.a. #if !( gsl_HAVE( MOVE_FORWARD ) && gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) ) + template< class U > + gsl_NODISCARD gsl_api gsl_constexpr14 + operator U() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return U( data_.ptr_ ); + } +#endif // gsl_HAVE( MOVE_FORWARD ) && gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) + + gsl_NODISCARD gsl_api gsl_constexpr14 T const & + operator->() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return data_.ptr_; + } + + gsl_NODISCARD gsl_api gsl_constexpr14 element_type & + operator*() const + { + gsl_Assert( data_.ptr_ != gsl_nullptr ); + return *data_.ptr_; + } + +#if gsl_HAVE( MOVE_FORWARD ) + // Visual C++ 2013 doesn't generate default move constructors, so we declare them explicitly. + gsl_api gsl_constexpr14 not_null( not_null && other ) + gsl_noexcept_not_testing // we want to be nothrow-movable despite the precondition check + : data_( std::move( other.data_ ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + gsl_api gsl_constexpr14 not_null & operator=( not_null && other ) + gsl_noexcept_not_testing // we want to be nothrow-movable despite the precondition check + { + gsl_Expects( other.data_.ptr_ != gsl_nullptr || &other == this ); + data_ = std::move( other.data_ ); + return *this; + } +#endif // gsl_HAVE( MOVE_FORWARD ) + +#if gsl_HAVE( IS_DEFAULT ) + gsl_constexpr14 not_null( not_null const & ) = default; + gsl_constexpr14 not_null & operator=( not_null const & ) = default; #endif + gsl_api gsl_constexpr20 friend void swap( not_null & lhs, not_null & rhs ) + gsl_noexcept_not_testing // we want to be nothrow-swappable despite the precondition check + { + gsl_Expects( lhs.data_.ptr_ != gsl_nullptr && rhs.data_.ptr_ != gsl_nullptr ); + using std::swap; + swap( lhs.data_.ptr_, rhs.data_.ptr_ ); + } + +gsl_is_delete_access: + not_null() gsl_is_delete; + // prevent compilation when initialized with a nullptr or literal 0: +#if gsl_HAVE( NULLPTR ) + not_null( std::nullptr_t ) gsl_is_delete; + not_null & operator=( std::nullptr_t ) gsl_is_delete; +#else + not_null( int ) gsl_is_delete; + not_null & operator=( int ) gsl_is_delete; +#endif + + // unwanted operators...pointers only point to single objects! + not_null & operator++() gsl_is_delete; + not_null & operator--() gsl_is_delete; + not_null operator++( int ) gsl_is_delete; + not_null operator--( int ) gsl_is_delete; + not_null & operator+ ( size_t ) gsl_is_delete; + not_null & operator+=( size_t ) gsl_is_delete; + not_null & operator- ( size_t ) gsl_is_delete; + not_null & operator-=( size_t ) gsl_is_delete; + not_null & operator+=( std::ptrdiff_t ) gsl_is_delete; + not_null & operator-=( std::ptrdiff_t ) gsl_is_delete; + void operator[]( std::ptrdiff_t ) const gsl_is_delete; +}; +#if gsl_CONFIG_DEFAULTS_VERSION >= 1 +template< class T > +class not_null< T * > +{ +private: + detail::not_null_data data_; + + // need to access `not_null::data_` + template< class U > + friend class not_null; + + template< class U > + friend struct detail::not_null_accessor; + +public: + typedef T element_type; + + gsl_api gsl_constexpr14 +#if gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) + explicit +#endif // gsl_CONFIG( NOT_NULL_EXPLICIT_CTOR ) + not_null( T * other ) + : data_( other ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + +#if gsl_HAVE( MOVE_FORWARD ) + // In Clang 3.x, `is_constructible>, unique_ptr>` tries to instantiate the copy constructor of `unique_ptr<>`, triggering an error. + // Note that Apple Clang's `__clang_major__` etc. are different from regular Clang. +# if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) template< class U -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::value )) + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value ), int >::type = 0 + > + gsl_api gsl_constexpr14 explicit not_null( not_null other ) + : data_( static_cast( std::move( other.data_.ptr_ ) ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_convertible::value ), int >::type = 0 + > + gsl_api gsl_constexpr14 not_null( not_null other ) + : data_( std::move( other.data_.ptr_ ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } +# else // a.k.a. ! ( gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) + // If type_traits are not available, then we can't distinguish `is_convertible<>` and `is_constructible<>`, so we unconditionally permit implicit construction. + template< class U > + gsl_api gsl_constexpr14 not_null( not_null other ) + : data_( std::move( other.data_.ptr_ ) ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + template< class U > + gsl_api gsl_constexpr14 not_null& operator=( not_null other ) + { + gsl_Expects( other.data_.ptr_ != gsl_nullptr ); + data_.ptr_ = std::move( other.data_.ptr_ ); + return *this; + } +# endif // gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && ! gsl_BETWEEN( gsl_COMPILER_CLANG_VERSION, 1, 400 ) && ! gsl_BETWEEN( gsl_COMPILER_APPLECLANG_VERSION, 1, 1001 ) +#else // a.k.a. ! gsl_HAVE( MOVE_FORWARD ) + template< class U > + gsl_api gsl_constexpr14 not_null( not_null const& other ) + : data_( other.data_.ptr_ ) + { + gsl_Expects( data_.ptr_ != gsl_nullptr ); + } + template< class U > + gsl_api gsl_constexpr14 not_null& operator=( not_null const & other ) + { + gsl_Expects( other.data_.ptr_ != gsl_nullptr ); + data_.ptr_ = other.data_.ptr_; + return *this; + } +#endif // gsl_HAVE( MOVE_FORWARD ) + +#if ! gsl_CONFIG( TRANSPARENT_NOT_NULL ) + gsl_NODISCARD gsl_api gsl_constexpr14 T* + get() const + { + return data_.ptr_; + } #endif + +#if gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) + // explicit conversion operator + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && !std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 > - gsl_api gsl_constexpr not_null( not_null const & other ) - : ptr_( other.get() ) - {} + gsl_NODISCARD gsl_api gsl_constexpr14 explicit + operator U() const + { + return U( data_.ptr_ ); + } - gsl_api gsl_constexpr14 get_result_t get() const + // implicit conversion operator + template< class U + // We *have* to use SFINAE with an NTTP arg here, otherwise the overload is ambiguous. + , typename std::enable_if< ( std::is_constructible::value && std::is_convertible::value && !detail::is_not_null_or_bool_oracle::value ), int >::type = 0 + > + gsl_NODISCARD gsl_api gsl_constexpr14 + operator U() const + { + return data_.ptr_; + } +#else // a.k.a. #if !( gsl_HAVE( MOVE_FORWARD ) && gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) ) + template< class U > + gsl_NODISCARD gsl_api gsl_constexpr14 + operator U() const { - // Without cheating and changing ptr_ from the outside, this check is superfluous: - Ensures( ptr_ != gsl_nullptr ); - return ptr_; + return data_.ptr_; } +#endif // gsl_HAVE( MOVE_FORWARD ) && gsl_HAVE( TYPE_TRAITS ) && gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) && gsl_HAVE( EXPLICIT ) - gsl_api gsl_constexpr operator get_result_t () const { return get(); } - gsl_api gsl_constexpr get_result_t operator->() const { return get(); } + gsl_NODISCARD gsl_api gsl_constexpr14 T* + operator->() const + { + return data_.ptr_; + } + + gsl_NODISCARD gsl_api gsl_constexpr14 element_type & + operator*() const + { + return *data_.ptr_; + } -#if gsl_HAVE( DECLTYPE_AUTO ) - gsl_api gsl_constexpr decltype(auto) operator*() const { return *get(); } +#if gsl_HAVE( IS_DEFAULT ) + gsl_constexpr14 not_null( not_null const & ) = default; + gsl_constexpr14 not_null & operator=( not_null const & ) = default; #endif + gsl_api gsl_constexpr20 friend void swap( not_null & lhs, not_null & rhs ) gsl_noexcept + { + using std::swap; + swap( lhs.data_.ptr_, rhs.data_.ptr_ ); + } + gsl_is_delete_access: + not_null() gsl_is_delete; // prevent compilation when initialized with a nullptr or literal 0: #if gsl_HAVE( NULLPTR ) - gsl_api not_null( std::nullptr_t ) gsl_is_delete; - gsl_api not_null & operator=( std::nullptr_t ) gsl_is_delete; + not_null( std::nullptr_t ) gsl_is_delete; + not_null & operator=( std::nullptr_t ) gsl_is_delete; #else - gsl_api not_null( int ) gsl_is_delete; - gsl_api not_null & operator=( int ) gsl_is_delete; + not_null( int ) gsl_is_delete; + not_null & operator=( int ) gsl_is_delete; #endif // unwanted operators...pointers only point to single objects! - gsl_api not_null & operator++() gsl_is_delete; - gsl_api not_null & operator--() gsl_is_delete; - gsl_api not_null operator++( int ) gsl_is_delete; - gsl_api not_null operator--( int ) gsl_is_delete; - gsl_api not_null & operator+ ( size_t ) gsl_is_delete; - gsl_api not_null & operator+=( size_t ) gsl_is_delete; - gsl_api not_null & operator- ( size_t ) gsl_is_delete; - gsl_api not_null & operator-=( size_t ) gsl_is_delete; - gsl_api not_null & operator+=( std::ptrdiff_t ) gsl_is_delete; - gsl_api not_null & operator-=( std::ptrdiff_t ) gsl_is_delete; - gsl_api void operator[]( std::ptrdiff_t ) const gsl_is_delete; + not_null & operator++() gsl_is_delete; + not_null & operator--() gsl_is_delete; + not_null operator++( int ) gsl_is_delete; + not_null operator--( int ) gsl_is_delete; + not_null & operator+ ( size_t ) gsl_is_delete; + not_null & operator+=( size_t ) gsl_is_delete; + not_null & operator- ( size_t ) gsl_is_delete; + not_null & operator-=( size_t ) gsl_is_delete; + not_null & operator+=( std::ptrdiff_t ) gsl_is_delete; + not_null & operator-=( std::ptrdiff_t ) gsl_is_delete; + void operator[]( std::ptrdiff_t ) const gsl_is_delete; +}; +#endif // gsl_CONFIG_DEFAULTS_VERSION >= 1 +#if gsl_HAVE( DEDUCTION_GUIDES ) +template< class U > +not_null( U ) -> not_null; +template< class U > +not_null( not_null ) -> not_null; +#endif -private: - T ptr_; +#if gsl_HAVE( NULLPTR ) +void make_not_null( std::nullptr_t ) gsl_is_delete; +#endif // gsl_HAVE( NULLPTR ) +#if gsl_HAVE( MOVE_FORWARD ) +template< class U > +gsl_NODISCARD gsl_api gsl_constexpr14 not_null +make_not_null( U u ) +{ + return not_null( std::move( u ) ); +} +template< class U > +gsl_NODISCARD gsl_api gsl_constexpr14 not_null +make_not_null( not_null u ) +{ + return std::move( u ); +} +#else // a.k.a. ! gsl_HAVE( MOVE_FORWARD ) +template< class U > +gsl_NODISCARD gsl_api not_null +make_not_null( U const & u ) +{ + return not_null( u ); +} +template< class U > +gsl_NODISCARD gsl_api not_null +make_not_null( not_null const & u ) +{ + return u; +} +#endif // gsl_HAVE( MOVE_FORWARD ) + +namespace detail { + +template< class T > +struct as_nullable_helper +{ + typedef T type; }; +template< class T > +struct as_nullable_helper< not_null > +{ +}; + +template< class T > +struct not_null_accessor +{ +#if gsl_HAVE( MOVE_FORWARD ) + static gsl_api T get( not_null&& p ) gsl_noexcept + { + return std::move( p.data_.ptr_ ); + } +#endif + static gsl_api T const & get( not_null const & p ) gsl_noexcept + { + return p.data_.ptr_; + } +}; + +namespace no_adl { + +#if gsl_HAVE( MOVE_FORWARD ) +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr auto as_nullable( T && p ) +gsl_noexcept_if( std::is_nothrow_move_constructible::value ) +-> typename detail::as_nullable_helper::type>::type +{ + return std::move( p ); +} +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr14 T as_nullable( not_null && p ) +{ + T result = detail::not_null_accessor::get( std::move( p ) ); + gsl_Expects( result != gsl_nullptr ); + return result; +} +#else // ! gsl_HAVE( MOVE_FORWARD ) +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr T const & as_nullable( T const & p ) gsl_noexcept +{ + return p; +} +#endif // gsl_HAVE( MOVE_FORWARD ) +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr14 T const & +as_nullable( not_null const & p ) +{ + T const & result = detail::not_null_accessor::get( p ); + gsl_Expects( result != gsl_nullptr ); + return result; +} +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr T* +as_nullable( not_null p ) gsl_noexcept +{ + return detail::not_null_accessor::get( p ); +} + +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr bool +is_valid( not_null const & p ) +{ + return detail::not_null_accessor::get( p ) != gsl_nullptr; +} +template< class T > +gsl_NODISCARD gsl_api gsl_constexpr bool +is_valid( not_null const & ) +{ + return true; +} + +} // namespace no_adl +} // namespace detail + +using namespace detail::no_adl; // not_null with implicit constructor, allowing copy-initialization: @@ -1199,18 +3257,16 @@ class not_null_ic : public not_null { public: template< class U -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_constructible::value )) -#endif + gsl_ENABLE_IF_(( std::is_constructible::value )) > gsl_api gsl_constexpr14 -#if gsl_HAVE( RVALUE_REFERENCE ) +#if gsl_HAVE( MOVE_FORWARD ) not_null_ic( U && u ) : not_null( std::forward( u ) ) -#else +#else // ! gsl_HAVE( MOVE_FORWARD ) not_null_ic( U const & u ) : not_null( u ) -#endif +#endif // gsl_HAVE( MOVE_FORWARD ) {} }; @@ -1230,42 +3286,190 @@ not_null operator+( std::ptrdiff_t, not_null const & ) gsl_is_delete; // not_null comparisons +#if gsl_HAVE( NULLPTR ) && gsl_HAVE( IS_DELETE ) +template< class T > +gsl_constexpr bool +operator==( not_null const &, std::nullptr_t ) = delete; +template< class T > +gsl_constexpr bool +operator==( std::nullptr_t , not_null const & ) = delete; +template< class T > +gsl_constexpr bool +operator!=( not_null const &, std::nullptr_t ) = delete; +template< class T > +gsl_constexpr bool +operator!=( std::nullptr_t , not_null const & ) = delete; +#endif // gsl_HAVE( NULLPTR ) && gsl_HAVE( IS_DELETE ) + +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator==( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( l.operator->() == r.operator->() ) +{ + return l.operator->() == r.operator->(); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator==( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_(l.operator->() == r ) +{ + return l.operator->() == r; +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator==( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( l == r.operator->() ) +{ + return l == r.operator->(); +} + +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( l.operator->() < r.operator->() ) +{ + return l.operator->() < r.operator->(); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_( l.operator->() < r ) +{ + return l.operator->() < r; +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( l < r.operator->() ) +{ + return l < r.operator->(); +} + +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator!=( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( l == r ) ) +{ + return !( l == r ); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator!=( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_( !( l == r ) ) +{ + return !( l == r ); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator!=( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( l == r ) ) +{ + return !( l == r ); +} + +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<=( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( r < l ) ) +{ + return !( r < l ); +} template< class T, class U > -gsl_api inline gsl_constexpr bool operator==( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<=( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_( !( r < l ) ) { - return l.get() == r.get(); + return !( r < l ); } - template< class T, class U > -gsl_api inline gsl_constexpr bool operator< ( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator<=( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( r < l ) ) { - return l.get() < r.get(); + return !( r < l ); } template< class T, class U > -gsl_api inline gsl_constexpr bool operator!=( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( r < l ) { - return !( l == r ); + return r < l; } - template< class T, class U > -gsl_api inline gsl_constexpr bool operator<=( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_( r < l ) { - return !( r < l ); + return r < l; } - template< class T, class U > -gsl_api inline gsl_constexpr bool operator> ( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( r < l ) { - return ( r < l ); + return r < l; } template< class T, class U > -gsl_api inline gsl_constexpr bool operator>=( not_null const & l, not_null const & r ) +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>=( not_null const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( l < r ) ) +{ + return !( l < r ); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>=( not_null const & l, U const & r ) +gsl_RETURN_DECLTYPE_( !( l < r ) ) +{ + return !( l < r ); +} +template< class T, class U > +gsl_NODISCARD inline gsl_api gsl_constexpr gsl_TRAILING_RETURN_TYPE_( bool ) +operator>=( T const & l, not_null const & r ) +gsl_RETURN_DECLTYPE_( !( l < r ) ) { return !( l < r ); } +// print not_null + +template< class CharType, class Traits, class T > +std::basic_ostream< CharType, Traits > & operator<<( std::basic_ostream< CharType, Traits > & os, not_null const & p ) +{ + return os << p.operator->(); +} + + +#if gsl_HAVE( VARIADIC_TEMPLATE ) +# if gsl_HAVE( UNIQUE_PTR ) +template< class T, class... Args > +gsl_NODISCARD not_null> +make_unique( Args &&... args ) +{ +# if gsl_HAVE( TYPE_TRAITS ) + static_assert( !std::is_array::value, "gsl::make_unique() returns `gsl::not_null>`, which is not " + "defined for array types because the Core Guidelines advise against pointer arithmetic, cf. \"Bounds safety profile\"." ); +# endif + return not_null>( new T( std::forward( args )... ) ); +} +# endif // gsl_HAVE( UNIQUE_PTR ) +# if gsl_HAVE( SHARED_PTR ) +template< class T, class... Args > +gsl_NODISCARD not_null> +make_shared( Args &&... args ) +{ +# if gsl_HAVE( TYPE_TRAITS ) + static_assert( !std::is_array::value, "gsl::make_shared() returns `gsl::not_null>`, which is not " + "defined for array types because the Core Guidelines advise against pointer arithmetic, cf. \"Bounds safety profile\"." ); +# endif + return not_null>( std::make_shared( std::forward( args )... ) ); +} +# endif // gsl_HAVE( SHARED_PTR ) +#endif // gsl_HAVE( VARIADIC_TEMPLATE ) + + // // Byte-specific type. // @@ -1275,15 +3479,9 @@ gsl_api inline gsl_constexpr bool operator>=( not_null const & l, not_null struct gsl_may_alias byte { typedef unsigned char type; type v; }; #endif -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) -# define gsl_ENABLE_IF_INTEGRAL_T(T) \ - gsl_REQUIRES_T(( std::is_integral::value )) -#else -# define gsl_ENABLE_IF_INTEGRAL_T(T) -#endif - template< class T > -gsl_api inline gsl_constexpr byte to_byte( T v ) gsl_noexcept +gsl_NODISCARD gsl_api inline gsl_constexpr byte +to_byte( T v ) gsl_noexcept { #if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) return static_cast( v ); @@ -1294,8 +3492,9 @@ gsl_api inline gsl_constexpr byte to_byte( T v ) gsl_noexcept #endif } -template< class IntegerType gsl_ENABLE_IF_INTEGRAL_T( IntegerType ) > -gsl_api inline gsl_constexpr IntegerType to_integer( byte b ) gsl_noexcept +template< class IntegerType gsl_ENABLE_IF_(( std::is_integral::value )) > +gsl_NODISCARD gsl_api inline gsl_constexpr IntegerType +to_integer( byte b ) gsl_noexcept { #if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) return static_cast::type>( b ); @@ -1304,18 +3503,58 @@ gsl_api inline gsl_constexpr IntegerType to_integer( byte b ) gsl_noexcept #endif } -gsl_api inline gsl_constexpr unsigned char to_uchar( byte b ) gsl_noexcept +gsl_NODISCARD gsl_api inline gsl_constexpr unsigned char +to_uchar( byte b ) gsl_noexcept { return to_integer( b ); } -gsl_api inline gsl_constexpr unsigned char to_uchar( int i ) gsl_noexcept +gsl_NODISCARD gsl_api inline gsl_constexpr unsigned char +to_uchar( int i ) gsl_noexcept { return static_cast( i ); } -#if ! gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) +template< class IntegerType gsl_ENABLE_IF_(( std::is_integral::value )) > +gsl_api inline gsl_constexpr14 byte & +operator<<=( byte & b, IntegerType shift ) gsl_noexcept +{ +#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) + return b = ::gsl::to_byte( ::gsl::to_uchar( b ) << shift ); +#else + b.v = ::gsl::to_uchar( b.v << shift ); return b; +#endif +} + +template< class IntegerType gsl_ENABLE_IF_(( std::is_integral::value )) > +gsl_NODISCARD gsl_api inline gsl_constexpr byte +operator<<( byte b, IntegerType shift ) gsl_noexcept +{ + return ::gsl::to_byte( ::gsl::to_uchar( b ) << shift ); +} + +template< class IntegerType gsl_ENABLE_IF_(( std::is_integral::value )) > +gsl_NODISCARD gsl_api inline gsl_constexpr14 byte & +operator>>=( byte & b, IntegerType shift ) gsl_noexcept +{ +#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) + return b = ::gsl::to_byte( ::gsl::to_uchar( b ) >> shift ); +#else + b.v = ::gsl::to_uchar( b.v >> shift ); return b; +#endif +} + +template< class IntegerType gsl_ENABLE_IF_(( std::is_integral::value )) > +gsl_NODISCARD gsl_api inline gsl_constexpr byte +operator>>( byte b, IntegerType shift ) gsl_noexcept +{ + return ::gsl::to_byte( ::gsl::to_uchar( b ) >> shift ); +} +#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) +gsl_DEFINE_ENUM_BITMASK_OPERATORS( byte ) +gsl_DEFINE_ENUM_RELATIONAL_OPERATORS( byte ) +#else // a.k.a. !gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) gsl_api inline gsl_constexpr bool operator==( byte l, byte r ) gsl_noexcept { return l.v == r.v; @@ -1345,121 +3584,64 @@ gsl_api inline gsl_constexpr bool operator>=( byte l, byte r ) gsl_noexcept { return !( l < r ); } -#endif - -template< class IntegerType gsl_ENABLE_IF_INTEGRAL_T( IntegerType ) > -gsl_api inline gsl_constexpr14 byte & operator<<=( byte & b, IntegerType shift ) gsl_noexcept -{ -#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) - return b = to_byte( to_uchar( b ) << shift ); -#else - b.v = to_uchar( b.v << shift ); return b; -#endif -} - -template< class IntegerType gsl_ENABLE_IF_INTEGRAL_T( IntegerType ) > -gsl_api inline gsl_constexpr byte operator<<( byte b, IntegerType shift ) gsl_noexcept -{ - return to_byte( to_uchar( b ) << shift ); -} - -template< class IntegerType gsl_ENABLE_IF_INTEGRAL_T( IntegerType ) > -gsl_api inline gsl_constexpr14 byte & operator>>=( byte & b, IntegerType shift ) gsl_noexcept -{ -#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) - return b = to_byte( to_uchar( b ) >> shift ); -#else - b.v = to_uchar( b.v >> shift ); return b; -#endif -} - -template< class IntegerType gsl_ENABLE_IF_INTEGRAL_T( IntegerType ) > -gsl_api inline gsl_constexpr byte operator>>( byte b, IntegerType shift ) gsl_noexcept -{ - return to_byte( to_uchar( b ) >> shift ); -} gsl_api inline gsl_constexpr14 byte & operator|=( byte & l, byte r ) gsl_noexcept { -#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) - return l = to_byte( to_uchar( l ) | to_uchar( r ) ); -#else - l.v = to_uchar( l ) | to_uchar( r ); return l; -#endif + l.v |= r.v; return l; } gsl_api inline gsl_constexpr byte operator|( byte l, byte r ) gsl_noexcept { - return to_byte( to_uchar( l ) | to_uchar( r ) ); + return ::gsl::to_byte( l.v | r.v ); } gsl_api inline gsl_constexpr14 byte & operator&=( byte & l, byte r ) gsl_noexcept { -#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) - return l = to_byte( to_uchar( l ) & to_uchar( r ) ); -#else - l.v = to_uchar( l ) & to_uchar( r ); return l; -#endif + l.v &= r.v; return l; } gsl_api inline gsl_constexpr byte operator&( byte l, byte r ) gsl_noexcept { - return to_byte( to_uchar( l ) & to_uchar( r ) ); + return ::gsl::to_byte( l.v & r.v ); } gsl_api inline gsl_constexpr14 byte & operator^=( byte & l, byte r ) gsl_noexcept { -#if gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) - return l = to_byte( to_uchar( l ) ^ to_uchar (r ) ); -#else - l.v = to_uchar( l ) ^ to_uchar (r ); return l; -#endif + l.v ^= r.v; return l; } gsl_api inline gsl_constexpr byte operator^( byte l, byte r ) gsl_noexcept { - return to_byte( to_uchar( l ) ^ to_uchar( r ) ); + return ::gsl::to_byte( l.v ^ r.v ); } gsl_api inline gsl_constexpr byte operator~( byte b ) gsl_noexcept { - return to_byte( ~to_uchar( b ) ); + return ::gsl::to_byte( ~b.v ); } +#endif // gsl_HAVE( ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ) #if gsl_FEATURE_TO_STD( WITH_CONTAINER ) -// Tag to select span constructor taking a container (prevent ms-gsl warning C26426): +// Tag to select span constructor taking a container: -struct with_container_t { gsl_constexpr with_container_t() gsl_noexcept {} }; -const gsl_constexpr with_container_t with_container; +struct with_container_t { gsl_constexpr with_container_t( ) gsl_noexcept { } }; +const gsl_constexpr with_container_t with_container; // TODO: this can lead to ODR violations because the symbol will be defined in multiple translation units #endif -#if gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) - namespace detail { -// Can construct from containers that: - -template< class Container, class ElementType - gsl_REQUIRES_T(( - ! detail::is_span< Container >::value - && ! detail::is_array< Container >::value - && ! detail::is_std_array< Container >::value - && std::is_convertible().data())>::type(*)[], ElementType(*)[] >::value - )) -#if gsl_HAVE( STD_DATA ) - // data(cont) and size(cont) well-formed: - , class = decltype( std::data( std::declval() ) ) - , class = decltype( std::size( std::declval() ) ) -#endif -> -struct can_construct_span_from : std11::true_type{}; +template< class T > +gsl_api gsl_constexpr14 T * endptr( T * data, gsl_CONFIG_SPAN_INDEX_TYPE size ) +{ + // Be sure to run the check before doing pointer arithmetics, which would be UB for `nullptr` and non-0 integers. + gsl_Expects( size == 0 || data != gsl_nullptr ); + return data + size; +} } // namespace detail -#endif - // // span<> - A 1D view of contiguous T's, replace (*,len). // @@ -1469,7 +3651,7 @@ class span template< class U > friend class span; public: - typedef index index_type; + typedef gsl_CONFIG_SPAN_INDEX_TYPE index_type; typedef T element_type; typedef typename std11::remove_cv< T >::type value_type; @@ -1485,29 +3667,30 @@ class span typedef std::reverse_iterator< iterator > reverse_iterator; typedef std::reverse_iterator< const_iterator > const_reverse_iterator; - typedef typename std::iterator_traits< iterator >::difference_type difference_type; + typedef gsl_CONFIG_SPAN_INDEX_TYPE size_type; + typedef std::ptrdiff_t difference_type; // 26.7.3.2 Constructors, copy, and assignment [span.cons] - gsl_api gsl_constexpr14 span() gsl_noexcept + gsl_api gsl_constexpr span() gsl_noexcept : first_( gsl_nullptr ) , last_ ( gsl_nullptr ) { - Expects( size() == 0 ); } #if ! gsl_DEPRECATE_TO_LEVEL( 5 ) #if gsl_HAVE( NULLPTR ) - gsl_api gsl_constexpr14 span( std::nullptr_t, index_type gsl_EXPECTS_UNUSED_PARAM( size_in ) ) + gsl_api gsl_constexpr14 span( std::nullptr_t, index_type size_in ) : first_( nullptr ) , last_ ( nullptr ) { - Expects( size_in == 0 ); + gsl_Expects( size_in == 0 ); } #endif #if gsl_HAVE( IS_DELETE ) + gsl_DEPRECATED gsl_api gsl_constexpr span( reference data_in ) : span( &data_in, 1 ) {} @@ -1519,34 +3702,24 @@ class span gsl_api gsl_constexpr14 span( pointer data_in, index_type size_in ) : first_( data_in ) - , last_ ( data_in + size_in ) + , last_( detail::endptr( data_in, size_in ) ) { - Expects( size_in == 0 || ( size_in > 0 && data_in != gsl_nullptr ) ); } gsl_api gsl_constexpr14 span( pointer first_in, pointer last_in ) : first_( first_in ) , last_ ( last_in ) { - Expects( first_in <= last_in ); + gsl_Expects( first_in <= last_in ); } #if ! gsl_DEPRECATE_TO_LEVEL( 5 ) template< class U > - gsl_api gsl_constexpr14 span( U * & data_in, index_type size_in ) - : first_( data_in ) - , last_ ( data_in + size_in ) - { - Expects( size_in == 0 || ( size_in > 0 && data_in != gsl_nullptr ) ); - } - - template< class U > - gsl_api gsl_constexpr14 span( U * const & data_in, index_type size_in ) + gsl_api gsl_constexpr14 span( U * data_in, index_type size_in ) : first_( data_in ) - , last_ ( data_in + size_in ) + , last_( detail::endptr( data_in, size_in ) ) { - Expects( size_in == 0 || ( size_in > 0 && data_in != gsl_nullptr ) ); } #endif // deprecate @@ -1559,9 +3732,7 @@ class span {} #else template< size_t N -# if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::value )) -# endif + gsl_ENABLE_IF_(( std::is_convertible::value )) > gsl_api gsl_constexpr span( element_type (&arr)[N] ) gsl_noexcept : first_( gsl_ADDRESSOF( arr[0] ) ) @@ -1587,21 +3758,17 @@ class span #else template< size_t N -# if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::value )) -# endif + gsl_ENABLE_IF_(( std::is_convertible::value )) > - gsl_api gsl_constexpr span( std::array< value_type, N > & arr ) + gsl_constexpr span( std::array< value_type, N > & arr ) : first_( arr.data() ) , last_ ( arr.data() + N ) {} template< size_t N -# if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::value )) -# endif + gsl_ENABLE_IF_(( std::is_convertible::value )) > - gsl_api gsl_constexpr span( std::array< value_type, N > const & arr ) + gsl_constexpr span( std::array< value_type, N > const & arr ) : first_( arr.data() ) , last_ ( arr.data() + N ) {} @@ -1611,34 +3778,34 @@ class span #if gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) template< class Container - gsl_REQUIRES_T(( detail::can_construct_span_from< Container, element_type >::value )) + gsl_ENABLE_IF_(( detail::is_compatible_container< Container, element_type >::value )) > - gsl_api gsl_constexpr span( Container & cont ) - : first_( cont.data() ) - , last_ ( cont.data() + cont.size() ) + gsl_api gsl_constexpr span( Container & cont ) gsl_noexcept + : first_( std17::data( cont ) ) + , last_ ( std17::data( cont ) + std17::size( cont ) ) {} template< class Container - gsl_REQUIRES_T(( - std::is_const< element_type >::value - && detail::can_construct_span_from< Container, element_type >::value + gsl_ENABLE_IF_(( + std::is_const< element_type >::value + && detail::is_compatible_container< Container, element_type >::value )) > - gsl_api gsl_constexpr span( Container const & cont ) - : first_( cont.data() ) - , last_ ( cont.data() + cont.size() ) + gsl_api gsl_constexpr span( Container const & cont ) gsl_noexcept + : first_( std17::data( cont ) ) + , last_ ( std17::data( cont ) + std17::size( cont ) ) {} #elif gsl_HAVE( UNCONSTRAINED_SPAN_CONTAINER_CTOR ) template< class Container > - gsl_api gsl_constexpr span( Container & cont ) + gsl_constexpr span( Container & cont ) : first_( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) ) , last_ ( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) + cont.size() ) {} template< class Container > - gsl_api gsl_constexpr span( Container const & cont ) + gsl_constexpr span( Container const & cont ) : first_( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) ) , last_ ( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) + cont.size() ) {} @@ -1648,53 +3815,56 @@ class span #if gsl_FEATURE_TO_STD( WITH_CONTAINER ) template< class Container > - gsl_api gsl_constexpr span( with_container_t, Container & cont ) + gsl_constexpr span( with_container_t, Container & cont ) gsl_noexcept : first_( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) ) , last_ ( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) + cont.size() ) {} template< class Container > - gsl_api gsl_constexpr span( with_container_t, Container const & cont ) + gsl_constexpr span( with_container_t, Container const & cont ) gsl_noexcept : first_( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) ) , last_ ( cont.size() == 0 ? gsl_nullptr : gsl_ADDRESSOF( cont[0] ) + cont.size() ) {} #endif -#if ! gsl_DEPRECATE_TO_LEVEL( 4 ) +#if !gsl_DEPRECATE_TO_LEVEL( 4 ) // constructor taking shared_ptr deprecated since 0.29.0 -#if gsl_HAVE( SHARED_PTR ) - gsl_api gsl_constexpr span( shared_ptr const & ptr ) +# if gsl_HAVE( SHARED_PTR ) + gsl_DEPRECATED + gsl_constexpr span( shared_ptr const & ptr ) : first_( ptr.get() ) , last_ ( ptr.get() ? ptr.get() + 1 : gsl_nullptr ) {} -#endif +# endif // constructors taking unique_ptr deprecated since 0.29.0 -#if gsl_HAVE( UNIQUE_PTR ) -# if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) +# if gsl_HAVE( UNIQUE_PTR ) +# if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) template< class ArrayElementType = typename std::add_pointer::type > -# else +# else template< class ArrayElementType > -# endif - gsl_api gsl_constexpr span( unique_ptr const & ptr, index_type count ) +# endif + gsl_DEPRECATED + gsl_constexpr span( unique_ptr const & ptr, index_type count ) : first_( ptr.get() ) , last_ ( ptr.get() + count ) {} - gsl_api gsl_constexpr span( unique_ptr const & ptr ) + gsl_DEPRECATED + gsl_constexpr span( unique_ptr const & ptr ) : first_( ptr.get() ) , last_ ( ptr.get() ? ptr.get() + 1 : gsl_nullptr ) {} -#endif +# endif #endif // deprecate shared_ptr, unique_ptr #if gsl_HAVE( IS_DEFAULT ) && ! gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 430, 600) - gsl_api gsl_constexpr span( span && ) gsl_noexcept = default; - gsl_api gsl_constexpr span( span const & ) = default; + gsl_constexpr span( span && ) gsl_noexcept = default; + gsl_constexpr span( span const & ) = default; #else gsl_api gsl_constexpr span( span const & other ) : first_( other.begin() ) @@ -1703,26 +3873,19 @@ class span #endif #if gsl_HAVE( IS_DEFAULT ) - ~span() = default; -#else - ~span() {} -#endif - -#if gsl_HAVE( IS_DEFAULT ) - gsl_api gsl_constexpr14 span & operator=( span && ) gsl_noexcept = default; - gsl_api gsl_constexpr14 span & operator=( span const & ) gsl_noexcept = default; + gsl_constexpr14 span & operator=( span && ) gsl_noexcept = default; + gsl_constexpr14 span & operator=( span const & ) gsl_noexcept = default; #else - gsl_api span & operator=( span other ) gsl_noexcept + gsl_constexpr14 span & operator=( span other ) gsl_noexcept { - other.swap( *this ); + first_ = other.first_; + last_ = other.last_; return *this; } #endif template< class U -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::value )) -#endif + gsl_ENABLE_IF_(( std::is_convertible::value )) > gsl_api gsl_constexpr span( span const & other ) : first_( other.begin() ) @@ -1736,90 +3899,123 @@ class span // 26.7.3.3 Subviews [span.sub] - gsl_api gsl_constexpr14 span first( index_type count ) const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr14 span + first( index_type count ) const { - Expects( 0 <= count && count <= this->size() ); + gsl_Expects( std::size_t( count ) <= std::size_t( this->size() ) ); return span( this->data(), count ); } - gsl_api gsl_constexpr14 span last( index_type count ) const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr14 span + last( index_type count ) const { - Expects( 0 <= count && count <= this->size() ); + gsl_Expects( std::size_t( count ) <= std::size_t( this->size() ) ); return span( this->data() + this->size() - count, count ); } - gsl_api gsl_constexpr14 span subspan( index_type offset ) const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr14 span + subspan( index_type offset ) const { - Expects( 0 <= offset && offset <= this->size() ); + gsl_Expects( std::size_t( offset ) <= std::size_t( this->size() ) ); return span( this->data() + offset, this->size() - offset ); } - gsl_api gsl_constexpr14 span subspan( index_type offset, index_type count ) const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr14 span + subspan( index_type offset, index_type count ) const { - Expects( - 0 <= offset && offset <= this->size() && - 0 <= count && count <= this->size() - offset ); + gsl_Expects( + std::size_t( offset ) <= std::size_t( this->size() ) && + std::size_t( count ) <= std::size_t( this->size() - offset ) ); return span( this->data() + offset, count ); } // 26.7.3.4 Observers [span.obs] - gsl_api gsl_constexpr index_type size() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + size() const gsl_noexcept { return narrow_cast( last_ - first_ ); } - gsl_api gsl_constexpr std::ptrdiff_t ssize() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr std::ptrdiff_t + ssize() const gsl_noexcept { return narrow_cast( last_ - first_ ); } - gsl_api gsl_constexpr index_type size_bytes() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + size_bytes() const gsl_noexcept { return size() * narrow_cast( sizeof( element_type ) ); } - gsl_api gsl_constexpr bool empty() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr bool + empty() const gsl_noexcept { return size() == 0; } // 26.7.3.5 Element access [span.elem] - gsl_api gsl_constexpr reference operator[]( index_type index ) const + gsl_NODISCARD gsl_api gsl_constexpr14 reference + operator[]( index_type pos ) const { - return at( index ); + gsl_Expects( pos < size() ); + return first_[ pos ]; } - gsl_api gsl_constexpr reference operator()( index_type index ) const +#if ! gsl_DEPRECATE_TO_LEVEL( 6 ) + gsl_DEPRECATED_MSG("use subscript indexing instead") + gsl_api gsl_constexpr14 reference + operator()( index_type pos ) const { - return at( index ); + return (*this)[ pos ]; } - gsl_api gsl_constexpr14 reference at( index_type index ) const + gsl_DEPRECATED_MSG("use subscript indexing instead") + gsl_api gsl_constexpr14 reference + at( index_type pos ) const { - Expects( index < size() ); - return first_[ index ]; + return (*this)[ pos ]; + } +#endif // deprecate + + gsl_NODISCARD gsl_api gsl_constexpr14 reference + front() const + { + gsl_Expects( first_ != last_ ); + return *first_; } - gsl_api gsl_constexpr pointer data() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr14 reference + back() const + { + gsl_Expects( first_ != last_ ); + return *(last_ - 1); + } + + gsl_NODISCARD gsl_api gsl_constexpr pointer + data() const gsl_noexcept { return first_; } // 26.7.3.6 Iterator support [span.iterators] - gsl_api gsl_constexpr iterator begin() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr iterator + begin() const gsl_noexcept { return iterator( first_ ); } - gsl_api gsl_constexpr iterator end() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr iterator + end() const gsl_noexcept { return iterator( last_ ); } - gsl_api gsl_constexpr const_iterator cbegin() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr const_iterator + cbegin() const gsl_noexcept { #if gsl_CPP11_OR_GREATER return { begin() }; @@ -1828,7 +4024,8 @@ class span #endif } - gsl_api gsl_constexpr const_iterator cend() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr const_iterator + cend() const gsl_noexcept { #if gsl_CPP11_OR_GREATER return { end() }; @@ -1837,36 +4034,40 @@ class span #endif } - gsl_api gsl_constexpr reverse_iterator rbegin() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 reverse_iterator + rbegin() const gsl_noexcept { return reverse_iterator( end() ); } - gsl_api gsl_constexpr reverse_iterator rend() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 reverse_iterator + rend() const gsl_noexcept { return reverse_iterator( begin() ); } - gsl_api gsl_constexpr const_reverse_iterator crbegin() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 const_reverse_iterator + crbegin() const gsl_noexcept { return const_reverse_iterator( cend() ); } - gsl_api gsl_constexpr const_reverse_iterator crend() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 const_reverse_iterator + crend() const gsl_noexcept { return const_reverse_iterator( cbegin() ); } - gsl_api void swap( span & other ) gsl_noexcept + gsl_constexpr14 void swap( span & other ) gsl_noexcept { - using std::swap; - swap( first_, other.first_ ); - swap( last_ , other.last_ ); + std::swap( first_, other.first_ ); + std::swap( last_ , other.last_ ); } #if ! gsl_DEPRECATE_TO_LEVEL( 3 ) // member length() deprecated since 0.29.0 + gsl_DEPRECATED_MSG("use size() instead") gsl_api gsl_constexpr index_type length() const gsl_noexcept { return size(); @@ -1874,6 +4075,7 @@ class span // member length_bytes() deprecated since 0.29.0 + gsl_DEPRECATED_MSG("use size_bytes() instead") gsl_api gsl_constexpr index_type length_bytes() const gsl_noexcept { return size_bytes(); @@ -1883,11 +4085,13 @@ class span #if ! gsl_DEPRECATE_TO_LEVEL( 2 ) // member as_bytes(), as_writeable_bytes deprecated since 0.17.0 + gsl_DEPRECATED_MSG("use free function gsl::as_bytes() instead") gsl_api span< const byte > as_bytes() const gsl_noexcept { return span< const byte >( reinterpret_cast( data() ), size_bytes() ); // NOLINT } + gsl_DEPRECATED_MSG("use free function gsl::as_writable_bytes() instead") gsl_api span< byte > as_writeable_bytes() const gsl_noexcept { return span< byte >( reinterpret_cast( data() ), size_bytes() ); // NOLINT @@ -1896,9 +4100,10 @@ class span #endif template< class U > - gsl_api span< U > as_span() const gsl_noexcept + gsl_NODISCARD gsl_api span< U > + as_span() const { - Expects( ( this->size_bytes() % sizeof(U) ) == 0 ); + gsl_Expects( ( this->size_bytes() % sizeof(U) ) == 0 ); return span< U >( reinterpret_cast( this->data() ), this->size_bytes() / sizeof( U ) ); // NOLINT } @@ -1930,71 +4135,79 @@ span( Container const & ) -> span; // 26.7.3.7 Comparison operators [span.comparison] -#if gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) +#if gsl_CONFIG( ALLOWS_SPAN_COMPARISON ) +# if gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T, class U > -gsl_api inline gsl_constexpr bool operator==( span const & l, span const & r ) +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr bool operator==( span const & l, span const & r ) { return l.size() == r.size() - && (l.begin() == r.begin() || std::equal( l.begin(), l.end(), r.begin() ) ); + && (l.begin() == r.begin() || detail::equal( l.begin(), l.end(), r.begin() ) ); } template< class T, class U > -gsl_api inline gsl_constexpr bool operator< ( span const & l, span const & r ) +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr bool operator< ( span const & l, span const & r ) { - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return detail::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } -#else +# else // a.k.a. !gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T > -gsl_api inline gsl_constexpr bool operator==( span const & l, span const & r ) +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr bool operator==( span const & l, span const & r ) { return l.size() == r.size() - && (l.begin() == r.begin() || std::equal( l.begin(), l.end(), r.begin() ) ); + && (l.begin() == r.begin() || detail::equal( l.begin(), l.end(), r.begin() ) ); } template< class T > -gsl_api inline gsl_constexpr bool operator< ( span const & l, span const & r ) +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr bool operator< ( span const & l, span const & r ) { - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return detail::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } -#endif +# endif // gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T, class U > -gsl_api inline gsl_constexpr bool operator!=( span const & l, span const & r ) +gsl_NODISCARD inline gsl_constexpr bool operator!=( span const & l, span const & r ) { return !( l == r ); } template< class T, class U > -gsl_api inline gsl_constexpr bool operator<=( span const & l, span const & r ) +gsl_NODISCARD inline gsl_constexpr bool operator<=( span const & l, span const & r ) { return !( r < l ); } template< class T, class U > -gsl_api inline gsl_constexpr bool operator> ( span const & l, span const & r ) +gsl_NODISCARD inline gsl_constexpr bool operator> ( span const & l, span const & r ) { return ( r < l ); } template< class T, class U > -gsl_api inline gsl_constexpr bool operator>=( span const & l, span const & r ) +gsl_NODISCARD inline gsl_constexpr bool operator>=( span const & l, span const & r ) { return !( l < r ); } +#endif // gsl_CONFIG( ALLOWS_SPAN_COMPARISON ) // span algorithms template< class T > -gsl_api inline gsl_constexpr std::size_t size( span const & spn ) +gsl_NODISCARD gsl_api inline gsl_constexpr std::size_t +size( span const & spn ) { return static_cast( spn.size() ); } template< class T > -gsl_api inline gsl_constexpr std::ptrdiff_t ssize( span const & spn ) +gsl_NODISCARD gsl_api inline gsl_constexpr std::ptrdiff_t +ssize( span const & spn ) { return spn.ssize(); } @@ -2002,7 +4215,7 @@ gsl_api inline gsl_constexpr std::ptrdiff_t ssize( span const & spn ) namespace detail { template< class II, class N, class OI > -gsl_api inline OI copy_n( II first, N count, OI result ) +gsl_api gsl_constexpr14 inline OI copy_n( II first, N count, OI result ) { if ( count > 0 ) { @@ -2017,47 +4230,58 @@ gsl_api inline OI copy_n( II first, N count, OI result ) } template< class T, class U > -gsl_api inline void copy( span src, span dest ) +gsl_api gsl_constexpr14 inline void copy( span src, span dest ) { #if gsl_CPP14_OR_GREATER // gsl_HAVE( TYPE_TRAITS ) (circumvent Travis clang 3.4) static_assert( std::is_assignable::value, "Cannot assign elements of source span to elements of destination span" ); #endif - Expects( dest.size() >= src.size() ); + gsl_Expects( dest.size() >= src.size() ); detail::copy_n( src.data(), src.size(), dest.data() ); } // span creator functions (see ctors) template< class T > -gsl_api inline span< const byte > as_bytes( span spn ) gsl_noexcept +gsl_NODISCARD gsl_api inline span< const byte > +as_bytes( span spn ) gsl_noexcept { return span< const byte >( reinterpret_cast( spn.data() ), spn.size_bytes() ); // NOLINT } template< class T> +gsl_NODISCARD gsl_api inline span< byte > +as_writable_bytes( span spn ) gsl_noexcept +{ + return span< byte >( reinterpret_cast( spn.data() ), spn.size_bytes() ); // NOLINT +} + +#if ! gsl_DEPRECATE_TO_LEVEL( 6 ) +template< class T> +gsl_DEPRECATED_MSG("use as_writable_bytes() (different spelling) instead") gsl_api inline span< byte > as_writeable_bytes( span spn ) gsl_noexcept { return span< byte >( reinterpret_cast( spn.data() ), spn.size_bytes() ); // NOLINT } +#endif // deprecate #if gsl_FEATURE_TO_STD( MAKE_SPAN ) template< class T > -gsl_api inline gsl_constexpr span +gsl_NODISCARD gsl_api inline gsl_constexpr span make_span( T * ptr, typename span::index_type count ) { return span( ptr, count ); } template< class T > -gsl_api inline gsl_constexpr span +gsl_NODISCARD gsl_api inline gsl_constexpr span make_span( T * first, T * last ) { return span( first, last ); } template< class T, size_t N > -gsl_api inline gsl_constexpr span +gsl_NODISCARD inline gsl_constexpr span make_span( T (&arr)[N] ) { return span( gsl_ADDRESSOF( arr[0] ), N ); @@ -2066,14 +4290,14 @@ make_span( T (&arr)[N] ) #if gsl_HAVE( ARRAY ) template< class T, size_t N > -gsl_api inline gsl_constexpr span +gsl_NODISCARD inline gsl_constexpr span make_span( std::array & arr ) { return span( arr ); } template< class T, size_t N > -gsl_api inline gsl_constexpr span +gsl_NODISCARD inline gsl_constexpr span make_span( std::array const & arr ) { return span( arr ); @@ -2082,31 +4306,31 @@ make_span( std::array const & arr ) #if gsl_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) && gsl_HAVE( AUTO ) -template< class Container, class = decltype(std::declval().data()) > -gsl_api inline gsl_constexpr auto -make_span( Container & cont ) -> span< typename Container::value_type > +template< class Container, class EP = decltype( std17::data(std::declval())) > +gsl_NODISCARD inline gsl_constexpr auto +make_span( Container & cont ) -> span< typename std::remove_pointer::type > { - return span< typename Container::value_type >( cont ); + return span< typename std::remove_pointer::type >( cont ); } -template< class Container, class = decltype(std::declval().data()) > -gsl_api inline gsl_constexpr auto -make_span( Container const & cont ) -> span< const typename Container::value_type > +template< class Container, class EP = decltype( std17::data(std::declval())) > +gsl_NODISCARD inline gsl_constexpr auto +make_span( Container const & cont ) -> span< const typename std::remove_pointer::type > { - return span< const typename Container::value_type >( cont ); + return span< const typename std::remove_pointer::type >( cont ); } #else template< class T > -gsl_api inline span +inline span make_span( std::vector & cont ) { return span( with_container, cont ); } template< class T > -gsl_api inline span +inline span make_span( std::vector const & cont ) { return span( with_container, cont ); @@ -2116,14 +4340,14 @@ make_span( std::vector const & cont ) #if gsl_FEATURE_TO_STD( WITH_CONTAINER ) template< class Container > -gsl_api inline gsl_constexpr span +gsl_NODISCARD inline gsl_constexpr span make_span( with_container_t, Container & cont ) gsl_noexcept { return span< typename Container::value_type >( with_container, cont ); } template< class Container > -gsl_api inline gsl_constexpr span +gsl_NODISCARD inline gsl_constexpr span make_span( with_container_t, Container const & cont ) gsl_noexcept { return span< const typename Container::value_type >( with_container, cont ); @@ -2131,18 +4355,22 @@ make_span( with_container_t, Container const & cont ) gsl_noexcept #endif // gsl_FEATURE_TO_STD( WITH_CONTAINER ) +#if !gsl_DEPRECATE_TO_LEVEL( 4 ) template< class Ptr > -gsl_api inline span +gsl_DEPRECATED +inline span make_span( Ptr & ptr ) { return span( ptr ); } +#endif // !gsl_DEPRECATE_TO_LEVEL( 4 ) template< class Ptr > -gsl_api inline span +gsl_DEPRECATED +inline span make_span( Ptr & ptr, typename span::index_type count ) { - return span( ptr, count); + return span( ptr, count ); } #endif // gsl_FEATURE_TO_STD( MAKE_SPAN ) @@ -2150,14 +4378,14 @@ make_span( Ptr & ptr, typename span::index_type coun #if gsl_FEATURE_TO_STD( BYTE_SPAN ) template< class T > -gsl_api inline gsl_constexpr span +gsl_NODISCARD gsl_api inline gsl_constexpr span byte_span( T & t ) gsl_noexcept { return span( reinterpret_cast( &t ), sizeof(T) ); } template< class T > -gsl_api inline gsl_constexpr span +gsl_NODISCARD gsl_api inline gsl_constexpr span byte_span( T const & t ) gsl_noexcept { return span( reinterpret_cast( &t ), sizeof(T) ); @@ -2208,6 +4436,7 @@ class basic_string_span typedef T element_type; typedef span span_type; + typedef typename span_type::size_type size_type; typedef typename span_type::index_type index_type; typedef typename span_type::difference_type difference_type; @@ -2222,18 +4451,21 @@ class basic_string_span // construction: #if gsl_HAVE( IS_DEFAULT ) - gsl_api gsl_constexpr basic_string_span() gsl_noexcept = default; + gsl_constexpr basic_string_span() gsl_noexcept = default; #else gsl_api gsl_constexpr basic_string_span() gsl_noexcept {} #endif #if gsl_HAVE( NULLPTR ) - gsl_api gsl_constexpr basic_string_span( std::nullptr_t ptr ) gsl_noexcept - : span_( ptr, index_type( 0 ) ) + gsl_api gsl_constexpr basic_string_span( std::nullptr_t ) gsl_noexcept + : span_( nullptr, static_cast( 0 ) ) {} #endif - gsl_api gsl_constexpr basic_string_span( pointer ptr ) +#ifdef __CUDACC_RELAXED_CONSTEXPR__ + gsl_api +#endif // __CUDACC_RELAXED_CONSTEXPR__ + gsl_constexpr basic_string_span( pointer ptr ) : span_( remove_z( ptr, (std::numeric_limits::max)() ) ) {} @@ -2246,19 +4478,19 @@ class basic_string_span {} template< std::size_t N > - gsl_api gsl_constexpr basic_string_span( element_type (&arr)[N] ) + gsl_constexpr basic_string_span( element_type (&arr)[N] ) : span_( remove_z( gsl_ADDRESSOF( arr[0] ), N ) ) {} #if gsl_HAVE( ARRAY ) template< std::size_t N > - gsl_api gsl_constexpr basic_string_span( std::array< typename std11::remove_const::type, N> & arr ) + gsl_constexpr basic_string_span( std::array< typename std11::remove_const::type, N> & arr ) : span_( remove_z( arr ) ) {} template< std::size_t N > - gsl_api gsl_constexpr basic_string_span( std::array< typename std11::remove_const::type, N> const & arr ) + gsl_constexpr basic_string_span( std::array< typename std11::remove_const::type, N> const & arr ) : span_( remove_z( arr ) ) {} @@ -2269,40 +4501,40 @@ class basic_string_span // Exclude: array, [basic_string,] basic_string_span template< class Container - gsl_REQUIRES_T(( + gsl_ENABLE_IF_(( ! detail::is_std_array< Container >::value && ! detail::is_basic_string_span< Container >::value && std::is_convertible< typename Container::pointer, pointer >::value && std::is_convertible< typename Container::pointer, decltype(std::declval().data()) >::value )) > - gsl_api gsl_constexpr basic_string_span( Container & cont ) + gsl_constexpr basic_string_span( Container & cont ) : span_( ( cont ) ) {} // Exclude: array, [basic_string,] basic_string_span template< class Container - gsl_REQUIRES_T(( + gsl_ENABLE_IF_(( ! detail::is_std_array< Container >::value && ! detail::is_basic_string_span< Container >::value && std::is_convertible< typename Container::pointer, pointer >::value && std::is_convertible< typename Container::pointer, decltype(std::declval().data()) >::value )) > - gsl_api gsl_constexpr basic_string_span( Container const & cont ) + gsl_constexpr basic_string_span( Container const & cont ) : span_( ( cont ) ) {} #elif gsl_HAVE( UNCONSTRAINED_SPAN_CONTAINER_CTOR ) template< class Container > - gsl_api gsl_constexpr basic_string_span( Container & cont ) + gsl_constexpr basic_string_span( Container & cont ) : span_( cont ) {} template< class Container > - gsl_api gsl_constexpr basic_string_span( Container const & cont ) + gsl_constexpr basic_string_span( Container const & cont ) : span_( cont ) {} @@ -2318,184 +4550,220 @@ class basic_string_span #if gsl_FEATURE_TO_STD( WITH_CONTAINER ) template< class Container > - gsl_api gsl_constexpr basic_string_span( with_container_t, Container & cont ) + gsl_constexpr basic_string_span( with_container_t, Container & cont ) : span_( with_container, cont ) {} #endif #if gsl_HAVE( IS_DEFAULT ) # if gsl_BETWEEN( gsl_COMPILER_GNUC_VERSION, 440, 600 ) - gsl_api gsl_constexpr basic_string_span( basic_string_span const & rhs ) = default; + gsl_constexpr basic_string_span( basic_string_span const & ) = default; - gsl_api gsl_constexpr basic_string_span( basic_string_span && rhs ) = default; + gsl_constexpr basic_string_span( basic_string_span && ) = default; # else - gsl_api gsl_constexpr basic_string_span( basic_string_span const & rhs ) gsl_noexcept = default; + gsl_constexpr basic_string_span( basic_string_span const & ) gsl_noexcept = default; - gsl_api gsl_constexpr basic_string_span( basic_string_span && rhs ) gsl_noexcept = default; + gsl_constexpr basic_string_span( basic_string_span && ) gsl_noexcept = default; # endif #endif template< class U -#if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - gsl_REQUIRES_T(( std::is_convertible::pointer, pointer>::value )) -#endif + gsl_ENABLE_IF_(( std::is_convertible::pointer, pointer>::value )) > gsl_api gsl_constexpr basic_string_span( basic_string_span const & rhs ) : span_( reinterpret_cast( rhs.data() ), rhs.length() ) // NOLINT {} -#if gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 120 +#if gsl_STDLIB_CPP11_120 template< class U - gsl_REQUIRES_T(( std::is_convertible::pointer, pointer>::value )) + gsl_ENABLE_IF_(( std::is_convertible::pointer, pointer>::value )) > gsl_api gsl_constexpr basic_string_span( basic_string_span && rhs ) : span_( reinterpret_cast( rhs.data() ), rhs.length() ) // NOLINT {} -#endif +#endif // gsl_STDLIB_CPP11_120 template< class CharTraits, class Allocator > - gsl_api gsl_constexpr basic_string_span( + gsl_constexpr basic_string_span( std::basic_string< typename std11::remove_const::type, CharTraits, Allocator > & str ) : span_( gsl_ADDRESSOF( str[0] ), str.length() ) {} template< class CharTraits, class Allocator > - gsl_api gsl_constexpr basic_string_span( + gsl_constexpr basic_string_span( std::basic_string< typename std11::remove_const::type, CharTraits, Allocator > const & str ) : span_( gsl_ADDRESSOF( str[0] ), str.length() ) {} - // destruction, assignment: + // assignment: #if gsl_HAVE( IS_DEFAULT ) - gsl_api ~basic_string_span() gsl_noexcept = default; + gsl_constexpr14 basic_string_span & operator=( basic_string_span const & ) gsl_noexcept = default; - gsl_api basic_string_span & operator=( basic_string_span const & rhs ) gsl_noexcept = default; - - gsl_api basic_string_span & operator=( basic_string_span && rhs ) gsl_noexcept = default; + gsl_constexpr14 basic_string_span & operator=( basic_string_span && ) gsl_noexcept = default; #endif // sub span: - gsl_api gsl_constexpr basic_string_span first( index_type count ) const + /*gsl_api*/ // currently disabled due to an apparent NVCC bug + gsl_NODISCARD gsl_constexpr14 basic_string_span + first( index_type count ) const { return span_.first( count ); } - gsl_api gsl_constexpr basic_string_span last( index_type count ) const + /*gsl_api*/ // currently disabled due to an apparent NVCC bug + gsl_NODISCARD gsl_constexpr14 basic_string_span + last( index_type count ) const { return span_.last( count ); } - gsl_api gsl_constexpr basic_string_span subspan( index_type offset ) const + /*gsl_api*/ // currently disabled due to an apparent NVCC bug + gsl_NODISCARD gsl_constexpr14 basic_string_span + subspan( index_type offset ) const { return span_.subspan( offset ); } - gsl_api gsl_constexpr basic_string_span subspan( index_type offset, index_type count ) const + /*gsl_api*/ // currently disabled due to an apparent NVCC bug + gsl_NODISCARD gsl_constexpr14 basic_string_span + subspan( index_type offset, index_type count ) const { return span_.subspan( offset, count ); } // observers: - gsl_api gsl_constexpr index_type length() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + length() const gsl_noexcept { return span_.size(); } - gsl_api gsl_constexpr index_type size() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + size() const gsl_noexcept { return span_.size(); } - gsl_api gsl_constexpr index_type length_bytes() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + length_bytes() const gsl_noexcept { return span_.size_bytes(); } - gsl_api gsl_constexpr index_type size_bytes() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr index_type + size_bytes() const gsl_noexcept { return span_.size_bytes(); } - gsl_api gsl_constexpr bool empty() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr bool + empty() const gsl_noexcept { return size() == 0; } - gsl_api gsl_constexpr reference operator[]( index_type idx ) const + gsl_NODISCARD gsl_api gsl_constexpr14 reference + operator[]( index_type idx ) const { return span_[idx]; } - gsl_api gsl_constexpr reference operator()( index_type idx ) const +#if ! gsl_DEPRECATE_TO_LEVEL( 6 ) + gsl_DEPRECATED_MSG("use subscript indexing instead") + gsl_api gsl_constexpr14 reference operator()( index_type idx ) const { return span_[idx]; } +#endif // deprecate + + gsl_NODISCARD gsl_api gsl_constexpr14 reference + front() const + { + return span_.front(); + } + + gsl_NODISCARD gsl_api gsl_constexpr14 reference + back() const + { + return span_.back(); + } - gsl_api gsl_constexpr pointer data() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr pointer + data() const gsl_noexcept { return span_.data(); } - gsl_api iterator begin() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr iterator + begin() const gsl_noexcept { return span_.begin(); } - gsl_api iterator end() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr iterator + end() const gsl_noexcept { return span_.end(); } - gsl_api reverse_iterator rbegin() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 reverse_iterator + rbegin() const gsl_noexcept { return span_.rbegin(); } - gsl_api reverse_iterator rend() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 reverse_iterator + rend() const gsl_noexcept { return span_.rend(); } // const version not in p0123r2: - gsl_api const_iterator cbegin() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr const_iterator + cbegin() const gsl_noexcept { return span_.cbegin(); } - gsl_api const_iterator cend() const gsl_noexcept + gsl_NODISCARD gsl_api gsl_constexpr const_iterator + cend() const gsl_noexcept { return span_.cend(); } - gsl_api const_reverse_iterator crbegin() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 const_reverse_iterator + crbegin() const gsl_noexcept { return span_.crbegin(); } - gsl_api const_reverse_iterator crend() const gsl_noexcept + gsl_NODISCARD gsl_constexpr17 const_reverse_iterator + crend() const gsl_noexcept { return span_.crend(); } private: - gsl_api static gsl_constexpr14 span_type remove_z( pointer const & sz, std::size_t max ) + gsl_api static gsl_constexpr14 span_type remove_z( pointer sz, std::size_t max ) { return span_type( sz, detail::string_length( sz, max ) ); } #if gsl_HAVE( ARRAY ) template< size_t N > - gsl_api static gsl_constexpr14 span_type remove_z( std::array::type, N> & arr ) + gsl_NODISCARD static gsl_constexpr14 span_type + remove_z( std::array::type, N> & arr ) { return remove_z( gsl_ADDRESSOF( arr[0] ), narrow_cast< std::size_t >( N ) ); } template< size_t N > - gsl_api static gsl_constexpr14 span_type remove_z( std::array::type, N> const & arr ) + gsl_NODISCARD static gsl_constexpr14 span_type + remove_z( std::array::type, N> const & arr ) { return remove_z( gsl_ADDRESSOF( arr[0] ), narrow_cast< std::size_t >( N ) ); } @@ -2510,71 +4778,85 @@ class basic_string_span #if gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator==( basic_string_span const & l, U const & u ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator==( basic_string_span const & l, U const & u ) gsl_noexcept { const basic_string_span< typename std11::add_const::type > r( u ); return l.size() == r.size() - && std::equal( l.begin(), l.end(), r.begin() ); + && detail::equal( l.begin(), l.end(), r.begin() ); } template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator<( basic_string_span const & l, U const & u ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator<( basic_string_span const & l, U const & u ) gsl_noexcept { const basic_string_span< typename std11::add_const::type > r( u ); - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return detail::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } #if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator==( U const & u, basic_string_span const & r ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator==( U const & u, basic_string_span const & r ) gsl_noexcept { const basic_string_span< typename std11::add_const::type > l( u ); return l.size() == r.size() - && std::equal( l.begin(), l.end(), r.begin() ); + && detail::equal( l.begin(), l.end(), r.begin() ); } template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator<( U const & u, basic_string_span const & r ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator<( U const & u, basic_string_span const & r ) gsl_noexcept { const basic_string_span< typename std11::add_const::type > l( u ); - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return detail::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } #endif #else //gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T > -gsl_api inline gsl_constexpr14 bool operator==( basic_string_span const & l, basic_string_span const & r ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator==( basic_string_span const & l, basic_string_span const & r ) gsl_noexcept { return l.size() == r.size() - && std::equal( l.begin(), l.end(), r.begin() ); + && detail::equal( l.begin(), l.end(), r.begin() ); } template< class T > -gsl_api inline gsl_constexpr14 bool operator<( basic_string_span const & l, basic_string_span const & r ) gsl_noexcept +gsl_SUPPRESS_MSGSL_WARNING(stl.1) +gsl_NODISCARD inline gsl_constexpr14 bool +operator<( basic_string_span const & l, basic_string_span const & r ) gsl_noexcept { - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return detail::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } #endif // gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator!=( basic_string_span const & l, U const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator!=( basic_string_span const & l, U const & r ) gsl_noexcept { return !( l == r ); } template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator<=( basic_string_span const & l, U const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator<=( basic_string_span const & l, U const & r ) gsl_noexcept { #if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) || ! gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) return !( r < l ); @@ -2585,7 +4867,8 @@ gsl_api inline gsl_constexpr14 bool operator<=( basic_string_span const & l, } template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator>( basic_string_span const & l, U const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator>( basic_string_span const & l, U const & r ) gsl_noexcept { #if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) || ! gsl_CONFIG( ALLOWS_NONSTRICT_SPAN_COMPARISON ) return ( r < l ); @@ -2596,7 +4879,8 @@ gsl_api inline gsl_constexpr14 bool operator>( basic_string_span const & l, U } template< class T, class U > -gsl_api inline gsl_constexpr14 bool operator>=( basic_string_span const & l, U const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator>=( basic_string_span const & l, U const & r ) gsl_noexcept { return !( l < r ); } @@ -2604,33 +4888,37 @@ gsl_api inline gsl_constexpr14 bool operator>=( basic_string_span const & l, #if gsl_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator!=( U const & l, basic_string_span const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator!=( U const & l, basic_string_span const & r ) gsl_noexcept { return !( l == r ); } template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator<=( U const & l, basic_string_span const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator<=( U const & l, basic_string_span const & r ) gsl_noexcept { return !( r < l ); } template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator>( U const & l, basic_string_span const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator>( U const & l, basic_string_span const & r ) gsl_noexcept { return ( r < l ); } template< class T, class U - gsl_REQUIRES_T(( !detail::is_basic_string_span::value )) + gsl_ENABLE_IF_(( !detail::is_basic_string_span::value )) > -gsl_api inline gsl_constexpr14 bool operator>=( U const & l, basic_string_span const & r ) gsl_noexcept +gsl_NODISCARD inline gsl_constexpr14 bool +operator>=( U const & l, basic_string_span const & r ) gsl_noexcept { return !( l < r ); } @@ -2640,7 +4928,8 @@ gsl_api inline gsl_constexpr14 bool operator>=( U const & l, basic_string_span -gsl_api inline span< const byte > as_bytes( basic_string_span spn ) gsl_noexcept +gsl_NODISCARD gsl_api inline span< const byte > +as_bytes( basic_string_span spn ) gsl_noexcept { return span< const byte >( reinterpret_cast( spn.data() ), spn.size_bytes() ); // NOLINT } @@ -2653,7 +4942,7 @@ typedef char * zstring; typedef const char * czstring; #if gsl_HAVE( WCHAR ) -typedef wchar_t * zwstring; +typedef wchar_t * wzstring; typedef const wchar_t * cwzstring; #endif @@ -2670,33 +4959,37 @@ typedef basic_string_span< wchar_t const > cwstring_span; #if 0 template< class T > -gsl_api inline std::basic_string< typename std::remove_const::type > to_string( basic_string_span spn ) +inline std::basic_string< typename std::remove_const::type > to_string( basic_string_span spn ) { std::string( spn.data(), spn.length() ); } #else -gsl_api inline std::string to_string( string_span const & spn ) +gsl_NODISCARD inline std::string +to_string( string_span const & spn ) { - return std::string( spn.data(), spn.length() ); + return std::string( spn.data(), static_cast( spn.length() ) ); } -gsl_api inline std::string to_string( cstring_span const & spn ) +gsl_NODISCARD inline std::string +to_string( cstring_span const & spn ) { - return std::string( spn.data(), spn.length() ); + return std::string( spn.data(), static_cast( spn.length() ) ); } #if gsl_HAVE( WCHAR ) -gsl_api inline std::wstring to_string( wstring_span const & spn ) +gsl_NODISCARD inline std::wstring +to_string( wstring_span const & spn ) { - return std::wstring( spn.data(), spn.length() ); + return std::wstring( spn.data(), static_cast( spn.length() ) ); } -gsl_api inline std::wstring to_string( cwstring_span const & spn ) +gsl_NODISCARD inline std::wstring +to_string( cwstring_span const & spn ) { - return std::wstring( spn.data(), spn.length() ); + return std::wstring( spn.data(), static_cast( spn.length() ) ); } #endif // gsl_HAVE( WCHAR ) @@ -2709,34 +5002,34 @@ gsl_api inline std::wstring to_string( cwstring_span const & spn ) namespace detail { template< class Stream > -gsl_api void write_padding( Stream & os, std::streamsize n ) +void write_padding( Stream & os, std::streamsize n ) { for ( std::streamsize i = 0; i < n; ++i ) os.rdbuf()->sputc( os.fill() ); } template< class Stream, class Span > -gsl_api Stream & write_to_stream( Stream & os, Span const & spn ) +Stream & write_to_stream( Stream & os, Span const & spn ) { typename Stream::sentry sentry( os ); if ( !os ) return os; - const std::streamsize length = narrow( spn.length() ); + const std::streamsize length = gsl::narrow_failfast( spn.length() ); // Whether, and how, to pad const bool pad = ( length < os.width() ); const bool left_pad = pad && ( os.flags() & std::ios_base::adjustfield ) == std::ios_base::right; if ( left_pad ) - write_padding( os, os.width() - length ); + detail::write_padding( os, os.width() - length ); // Write span characters os.rdbuf()->sputn( spn.begin(), length ); if ( pad && !left_pad ) - write_padding( os, os.width() - length ); + detail::write_padding( os, os.width() - length ); // Reset output stream width os.width(0); @@ -2747,13 +5040,13 @@ gsl_api Stream & write_to_stream( Stream & os, Span const & spn ) } // namespace detail template< typename Traits > -gsl_api std::basic_ostream< char, Traits > & operator<<( std::basic_ostream< char, Traits > & os, string_span const & spn ) +std::basic_ostream< char, Traits > & operator<<( std::basic_ostream< char, Traits > & os, string_span const & spn ) { return detail::write_to_stream( os, spn ); } template< typename Traits > -gsl_api std::basic_ostream< char, Traits > & operator<<( std::basic_ostream< char, Traits > & os, cstring_span const & spn ) +std::basic_ostream< char, Traits > & operator<<( std::basic_ostream< char, Traits > & os, cstring_span const & spn ) { return detail::write_to_stream( os, spn ); } @@ -2761,13 +5054,13 @@ gsl_api std::basic_ostream< char, Traits > & operator<<( std::basic_ostream< cha #if gsl_HAVE( WCHAR ) template< typename Traits > -gsl_api std::basic_ostream< wchar_t, Traits > & operator<<( std::basic_ostream< wchar_t, Traits > & os, wstring_span const & spn ) +std::basic_ostream< wchar_t, Traits > & operator<<( std::basic_ostream< wchar_t, Traits > & os, wstring_span const & spn ) { return detail::write_to_stream( os, spn ); } template< typename Traits > -gsl_api std::basic_ostream< wchar_t, Traits > & operator<<( std::basic_ostream< wchar_t, Traits > & os, cwstring_span const & spn ) +std::basic_ostream< wchar_t, Traits > & operator<<( std::basic_ostream< wchar_t, Traits > & os, cwstring_span const & spn ) { return detail::write_to_stream( os, spn ); } @@ -2785,20 +5078,19 @@ gsl_api std::basic_ostream< wchar_t, Traits > & operator<<( std::basic_ostream< namespace detail { template< class T, class SizeType, const T Sentinel > -gsl_api static span ensure_sentinel( T * seq, SizeType max = (std::numeric_limits::max)() ) +gsl_constexpr14 static span ensure_sentinel( T * seq, SizeType max = (std::numeric_limits::max)() ) { typedef T * pointer; gsl_SUPPRESS_MSVC_WARNING( 26429, "f.23: symbol 'cur' is never tested for nullness, it can be marked as not_null" ) - pointer cur = seq; while ( static_cast( cur - seq ) < max && *cur != Sentinel ) ++cur; - Expects( *cur == Sentinel ); + gsl_Expects( *cur == Sentinel ); - return span( seq, narrow_cast< typename span::index_type >( cur - seq ) ); + return span( seq, gsl::narrow_cast< typename span::index_type >( cur - seq ) ); } } // namespace detail @@ -2809,49 +5101,318 @@ gsl_api static span ensure_sentinel( T * seq, SizeType max = (std::numeric_li // template< class T > -gsl_api inline span ensure_z( T * const & sz, size_t max = (std::numeric_limits::max)() ) +gsl_NODISCARD inline gsl_constexpr14 span +ensure_z( T * const & sz, size_t max = (std::numeric_limits::max)() ) { return detail::ensure_sentinel( sz, max ); } template< class T, size_t N > -gsl_api inline span ensure_z( T (&sz)[N] ) +gsl_NODISCARD inline gsl_constexpr14 span +ensure_z( T (&sz)[N] ) { - return ensure_z( gsl_ADDRESSOF( sz[0] ), N ); + return ::gsl::ensure_z( gsl_ADDRESSOF( sz[0] ), N ); } # if gsl_HAVE( TYPE_TRAITS ) template< class Container > -gsl_api inline span< typename std::remove_pointer::type > +gsl_NODISCARD inline gsl_constexpr14 span< typename std::remove_pointer::type > ensure_z( Container & cont ) { - return ensure_z( cont.data(), cont.length() ); + return ::gsl::ensure_z( cont.data(), cont.length() ); } # endif +// +// basic_zstring_span<> - A view of contiguous null-terminated characters, replace (*,len). +// + +template +class basic_zstring_span +{ +public: + typedef T element_type; + typedef span span_type; + + typedef typename span_type::index_type index_type; + typedef typename span_type::difference_type difference_type; + + typedef element_type * czstring_type; + typedef basic_string_span string_span_type; + + gsl_api gsl_constexpr14 basic_zstring_span( span_type s ) + : span_( s ) + { + // expects a zero-terminated span + gsl_Expects( s.back() == '\0' ); + } + +#if gsl_HAVE( IS_DEFAULT ) + gsl_constexpr basic_zstring_span( basic_zstring_span const & ) = default; + gsl_constexpr basic_zstring_span( basic_zstring_span && ) = default; + gsl_constexpr14 basic_zstring_span & operator=( basic_zstring_span const & ) = default; + gsl_constexpr14 basic_zstring_span & operator=( basic_zstring_span && ) = default; +#else + gsl_api gsl_constexpr basic_zstring_span( basic_zstring_span const & other) : span_ ( other.span_ ) {} + gsl_api gsl_constexpr basic_zstring_span & operator=( basic_zstring_span const & other ) { span_ = other.span_; return *this; } +#endif + + gsl_NODISCARD gsl_api gsl_constexpr bool + empty() const gsl_noexcept + { + return false; + } + + gsl_NODISCARD gsl_api gsl_constexpr string_span_type + as_string_span() const gsl_noexcept + { + return string_span_type( span_.data(), span_.size() - 1 ); + } + + /*gsl_api*/ // currently disabled due to an apparent NVCC bug + gsl_NODISCARD gsl_constexpr string_span_type + ensure_z() const + { + return ::gsl::ensure_z(span_.data(), span_.size()); + } + + gsl_NODISCARD gsl_api gsl_constexpr czstring_type + assume_z() const gsl_noexcept + { + return span_.data(); + } + +private: + span_type span_; +}; + +// +// zString types: +// + +typedef basic_zstring_span< char > zstring_span; +typedef basic_zstring_span< char const > czstring_span; + +#if gsl_HAVE( WCHAR ) +typedef basic_zstring_span< wchar_t > wzstring_span; +typedef basic_zstring_span< wchar_t const > cwzstring_span; +#endif + } // namespace gsl -#if gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 120 +#if gsl_HAVE( HASH ) + +// +// std::hash specializations for GSL types +// + +namespace gsl { + +namespace detail { + +// +// Helper struct for std::hash specializations +// + +template +struct conditionally_enabled_hash +{ + +}; + +// disabled as described in [unord.hash] +template<> +struct conditionally_enabled_hash< false > +{ +gsl_is_delete_access: + conditionally_enabled_hash() gsl_is_delete; + conditionally_enabled_hash( conditionally_enabled_hash const & ) gsl_is_delete; + conditionally_enabled_hash( conditionally_enabled_hash && ) gsl_is_delete; + conditionally_enabled_hash & operator=( conditionally_enabled_hash const & ) gsl_is_delete; + conditionally_enabled_hash & operator=( conditionally_enabled_hash && ) gsl_is_delete; +}; + +} // namespace detail + +} // namespace gsl namespace std { +template< class T > +struct hash< ::gsl::not_null< T > > : public ::gsl::detail::conditionally_enabled_hash>::value> +{ +public: + gsl_NODISCARD gsl_constexpr std::size_t + operator()( ::gsl::not_null const & v ) const + // hash function is not `noexcept` because `as_nullable()` has preconditions + { + return hash()( ::gsl::as_nullable( v ) ); + } +}; +template< class T > +struct hash< ::gsl::not_null< T* > > +{ +public: + gsl_NODISCARD gsl_constexpr std::size_t + operator()( ::gsl::not_null< T* > const & v ) const gsl_noexcept + { + return hash()( ::gsl::as_nullable( v ) ); + } +}; + template<> -struct hash< gsl::byte > +struct hash< ::gsl::byte > { public: - std::size_t operator()( gsl::byte v ) const gsl_noexcept + gsl_NODISCARD gsl_constexpr std::size_t operator()( ::gsl::byte v ) const gsl_noexcept { - return gsl::to_integer( v ); + return ::gsl::to_integer( v ); } }; } // namespace std -#endif +#endif // gsl_HAVE( HASH ) + +#if gsl_FEATURE( GSL_LITE_NAMESPACE ) + +// gsl_lite namespace: + +// gsl-lite currently keeps all symbols in the namespace `gsl`. The `gsl_lite` namespace contains all the symbols in the +// `gsl` namespace, plus some extensions that are not specified in the Core Guidelines. +// +// Going forward, we want to support coexistence of gsl-lite with M-GSL, so we want to encourage using the `gsl_lite` +// namespace when consuming gsl-lite. Typical use in library code would be: +// +// #include // instead of +// +// namespace foo { +// namespace gsl = ::gsl_lite; // convenience alias +// double mean( gsl::span elements ) +// { +// gsl_Expects( ! elements.empty() ); // instead of Expects() +// ... +// } +// } // namespace foo +// +// In a future version, the new header will only define the `gsl_lite` namespace and no +// unprefixed `Expects()` and `Ensures()` macros to avoid collision with M-GSL. To ensure backward compatibility, the +// old header will keep defining the `gsl` namespace and the `Expects()` and `Ensures()` macros. + +namespace gsl_lite { + +namespace std11 = ::gsl::std11; +namespace std14 = ::gsl::std14; +namespace std17 = ::gsl::std17; +namespace std20 = ::gsl::std20; + +using namespace std11; +//using namespace std14; // contains only make_unique<>(), which is superseded by `gsl::make_unique<>()` +using namespace std17; +using namespace std20; + +using namespace ::gsl::detail::no_adl; + +# if gsl_HAVE( UNIQUE_PTR ) && gsl_HAVE( SHARED_PTR ) +using std::unique_ptr; +using std::shared_ptr; +# if gsl_HAVE( VARIADIC_TEMPLATE ) +using ::gsl::make_unique; +using ::gsl::make_shared; +# endif +# endif + +using ::gsl::index; +using ::gsl::dim; +using ::gsl::stride; +using ::gsl::diff; + +# if gsl_HAVE( ALIAS_TEMPLATE ) +# if gsl_BETWEEN( gsl_COMPILER_MSVC_VERSION, 1, 141 ) // VS 2015 and earlier have trouble with `using` for alias templates + template< class T +# if gsl_HAVE( TYPE_TRAITS ) + , typename = typename std::enable_if< std::is_pointer::value >::type +# endif + > + using owner = T; +# else +using ::gsl::owner; +# endif +# endif + +using ::gsl::fail_fast; + +using ::gsl::finally; +# if gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) +using ::gsl::on_return; +using ::gsl::on_error; +# endif // gsl_FEATURE( EXPERIMENTAL_RETURN_GUARD ) + +using ::gsl::narrow_cast; +using ::gsl::narrowing_error; +using ::gsl::narrow; +using ::gsl::narrow_failfast; + +using ::gsl::at; + +using ::gsl::not_null; +using ::gsl::not_null_ic; +using ::gsl::make_not_null; + +using ::gsl::byte; + +using ::gsl::to_byte; +using ::gsl::to_integer; +using ::gsl::to_uchar; +using ::gsl::to_string; + +using ::gsl::with_container_t; +using ::gsl::with_container; + +using ::gsl::span; +using ::gsl::make_span; +using ::gsl::byte_span; +using ::gsl::copy; +using ::gsl::as_bytes; +using ::gsl::as_writable_bytes; +# if ! gsl_DEPRECATE_TO_LEVEL( 6 ) +using ::gsl::as_writeable_bytes; +# endif + +using ::gsl::basic_string_span; +using ::gsl::string_span; +using ::gsl::cstring_span; + +using ::gsl::basic_zstring_span; +using ::gsl::zstring_span; +using ::gsl::czstring_span; + +using ::gsl::zstring; +using ::gsl::czstring; + +# if gsl_HAVE( WCHAR ) +using ::gsl::wzstring; +using ::gsl::cwzstring; + +using ::gsl::wzstring_span; +using ::gsl::cwzstring_span; +# endif // gsl_HAVE( WCHAR ) + +using ::gsl::ensure_z; + +} // namespace gsl_lite + +#endif // gsl_FEATURE( GSL_LITE_NAMESPACE ) gsl_RESTORE_MSVC_WARNINGS() +// #undef internal macros +#undef gsl_STATIC_ASSERT_ +#undef gsl_ENABLE_IF_ +#undef gsl_TRAILING_RETURN_TYPE_ +#undef gsl_RETURN_DECLTYPE_ + #endif // GSL_GSL_LITE_HPP_INCLUDED // end of file diff --git a/documentation/amici_refs.bib b/documentation/amici_refs.bib index 900728cb1e..ded97337cd 100644 --- a/documentation/amici_refs.bib +++ b/documentation/amici_refs.bib @@ -1,5 +1,3 @@ -% Encoding: UTF-8 - @article{BallnusHug2017, Author = {Ballnus, B. and Hug, S. and Hatz, K. and G{\"o}rlitz, L. and Hasenauer, J. and Theis, F. J.}, Date-Added = {2019-03-19 23:04:09 +0100}, @@ -456,19 +454,6 @@ @Article{FroehlichKes2018 url = {https://doi.org/10.1016/j.cels.2018.10.013}, } -@Article{StaporSch2019, - author = {Stapor, Paul and Schmiester, Leonard and Wierling, Christoph and Lange, Bodo and Weindl, Daniel and Hasenauer, Jan}, - title = {Mini-batch optimization enables training of ODE models on large-scale datasets}, - journal = {bioRxiv}, - year = {2019}, - abstract = {Quantitative dynamical models are widely used to study cellular signal processing. A critical step in modeling is the estimation of unknown model parameters from experimental data. As model sizes and datasets are steadily growing, established parameter optimization approaches for mechanistic models become computationally extremely challenging. However, mini-batch optimization methods, as employed in deep learning, have better scaling properties. In this work, we adapt, apply, and benchmark mini-batch optimization for ordinary differential equation (ODE) models thereby establishing a direct link between dynamic modeling and machine learning. On our main application example, a large-scale model of cancer signaling, we benchmark mini-batch optimization against established methods, achieving better optimization results and reducing computation by more than an order of magnitude. We expect that our work will serve as a first step towards mini-batch optimization tailored to ODE models and enable modeling of even larger and more complex systems than what is currently possible.}, - doi = {10.1101/859884}, - elocation-id = {859884}, - eprint = {https://www.biorxiv.org/content/early/2019/11/30/859884.full.pdf}, - publisher = {Cold Spring Harbor Laboratory}, - url = {https://www.biorxiv.org/content/early/2019/11/30/859884}, -} - @Article{AlabertLoo2020, author = {Alabert, Constance and Loos, Carolin and Voelker-Albert, Moritz and Graziano, Simona and Forné, Ignasi and Reveron-Gomez, Nazaret and Schuh, Lea and Hasenauer, Jan and Marr, Carsten and Imhof, Axel and Groth, Anja}, journal = {Cell reports}, @@ -669,62 +654,6 @@ @Article{Kuritz2020.03.30.015909 url = {https://www.biorxiv.org/content/early/2020/03/31/2020.03.30.015909}, } -@Article{Schmucker2020.07.05.184960, - author = {Schmucker, Robin and Farina, Gabriele and Faeder, James and Fr{\"o}hlich, Fabian and Saglam, Ali Sinan and Sandholm, Tuomas}, - journal = {bioRxiv}, - title = {Combination Treatment Optimization Using a Pan-Cancer Pathway Model}, - year = {2020}, - abstract = {The design of efficient combination therapies is a difficult key challenge in the treatment of complex diseases such as cancers. The large heterogeneity of cancers and the large number of available drugs renders exhaustive in vivo or even in vitro investigation of possible treatments impractical. In recent years, sophisti-cated mechanistic, ordinary differential equation-based pathways models that can predict treatment responses at a molecular level have been developed. However, surprisingly little effort has been put into leveraging these models to find novel therapies. In this paper we use for the first time, to our knowledge, a large-scale state-of-the-art pan-cancer signaling pathway model to identify potentially novel combination therapies to treat individual cancer cell lines from various tissues (e.g., minimizing proliferation while keeping dosage low to avoid adverse side effects) and populations of cancer cell lines (e.g., minimizing the maximum or average proliferation across the cell lines while keeping dosage low). We also show how our method can be used to optimize the mixtures and dosages used in sequential treatment plans{\textemdash}that is, optimized sequences of potentially different drug combinations{\textemdash}providing additional benefits. In order to solve the treatment optimization problems, we combine the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) algorithm with a significantly more scalable sampling scheme for truncated Gaussian distributions, based on a Hamiltonian Monte-Carlo method. These optimization techniques are independent of the signaling pathway model, and can thus be used for other signaling pathway models also, provided that a suitable predictive model is available.Competing Interest StatementThe authors have declared no competing interest.}, - doi = {10.1101/2020.07.05.184960}, - elocation-id = {2020.07.05.184960}, - eprint = {https://www.biorxiv.org/content/early/2020/07/06/2020.07.05.184960.full.pdf}, - publisher = {Cold Spring Harbor Laboratory}, - timestamp = {2020-11-09}, - url = {https://www.biorxiv.org/content/early/2020/07/06/2020.07.05.184960}, -} - -@Article{Schuh2020.05.28.110684, - author = {Schuh, Lea and Loos, Carolin and Pokrovsky, Daniil and Imhof, Axel and Rupp, Ralph and Marr, Carsten}, - journal = {bioRxiv}, - title = {Computational modeling reveals cell-cycle dependent kinetics of H4K20 methylation states during Xenopus embryogenesis}, - year = {2020}, - abstract = {Histone modifications regulate chromatin architecture and thereby control gene expression. Rapid cell divisions and DNA replication however lead to a dilution of histone modifications and can thus affect chromatin mediated gene regulation So how does the cell-cycle shape the histone modification landscape, in particular during embryogenesis when a fast and precise control of cell-specific gene expression is required?We addressed this question in vivo by manipulating the cell-cycle during early Xenopus laevis embryogenesis. The global distribution of un-, mono- di- and tri-methylated histone H4K20 was measured by mass spectrometry in normal and cell-cycle arrested embryos over time. Using multi-start maximum likelihood optimization and quantitative model selection, we found that three specific methylation rate constants were required to explain the measured H4K20 methylation state kinetics. Interestingly, demethylation was found to be redundant in the cycling embryos but essential in the cell-cycle arrested embryos.Together, we present the first quantitative analysis of in vivo histone H4K20 methylation kinetics. Our computational model shows that demethylation is only essential for regulating H4K20 methylation kinetics in non-cycling cells. In rapidly dividing cells of early embryos, we predict that demethylation is dispensable, suggesting that cell-cycle mediated dilution of chromatin marks is an essential regulatory component for shaping the epigenetic landscape during early embryonic development.Competing Interest StatementThe authors have declared no competing interest.}, - doi = {10.1101/2020.05.28.110684}, - elocation-id = {2020.05.28.110684}, - eprint = {https://www.biorxiv.org/content/early/2020/05/30/2020.05.28.110684.full.pdf}, - publisher = {Cold Spring Harbor Laboratory}, - timestamp = {2020-11-09}, - url = {https://www.biorxiv.org/content/early/2020/05/30/2020.05.28.110684}, -} - -@Article{Schaelte2020.01.30.927004, - author = {Sch{\"a}lte, Yannik and Hasenauer, Jan}, - journal = {bioRxiv}, - title = {Efficient Exact Inference for Dynamical Systems with Noisy Measurements using Sequential Approximate Bayesian Computation}, - year = {2020}, - abstract = {Motivation Approximate Bayesian Computation (ABC) is an increasingly popular method for likelihood-free parameter inference in systems biology and other fields of research, since it allows analysing complex stochastic models. However, the introduced approximation error is often not clear. It has been shown that ABC actually gives exact inference under the implicit assumption of a measurement noise model. Noise being common in biological systems, it is intriguing to exploit this insight. But this is difficult in practice, since ABC is in general highly computationally demanding. Thus, the question we want to answer here is how to efficiently account for measurement noise in ABC.Results We illustrate exemplarily how ABC yields erroneous parameter estimates when neglecting measurement noise. Then, we discuss practical ways of correctly including the measurement noise in the analysis. We present an efficient adaptive sequential importance sampling based algorithm applicable to various model types and noise models. We test and compare it on several models, including ordinary and stochastic differential equations, Markov jump processes, and stochastically interacting agents, and noise models including normal, Laplace, and Poisson noise. We conclude that the proposed algorithm could improve the accuracy of parameter estimates for a broad spectrum of applications.Availability The developed algorithms are made publicly available as part of the open-source python toolbox pyABC (https://github.com/icb-dcm/pyabc).Contact jan.hasenauer{at}uni-bonn.deSupplementary information Supplementary information is available at bioRxiv online. Supplementary code and data are available online at http://doi.org/10.5281/zenodo.3631120.}, - doi = {10.1101/2020.01.30.927004}, - elocation-id = {2020.01.30.927004}, - eprint = {https://www.biorxiv.org/content/early/2020/01/31/2020.01.30.927004.full.pdf}, - publisher = {Cold Spring Harbor Laboratory}, - timestamp = {2020-11-09}, - url = {https://www.biorxiv.org/content/early/2020/01/31/2020.01.30.927004}, -} - -@Article{AdlungSta2019, - author = {Adlung, Lorenz and Stapor, Paul and T{\"o}nsing, Christian and Schmiester, Leonard and Schwarzm{\"u}ller, Luisa E. and Wang, Dantong and Timmer, Jens and Klingm{\"u}ller, Ursula and Hasenauer, Jan and Schilling, Marcel}, - journal = {bioRxiv}, - title = {Cell-to-cell variability in JAK2/STAT5 pathway components and cytoplasmic volumes define survival threshold in erythroid progenitor cells}, - year = {2019}, - abstract = {Survival or apoptosis is a binary decision in individual cells. Yet, at the cell population level, a graded increase in survival of CFU-E cells is observed upon stimulation with Erythropoietin (Epo). To identify components of JAK2/STAT5 signal transduction that contribute to the graded population response, a cell population-level model calibrated with experimental data was extended to study the behavior in single cells. The single-cell model showed that the high cell-to-cell variability in nuclear phosphorylated STAT5 is caused by variability in the amount of EpoR:JAK2 complexes and of SHP1 as well as the extent of nuclear import due to the large variance in the cytoplasmic volume of CFU-E cells. 24 to 118 pSTAT5 molecules in the nucleus for 120 min are sufficient to ensure cell survival. Thus, variability in membrane-associated processes are responsible to convert a switch-like behavior at the single-cell level to a graded population level response.HighlightsMathematical modeling enables integration of heterogeneous dataSingle-cell modeling captures binary decision processMultiple sources of cell-to-cell variability in erythroid progenitor cellsMinimal amount of active STAT5 sufficient for survival of erythroid progenitor cells}, - doi = {10.1101/866871}, - elocation-id = {866871}, - eprint = {https://www.biorxiv.org/content/early/2019/12/07/866871.full.pdf}, - publisher = {Cold Spring Harbor Laboratory}, - timestamp = {2020-11-09}, - url = {https://www.biorxiv.org/content/early/2019/12/07/866871}, -} - @Article{PittGom2018, author = {Jake Alan Pitt and Lucian Gomoescu and Constantinos C. Pantelides and Benoît Chachuat and Julio R. Banga}, journal = {IFAC-PapersOnLine}, @@ -864,14 +793,6 @@ @Article{VanhoeferMat2021 url = {https://doi.org/10.21105/joss.03215}, } -@Misc{VillaverdePat2021, - author = {Alejandro F. Villaverde and Dilan Pathirana and Fabian Fröhlich and Jan Hasenauer and Julio R. Banga}, - title = {A protocol for dynamic model calibration}, - year = {2021}, - archiveprefix = {arXiv}, - eprint = {2105.12008}, - primaryclass = {q-bio.QM}, -} @article {Froehlich2021.05.20.445065, author = {Fr{\"o}hlich, Fabian and Sorger, Peter K.}, title = {Fides: Reliable Trust-Region Optimization for Parameter Estimation of Ordinary Differential Equation Models}, @@ -937,6 +858,7 @@ @Misc{MaierHar2020 eprint = {2006.01061}, primaryclass = {stat.ML}, } + @phdthesis{Maier2021, author = {Corinna Maier}, title = {Bayesian data assimilation and reinforcement learning for model-informed precision dosing in oncology}, @@ -946,6 +868,7 @@ @phdthesis{Maier2021 doi = {10.25932/publishup-51587}, year = {2021}, } + @article {Contento2021.10.01.21263052, author = {Contento, Lorenzo and Castelletti, Noemi and Raim{\'u}ndez, Elba and Le Gleut, Ronan and Sch{\"a}lte, Yannik and Stapor, Paul and Hinske, Ludwig Christian and H{\"o}lscher, Michael and Wieser, Andreas and Radon, Katja and Fuchs, Christiane and Hasenauer, Jan and the KoCo19 study group}, title = {Integrative modelling of reported case numbers and seroprevalence reveals time-dependent test efficiency and infection rates}, @@ -983,6 +906,99 @@ @Article{GudinaAli2021 url = {https://www.sciencedirect.com/science/article/pii/S2214109X21003867}, } +@Article{StaporSch2022, + author = {Stapor, Paul and Schmiester, Leonard and Wierling, Christoph and Merkt, Simon and Pathirana, Dilan and Lange, Bodo M. H. and Weindl, Daniel and Hasenauer, Jan}, + journal = {Nature Communications}, + title = {{Mini-batch optimization enables training of ODE models on large-scale datasets}}, + year = {2022}, + issn = {2041-1723}, + number = {1}, + pages = {34}, + volume = {13}, + abstract = {Quantitative dynamic models are widely used to study cellular signal processing. A critical step in modelling is the estimation of unknown model parameters from experimental data. As model sizes and datasets are steadily growing, established parameter optimization approaches for mechanistic models become computationally extremely challenging. Mini-batch optimization methods, as employed in deep learning, have better scaling properties. In this work, we adapt, apply, and benchmark mini-batch optimization for ordinary differential equation (ODE) models, thereby establishing a direct link between dynamic modelling and machine learning. On our main application example, a large-scale model of cancer signaling, we benchmark mini-batch optimization against established methods, achieving better optimization results and reducing computation by more than an order of magnitude. We expect that our work will serve as a first step towards mini-batch optimization tailored to ODE models and enable modelling of even larger and more complex systems than what is currently possible.}, + doi = {10.1038/s41467-021-27374-6}, + refid = {Stapor2022}, + url = {https://doi.org/10.1038/s41467-021-27374-6}, +} + +@Article{SchmuckerFar2022, + author = {Schmucker, Robin and Farina, Gabriele and Faeder, James and Fröhlich, Fabian and Saglam, Ali Sinan and Sandholm, Tuomas}, + journal = {PLOS Computational Biology}, + title = {Combination treatment optimization using a pan-cancer pathway model}, + year = {2022}, + month = {12}, + number = {12}, + pages = {1-22}, + volume = {17}, + abstract = {The design of efficient combination therapies is a difficult key challenge in the treatment of complex diseases such as cancers. The large heterogeneity of cancers and the large number of available drugs renders exhaustive in vivo or even in vitro investigation of possible treatments impractical. In recent years, sophisticated mechanistic, ordinary differential equation-based pathways models that can predict treatment responses at a molecular level have been developed. However, surprisingly little effort has been put into leveraging these models to find novel therapies. In this paper we use for the first time, to our knowledge, a large-scale state-of-the-art pan-cancer signaling pathway model to identify candidates for novel combination therapies to treat individual cancer cell lines from various tissues (e.g., minimizing proliferation while keeping dosage low to avoid adverse side effects) and populations of heterogeneous cancer cell lines (e.g., minimizing the maximum or average proliferation across the cell lines while keeping dosage low). We also show how our method can be used to optimize the drug combinations used in sequential treatment plans—that is, optimized sequences of potentially different drug combinations—providing additional benefits. In order to solve the treatment optimization problems, we combine the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) algorithm with a significantly more scalable sampling scheme for truncated Gaussian distributions, based on a Hamiltonian Monte-Carlo method. These optimization techniques are independent of the signaling pathway model, and can thus be adapted to find treatment candidates for other complex diseases than cancers as well, as long as a suitable predictive model is available.}, + doi = {10.1371/journal.pcbi.1009689}, + publisher = {Public Library of Science}, + url = {https://doi.org/10.1371/journal.pcbi.1009689}, +} + +@Article{SchuhLoo2020, + author = {Schuh, Lea and Loos, Carolin and Pokrovsky, Daniil and Imhof, Axel and Rupp, Ralph A. W. and Marr, Carsten}, + journal = {Cell Systems}, + title = {H4K20 Methylation Is Differently Regulated by Dilution and Demethylation in Proliferating and Cell-Cycle-Arrested Xenopus Embryos}, + year = {2020}, + issn = {2405-4712}, + month = dec, + number = {6}, + pages = {653--662.e8}, + volume = {11}, + abstract = {DNA replication during cell division leads to dilution of histone modifications and can thus affect chromatin-mediated gene regulation, raising the question of how the cell-cycle shapes the histone modification landscape, particularly during embryogenesis. We tackled this problem by manipulating the cell cycle during early Xenopus laevis embryogenesis and analyzing in vivo histone H4K20 methylation kinetics. The global distribution of un-, mono-, di-, and tri-methylated histone H4K20 was measured by mass spectrometry in normal and cell-cycle-arrested embryos over time. Using multi-start maximum likelihood optimization and quantitative model selection, we found that three specific biological methylation rate constants were required to explain the measured H4K20 methylation state kinetics. While demethylation is essential for regulating H4K20 methylation kinetics in non-cycling cells, demethylation is very likely dispensable in rapidly dividing cells of early embryos, suggesting that cell-cycle-mediated dilution of H4K20 methylation is an essential regulatory component for shaping its epigenetic landscape during early development.A record of this paper?s transparent peer review process is included in the Supplemental Information.}, + comment = {doi: 10.1016/j.cels.2020.11.003}, + doi = {10.1016/j.cels.2020.11.003}, + publisher = {Elsevier}, + url = {https://doi.org/10.1016/j.cels.2020.11.003}, +} + +@Article{VillaverdePat2021, + author = {Villaverde, Alejandro F and Pathirana, Dilan and Fröhlich, Fabian and Hasenauer, Jan and Banga, Julio R}, + journal = {Briefings in Bioinformatics}, + title = {{A protocol for dynamic model calibration}}, + year = {2021}, + issn = {1477-4054}, + month = {10}, + note = {bbab387}, + abstract = {{Ordinary differential equation models are nowadays widely used for the mechanistic description of biological processes and their temporal evolution. These models typically have many unknown and nonmeasurable parameters, which have to be determined by fitting the model to experimental data. In order to perform this task, known as parameter estimation or model calibration, the modeller faces challenges such as poor parameter identifiability, lack of sufficiently informative experimental data and the existence of local minima in the objective function landscape. These issues tend to worsen with larger model sizes, increasing the computational complexity and the number of unknown parameters. An incorrectly calibrated model is problematic because it may result in inaccurate predictions and misleading conclusions. For nonexpert users, there are a large number of potential pitfalls. Here, we provide a protocol that guides the user through all the steps involved in the calibration of dynamic models. We illustrate the methodology with two models and provide all the code required to reproduce the results and perform the same analysis on new models. Our protocol provides practitioners and researchers in biological modelling with a one-stop guide that is at the same time compact and sufficiently comprehensive to cover all aspects of the problem.}}, + doi = {10.1093/bib/bbab387}, + eprint = {https://academic.oup.com/bib/advance-article-pdf/doi/10.1093/bib/bbab387/40534209/bbab387.pdf}, + url = {https://doi.org/10.1093/bib/bbab387}, +} + +@Article{SchaelteHas2020, + author = {Schälte, Yannik and Hasenauer, Jan}, + journal = {Bioinformatics}, + title = {{Efficient exact inference for dynamical systems with noisy measurements using sequential approximate Bayesian computation}}, + year = {2020}, + issn = {1367-4803}, + month = {07}, + number = {Supplement_1}, + pages = {i551-i559}, + volume = {36}, + abstract = {{Approximate Bayesian computation (ABC) is an increasingly popular method for likelihood-free parameter inference in systems biology and other fields of research, as it allows analyzing complex stochastic models. However, the introduced approximation error is often not clear. It has been shown that ABC actually gives exact inference under the implicit assumption of a measurement noise model. Noise being common in biological systems, it is intriguing to exploit this insight. But this is difficult in practice, as ABC is in general highly computationally demanding. Thus, the question we want to answer here is how to efficiently account for measurement noise in ABC.We illustrate exemplarily how ABC yields erroneous parameter estimates when neglecting measurement noise. Then, we discuss practical ways of correctly including the measurement noise in the analysis. We present an efficient adaptive sequential importance sampling-based algorithm applicable to various model types and noise models. We test and compare it on several models, including ordinary and stochastic differential equations, Markov jump processes and stochastically interacting agents, and noise models including normal, Laplace and Poisson noise. We conclude that the proposed algorithm could improve the accuracy of parameter estimates for a broad spectrum of applications.The developed algorithms are made publicly available as part of the open-source python toolbox pyABC (https://github.com/icb-dcm/pyabc).Supplementary data are available at Bioinformatics online.}}, + doi = {10.1093/bioinformatics/btaa397}, + eprint = {https://academic.oup.com/bioinformatics/article-pdf/36/Supplement\_1/i551/33488985/btaa397.pdf}, + url = {https://doi.org/10.1093/bioinformatics/btaa397}, +} + +@Article{AdlungSta2021, + author = {Lorenz Adlung and Paul Stapor and Christian Tönsing and Leonard Schmiester and Luisa E. Schwarzmüller and Lena Postawa and Dantong Wang and Jens Timmer and Ursula Klingmüller and Jan Hasenauer and Marcel Schilling}, + journal = {Cell Reports}, + title = {Cell-to-cell variability in JAK2/STAT5 pathway components and cytoplasmic volumes defines survival threshold in erythroid progenitor cells}, + year = {2021}, + issn = {2211-1247}, + number = {6}, + pages = {109507}, + volume = {36}, + abstract = {Summary +Survival or apoptosis is a binary decision in individual cells. However, at the cell-population level, a graded increase in survival of colony-forming unit-erythroid (CFU-E) cells is observed upon stimulation with erythropoietin (Epo). To identify components of Janus kinase 2/signal transducer and activator of transcription 5 (JAK2/STAT5) signal transduction that contribute to the graded population response, we extended a cell-population-level model calibrated with experimental data to study the behavior in single cells. The single-cell model shows that the high cell-to-cell variability in nuclear phosphorylated STAT5 is caused by variability in the amount of Epo receptor (EpoR):JAK2 complexes and of SHP1, as well as the extent of nuclear import because of the large variance in the cytoplasmic volume of CFU-E cells. 24–118 pSTAT5 molecules in the nucleus for 120 min are sufficient to ensure cell survival. Thus, variability in membrane-associated processes is sufficient to convert a switch-like behavior at the single-cell level to a graded population-level response.}, + doi = {https://doi.org/10.1016/j.celrep.2021.109507}, + keywords = {single-cell modeling, JAK/STAT, signal transduction, Epo, heterogeneity, cell fate decision, apoptosis, CFU-E cells, transcription factor, mathematical modeling}, + url = {https://www.sciencedirect.com/science/article/pii/S2211124721009372}, +} + @Comment{jabref-meta: databaseType:bibtex;} @Comment{jabref-meta: grouping: diff --git a/documentation/conf.py b/documentation/conf.py index de30887b3a..c647bda326 100644 --- a/documentation/conf.py +++ b/documentation/conf.py @@ -7,18 +7,23 @@ # http://www.sphinx-doc.org/en/stable/config import os -import sys import re -import mock import subprocess +import sys +import typing -from sphinx.transforms.post_transforms import ReferencesResolver +import exhale.deploy import exhale_multiproject_monkeypatch +import mock from exhale import configs as exhale_configs -import exhale.deploy +from sphinx.transforms.post_transforms import ReferencesResolver + +# need to import before setting typing.TYPE_CHECKING=True, fails otherwise +import pandas as pd + +exhale_multiproject_monkeypatch, pd # to avoid removal of unused import # BEGIN Monkeypatch exhale -exhale_multiproject_monkeypatch # to avoid removal of unused import from exhale.deploy import _generate_doxygen as exhale_generate_doxygen @@ -33,7 +38,7 @@ def my_exhale_generate_doxygen(doxygen_input): 'build', 'mtocpp_post') subprocess.run([mtocpp_post, doxy_xml_dir]) - # let exhale do it's job + # let exhale do its job exhale_generate_doxygen(doxygen_input) @@ -45,7 +50,8 @@ def my_exhale_generate_doxygen(doxygen_input): from breathe.renderer.sphinxrenderer import \ DomainDirectiveFactory as breathe_DomainDirectiveFactory -old_breathe_DomainDirectiveFactory_create = breathe_DomainDirectiveFactory.create +old_breathe_DomainDirectiveFactory_create = \ + breathe_DomainDirectiveFactory.create def my_breathe_DomainDirectiveFactory_create(domain: str, args): @@ -60,7 +66,8 @@ def my_breathe_DomainDirectiveFactory_create(domain: str, args): return cls(domain + ':' + name, *args[1:]) -breathe_DomainDirectiveFactory.create = my_breathe_DomainDirectiveFactory_create +breathe_DomainDirectiveFactory.create = \ + my_breathe_DomainDirectiveFactory_create # END Monkeypatch breathe @@ -115,7 +122,7 @@ def install_amici_deps_rtd(): def install_doxygen(): """Get a more recent doxygen""" - version = '1.9.1' + version = '1.9.3' doxygen_exe = os.path.join(amici_dir, 'ThirdParty', f'doxygen-{version}', 'bin', 'doxygen') # to create a symlink to doxygen in a location that is already on PATH @@ -135,12 +142,12 @@ def install_doxygen(): print(res.stdout.decode(), res.stderr.decode()) assert version in res.stdout.decode() + # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -# amici_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -155,6 +162,8 @@ def install_doxygen(): install_mtocpp() # Install AMICI if not already present +typing.TYPE_CHECKING = True + try: import amici except ModuleNotFoundError: @@ -172,6 +181,9 @@ def install_doxygen(): import amici +typing.TYPE_CHECKING = False + + # -- Project information ----------------------------------------------------- # The short X.Y version version = amici.__version__ @@ -583,8 +595,8 @@ def fix_typehints(sig: str) -> str: sig = re.sub(r' &$', r'', sig) # turn gsl_spans and pointers int Iterables - sig = re.sub(r'([\w\.]+) \*', r'Iterable[\1]', sig) - sig = re.sub(r'gsl::span< ([\w\.]+) >', r'Iterable[\1]', sig) + sig = re.sub(r'([\w.]+) \*', r'Iterable[\1]', sig) + sig = re.sub(r'gsl::span< ([\w.]+) >', r'Iterable[\1]', sig) # fix garbled output sig = sig.replace(' >', '') diff --git a/documentation/python_installation.rst b/documentation/python_installation.rst index 8790832749..59e98dc285 100644 --- a/documentation/python_installation.rst +++ b/documentation/python_installation.rst @@ -388,6 +388,15 @@ install the latter locally, using: conda install -c conda-forge openblas +To make AMICI use openblas, set the following environment variable: + +.. code-block:: bash + + export BLAS_LIBS=-lopenblas + +``BLAS_LIBS`` needs to be set during installation of the AMICI package, as +well as during any future model import. + To install AMICI, now run: .. code-block:: bash diff --git a/documentation/references.md b/documentation/references.md index 42979d7e81..4eb30a5013 100644 --- a/documentation/references.md +++ b/documentation/references.md @@ -4,8 +4,20 @@ List of publications using AMICI. Total number is 64. If you applied AMICI in your work and your publication is missing, please let us know via a new Github issue. +

2022

+
+
+

Schmucker, Robin, Gabriele Farina, James Faeder, Fabian Fröhlich, Ali Sinan Saglam, and Tuomas Sandholm. 2022. “Combination Treatment Optimization Using a Pan-Cancer Pathway Model.” PLOS Computational Biology 17 (12): 1–22. https://doi.org/10.1371/journal.pcbi.1009689.

+
+
+

Stapor, Paul, Leonard Schmiester, Christoph Wierling, Simon Merkt, Dilan Pathirana, Bodo M. H. Lange, Daniel Weindl, and Jan Hasenauer. 2022. “Mini-batch optimization enables training of ODE models on large-scale datasets.” Nature Communications 13 (1): 34. https://doi.org/10.1038/s41467-021-27374-6.

+
+

2021

+
+

Adlung, Lorenz, Paul Stapor, Christian Tönsing, Leonard Schmiester, Luisa E. Schwarzmüller, Lena Postawa, Dantong Wang, et al. 2021. “Cell-to-Cell Variability in Jak2/Stat5 Pathway Components and Cytoplasmic Volumes Defines Survival Threshold in Erythroid Progenitor Cells.” Cell Reports 36 (6): 109507. https://doi.org/https://doi.org/10.1016/j.celrep.2021.109507.

+

Bast, Lisa, Michèle C. Buck, Judith S. Hecker, Robert A. J. Oostendorp, Katharina S. Götze, and Carsten Marr. 2021. “Computational Modeling of Stem and Progenitor Cell Kinetics Identifies Plausible Hematopoietic Lineage Hierarchies.” iScience 24 (2): 102120. https://doi.org/https://doi.org/10.1016/j.isci.2021.102120.

@@ -49,7 +61,7 @@ If you applied AMICI in your work and your publication is missing, please let us

van Rosmalen, R. P., R. W. Smith, V. A. P. Martins dos Santos, C. Fleck, and M. Suarez-Diez. 2021. “Model Reduction of Genome-Scale Metabolic Models as a Basis for Targeted Kinetic Models.” Metabolic Engineering 64: 74–84. https://doi.org/https://doi.org/10.1016/j.ymben.2021.01.008.

-

Villaverde, Alejandro F., Dilan Pathirana, Fabian Fröhlich, Jan Hasenauer, and Julio R. Banga. 2021. “A Protocol for Dynamic Model Calibration.” http://arxiv.org/abs/2105.12008.

+

Villaverde, Alejandro F, Dilan Pathirana, Fabian Fröhlich, Jan Hasenauer, and Julio R Banga. 2021. “A protocol for dynamic model calibration.” Briefings in Bioinformatics, October. https://doi.org/10.1093/bib/bbab387.

2020

@@ -69,17 +81,14 @@ If you applied AMICI in your work and your publication is missing, please let us

Maier, Corinna, Niklas Hartung, Charlotte Kloft, Wilhelm Huisinga, and Jana de Wiljes. 2020. “Reinforcement Learning and Bayesian Data Assimilation for Model-Informed Precision Dosing in Oncology.” http://arxiv.org/abs/2006.01061.

-
-

Schälte, Yannik, and Jan Hasenauer. 2020. “Efficient Exact Inference for Dynamical Systems with Noisy Measurements Using Sequential Approximate Bayesian Computation.” bioRxiv. https://doi.org/10.1101/2020.01.30.927004.

+
+

Schälte, Yannik, and Jan Hasenauer. 2020. “Efficient exact inference for dynamical systems with noisy measurements using sequential approximate Bayesian computation.” Bioinformatics 36 (July): i551–i559. https://doi.org/10.1093/bioinformatics/btaa397.

Schmiester, Leonard, Daniel Weindl, and Jan Hasenauer. 2020. “Parameterization of Mechanistic Models from Qualitative Data Using an Efficient Optimal Scaling Approach.” Journal of Mathematical Biology, July. https://doi.org/10.1007/s00285-020-01522-w.

-
-

Schmucker, Robin, Gabriele Farina, James Faeder, Fabian Fröhlich, Ali Sinan Saglam, and Tuomas Sandholm. 2020. “Combination Treatment Optimization Using a Pan-Cancer Pathway Model.” bioRxiv. https://doi.org/10.1101/2020.07.05.184960.

-
-
-

Schuh, Lea, Carolin Loos, Daniil Pokrovsky, Axel Imhof, Ralph Rupp, and Carsten Marr. 2020. “Computational Modeling Reveals Cell-Cycle Dependent Kinetics of H4k20 Methylation States During Xenopus Embryogenesis.” bioRxiv. https://doi.org/10.1101/2020.05.28.110684.

+
+

Schuh, Lea, Carolin Loos, Daniil Pokrovsky, Axel Imhof, Ralph A. W. Rupp, and Carsten Marr. 2020. “H4K20 Methylation Is Differently Regulated by Dilution and Demethylation in Proliferating and Cell-Cycle-Arrested Xenopus Embryos.” Cell Systems 11 (6): 653–662.e8. https://doi.org/10.1016/j.cels.2020.11.003.

Sten, Sebastian. 2020. “Mathematical Modeling of Neurovascular Coupling.” Linköping University Medical Dissertations. PhD thesis, Linköping UniversityLinköping UniversityLinköping University, Division of Diagnostics; Specialist Medicine, Faculty of Medicine; Health Sciences, Center for Medical Image Science; Visualization (CMIV); Linköping University, Division of Diagnostics; Specialist Medicine. https://doi.org/10.3384/diss.diva-167806.

@@ -93,9 +102,6 @@ If you applied AMICI in your work and your publication is missing, please let us

2019

-
-

Adlung, Lorenz, Paul Stapor, Christian Tönsing, Leonard Schmiester, Luisa E. Schwarzmüller, Dantong Wang, Jens Timmer, Ursula Klingmüller, Jan Hasenauer, and Marcel Schilling. 2019. “Cell-to-Cell Variability in Jak2/Stat5 Pathway Components and Cytoplasmic Volumes Define Survival Threshold in Erythroid Progenitor Cells.” bioRxiv. https://doi.org/10.1101/866871.

-

Dharmarajan, Lekshmi, Hans-Michael Kaltenbach, Fabian Rudolf, and Joerg Stelling. 2019. “A Simple and Flexible Computational Framework for Inferring Sources of Heterogeneity from Single-Cell Dynamics.” Cell Systems 8 (1): 15–26.e11. https://doi.org/10.1016/j.cels.2018.12.007.

@@ -120,9 +126,6 @@ If you applied AMICI in your work and your publication is missing, please let us

Schmiester, Leonard, Yannik Schälte, Fabian Fröhlich, Jan Hasenauer, and Daniel Weindl. 2019. “Efficient parameterization of large-scale dynamic models based on relative measurements.” Bioinformatics, July. https://doi.org/10.1093/bioinformatics/btz581.

-
-

Stapor, Paul, Leonard Schmiester, Christoph Wierling, Bodo Lange, Daniel Weindl, and Jan Hasenauer. 2019. “Mini-Batch Optimization Enables Training of Ode Models on Large-Scale Datasets.” bioRxiv. https://doi.org/10.1101/859884.

-

Terje Lines, Glenn, Łukasz Paszkowski, Leonard Schmiester, Daniel Weindl, Paul Stapor, and Jan Hasenauer. 2019. “Efficient Computation of Steady States in Large-Scale Ode Models of Biochemical Reaction Networks.” IFAC-PapersOnLine 52 (26): 32–37. https://doi.org/10.1016/j.ifacol.2019.12.232.

diff --git a/documentation/rtd_requirements.txt b/documentation/rtd_requirements.txt index a97d743172..fcb9061795 100644 --- a/documentation/rtd_requirements.txt +++ b/documentation/rtd_requirements.txt @@ -8,7 +8,7 @@ nbsphinx>=0.8.7 recommonmark>=0.6.0 sphinx_rtd_theme>=1.0.0 petab>=0.1.20 -sphinx-autodoc-typehints>=1.10.3 +sphinx-autodoc-typehints==1.13.0 git+https://github.com/readthedocs/sphinx-hoverxref@master ipython>=7.28.0 breathe==4.31.0 diff --git a/include/amici/edata.h b/include/amici/edata.h index 1ed10896d0..8c1e821aea 100644 --- a/include/amici/edata.h +++ b/include/amici/edata.h @@ -385,6 +385,11 @@ class ExpData : public SimulationParameters { */ const realtype *getObservedEventsStdDevPtr(int ie) const; + /** + * @brief Arbitrary (not necessarily unique) identifier. + */ + std::string id; + protected: /** * @brief resizes observedData, observedDataStdDev, observedEvents and diff --git a/include/amici/hdf5.h b/include/amici/hdf5.h index 9d92d97f98..8ed91da0ec 100644 --- a/include/amici/hdf5.h +++ b/include/amici/hdf5.h @@ -240,6 +240,17 @@ void createAndWriteDouble3DDataset(H5::H5File const &file, gsl::span buffer, hsize_t m, hsize_t n, hsize_t o); +/** + * @brief Read string attribute from HDF5 object. + * @param file HDF5 file + * @param optionsObject Object to read attribute from + * @param attributeName Name of attribute to read + * @return Attribute value + */ +std::string getStringAttribute(H5::H5File const& file, + std::string const& optionsObject, + std::string const& attributeName); + /** * @brief Read scalar native double attribute from HDF5 object. * @param file HDF5 file diff --git a/include/amici/model.h b/include/amici/model.h index 1de282d206..8cb1e3be4a 100644 --- a/include/amici/model.h +++ b/include/amici/model.h @@ -642,7 +642,7 @@ class Model : public AbstractModel, public ModelDimensions { throw AmiException("Mismatch in conservation law sensitivity size"); state_ = state; }; - + /** * @brief Sets the estimated lower boundary for sigma_y. When :meth:`setAddSigmaResiduals` is * activated, this lower boundary must ensure that log(sigma) + min_sigma > 0. @@ -651,7 +651,7 @@ class Model : public AbstractModel, public ModelDimensions { void setMinimumSigmaResiduals(double min_sigma) { min_sigma_ = min_sigma; } - + /** * @brief Gets the specified estimated lower boundary for sigma_y. * @return lower boundary @@ -659,7 +659,7 @@ class Model : public AbstractModel, public ModelDimensions { realtype getMinimumSigmaResiduals() const { return min_sigma_; } - + /** * @brief Specifies whether residuals should be added to account for parameter dependent sigma. * @@ -673,7 +673,7 @@ class Model : public AbstractModel, public ModelDimensions { void setAddSigmaResiduals(bool sigma_res) { sigma_res_ = sigma_res; } - + /** * @brief Checks whether residuals should be added to account for parameter dependent sigma. * @return sigma_res @@ -802,7 +802,7 @@ class Model : public AbstractModel, public ModelDimensions { */ void getObservable(gsl::span y, const realtype t, const AmiVector &x); - + /** * @brief Get scaling type for observable * @param iy observable index @@ -1750,10 +1750,10 @@ class Model : public AbstractModel, public ModelDimensions { * checked for finiteness */ bool always_check_finite_ {false}; - + /** indicates whether sigma residuals are to be added for every datapoint */ bool sigma_res_ {false}; - + /** offset to ensure positivity of sigma residuals, only has an effect when `sigma_res_` is `true` */ realtype min_sigma_ {50.0}; diff --git a/include/amici/rdata.h b/include/amici/rdata.h index ec8fe146b1..d83c775b6a 100644 --- a/include/amici/rdata.h +++ b/include/amici/rdata.h @@ -92,6 +92,10 @@ class ReturnData: public ModelDimensions { SteadystateProblem const *posteq, Model &model, Solver const &solver, ExpData const *edata); + /** + * @brief Arbitrary (not necessarily unique) identifier. + */ + std::string id; /** * timepoints (shape `nt`) @@ -375,15 +379,15 @@ class ReturnData: public ModelDimensions { template friend void boost::serialization::serialize(Archive &ar, ReturnData &r, unsigned int version); - + /** boolean indicating whether residuals for standard deviations have been added */ bool sigma_res; protected: - + /** offset for sigma_residuals */ realtype sigma_offset; - + /** timepoint for model evaluation*/ realtype t_; diff --git a/include/amici/serialization.h b/include/amici/serialization.h index 6539bc36ca..b62f0a4ffa 100644 --- a/include/amici/serialization.h +++ b/include/amici/serialization.h @@ -170,6 +170,7 @@ void serialize(Archive &ar, amici::SimulationParameters &s, const unsigned int / template void serialize(Archive &ar, amici::ReturnData &r, const unsigned int /*version*/) { ar &dynamic_cast(r); + ar &r.id; ar &r.nx; ar &r.nxtrue; ar &r.nplist; diff --git a/include/amici/sundials_matrix_wrapper.h b/include/amici/sundials_matrix_wrapper.h index c6cbaca587..b94667e39e 100644 --- a/include/amici/sundials_matrix_wrapper.h +++ b/include/amici/sundials_matrix_wrapper.h @@ -8,6 +8,7 @@ #include #include +#include #include diff --git a/include/amici/symbolic_functions.h b/include/amici/symbolic_functions.h index a4bf83e622..3cacc823be 100644 --- a/include/amici/symbolic_functions.h +++ b/include/amici/symbolic_functions.h @@ -3,32 +3,234 @@ namespace amici { +/** + * C implementation of log function, this prevents returning NaN values for + * negative values + * + * @param x argument + * @return if(x>0) then log(x) else -Inf + * + */ double log(double x); + +/** + * C implementation of matlab function dirac + * + * @param x argument + * @return if(x==0) then INF else 0 + * + */ double dirac(double x); double heaviside(double x, double x0); +/** + * c implementation of matlab function min + * + * @param a value1 + * @param b value2 + * @param c bogus parameter to ensure correct parsing as a function + * @return if(a < b) then a else b + * + */ double min(double a, double b, double c); + +/** + * parameter derivative of c implementation of matlab function max + * + * @param id argument index for differentiation + * @param a value1 + * @param b value2 + * @param c bogus parameter to ensure correct parsing as a function + * @return id == 1: if(a > b) then 1 else 0 + * @return id == 2: if(a > b) then 0 else 1 + * + */ double Dmin(int id, double a, double b, double c); + +/** + * c implementation of matlab function max + * + * @param a value1 + * @param b value2 + * @return if(a > b) then a else b + * + */ double max(double a, double b, double c); + +/** + * parameter derivative of c implementation of matlab function max + * + * @param id argument index for differentiation + * @param a value1 + * @param b value2 + * @return id == 1: if(a > b) then 1 else 0 + * @return id == 2: if(a > b) then 0 else 1 + * + */ double Dmax(int id, double a, double b, double c); +/** + * specialized pow functions that assumes positivity of the first argument + * + * @param base base + * @param exponent exponent + * @return pow(max(base,0.0),exponen) + * + */ double pos_pow(double base, double exponent); - + +/** + * c++ interface to the isNaN function + * + * @param what argument + * @return isnan(what) + * + */ int isNaN(double what); + +/** + * c++ interface to the isinf function + * + * @param what argument + * @return isnan(what) + * + */ int isInf(double what); + +/** + * function returning nan + * + * @return NaN + * + */ double getNaN(); -/* sign */ +/** + * c implementation of matlab function sign + * + * @param x argument + * @return 0 + * + */ double sign(double x); -/* splines */ + +/* legacy spline implementation in C (MATLAB only) */ + +/** + * @brief Spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments must be of type + * double. + * + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return spline(t) + * + */ double spline(double t, int num, ...); + +/** + * @brief Exponentiated spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments must be of type + * double. + * + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return spline(t) + * + */ double spline_pos(double t, int num, ...); + +/** + * @brief Derivation of a spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments but id must be of + * type double. + * + * @param id index of node to which the derivative of the corresponding spline + * coefficient should be computed + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return dsplinedp(t) + * + */ double Dspline(int id, double t, int num, ...); + +/** + * @brief Derivation of an exponentiated spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments but id must be of + * type double. + * + * @param id index of node to which the derivative of the corresponding spline + * coefficient should be computed + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return dsplinedp(t) + * + */ double Dspline_pos(int id, double t, int num, ...); + +/** + * @brief Second derivation of a spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments but id1 and id2 + * must be of type double. + * + * @param id1 index of node to which the first derivative of the corresponding + * spline coefficient should be computed + * @param id2 index of node to which the second derivative of the corresponding + * spline coefficient should be computed + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return ddspline(t) + */ double DDspline(int id1, int id2, double t, int num, ...); + +/** + * @brief Derivation of an exponentiated spline function + * + * Takes variable argument pairs (ti,pi) with `ti`: location of node i and + * `pi`: spline value at node i. the last two arguments are always `ss`: flag + * indicating whether slope at first node should be user defined + * and `dudt` user defined slope at first node. All arguments but id1 and id2 + * must be of type double. + * + * @param id1 index of node to which the first derivative of the corresponding + * spline coefficient should be computed + * @param id2 index of node to which the second derivative of the corresponding + * spline coefficient should be computed + * @param t point at which the spline should be evaluated + * @param num number of spline nodes + * + * @return ddspline(t) + * + */ double DDspline_pos(int id1, int id2, double t, int num, ...); + } // namespace amici #endif /* amici_symbolic_functions_h */ diff --git a/python/amici/__init__.py b/python/amici/__init__.py index af4b7376d0..40d6966420 100644 --- a/python/amici/__init__.py +++ b/python/amici/__init__.py @@ -127,13 +127,7 @@ def _capture_cstdout(): # These module require the swig interface and other dependencies from .numpy import ReturnDataView, ExpDataView - from .pandas import ( - getEdataFromDataFrame, - getDataObservablesAsDataFrame, - getSimulationObservablesAsDataFrame, - getSimulationStatesAsDataFrame, - getResidualsAsDataFrame - ) + from .pandas import * # These modules don't require the swig interface from .sbml_import import SbmlImporter, assignmentRules2observables @@ -144,7 +138,8 @@ def _capture_cstdout(): from typing import Protocol class ModelModule(Protocol): - """Enable Python static type checking for AMICI-generated model modules""" + """Enable Python static type checking for AMICI-generated model + modules""" def getModel(self) -> amici.Model: pass except ImportError: diff --git a/python/amici/cxxcodeprinter.py b/python/amici/cxxcodeprinter.py new file mode 100644 index 0000000000..5411010270 --- /dev/null +++ b/python/amici/cxxcodeprinter.py @@ -0,0 +1,214 @@ +"""C++ code generation""" +import re +from typing import List, Optional, Tuple, Dict + +import sympy as sp +from sympy.printing.cxx import CXX11CodePrinter + + +class AmiciCxxCodePrinter(CXX11CodePrinter): + """C++ code printer""" + + def __init__(self): + super().__init__() + + def doprint(self, expr: sp.Expr, assign_to: Optional[str] = None) -> str: + try: + code = super().doprint(expr, assign_to) + code = re.sub(r'(^|\W)M_PI(\W|$)', r'\1amici::pi\2', code) + + return code + except TypeError as e: + raise ValueError( + f'Encountered unsupported function in expression "{expr}": ' + f'{e}!' + ) + + def _get_sym_lines_array( + self, + equations: sp.Matrix, + variable: str, + indent_level: int + ) -> List[str]: + """ + Generate C++ code for assigning symbolic terms in symbols to C++ array + `variable`. + + :param equations: + vectors of symbolic expressions + + :param variable: + name of the C++ array to assign to + + :param indent_level: + indentation level (number of leading blanks) + + :return: + C++ code as list of lines + """ + return [ + ' ' * indent_level + f'{variable}[{index}] = ' + f'{self.doprint(math)};' + for index, math in enumerate(equations) + if math not in [0, 0.0] + ] + + def _get_sym_lines_symbols( + self, symbols: sp.Matrix, + equations: sp.Matrix, + variable: str, + indent_level: int + ) -> List[str]: + """ + Generate C++ code for where array elements are directly replaced with + their corresponding macro symbol + + :param symbols: + vectors of symbols that equations are assigned to + + :param equations: + vectors of expressions + + :param variable: + name of the C++ array to assign to, only used in comments + + :param indent_level: + indentation level (number of leading blanks) + + :return: + C++ code as list of lines + """ + return [ + f'{" " * indent_level}{sym} = {self.doprint(math)};' + f' // {variable}[{index}]'.replace('\n', + '\n' + ' ' * indent_level) + for index, (sym, math) in enumerate(zip(symbols, equations)) + if math not in [0, 0.0] + ] + + def csc_matrix( + self, + matrix: sp.Matrix, + rownames: List[sp.Symbol], + colnames: List[sp.Symbol], + identifier: Optional[int] = 0, + pattern_only: Optional[bool] = False + ) -> Tuple[ + List[int], List[int], sp.Matrix, List[str], sp.Matrix + ]: + """ + Generates the sparse symbolic identifiers, symbolic identifiers, + sparse matrix, column pointers and row values for a symbolic + variable + + :param matrix: + dense matrix to be sparsified + + :param rownames: + ids of the variable of which the derivative is computed (assuming + matrix is the jacobian) + + :param colnames: + ids of the variable with respect to which the derivative is computed + (assuming matrix is the jacobian) + + :param identifier: + additional identifier that gets appended to symbol names to + ensure their uniqueness in outer loops + + :param pattern_only: + flag for computing sparsity pattern without whole matrix + + :return: + symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, + sparse_matrix + + """ + idx = 0 + + nrows, ncols = matrix.shape + + if not pattern_only: + sparse_matrix = sp.zeros(nrows, ncols) + symbol_list = [] + sparse_list = [] + symbol_col_ptrs = [] + symbol_row_vals = [] + + for col in range(ncols): + symbol_col_ptrs.append(idx) + for row in range(nrows): + if matrix[row, col] == 0: + continue + + symbol_row_vals.append(row) + idx += 1 + symbol_name = f'd{self.doprint(rownames[row])}' \ + f'_d{self.doprint(colnames[col])}' + if identifier: + symbol_name += f'_{identifier}' + symbol_list.append(symbol_name) + if pattern_only: + continue + + sparse_matrix[row, col] = sp.Symbol(symbol_name, real=True) + sparse_list.append(matrix[row, col]) + + if idx == 0: + symbol_col_ptrs = [] # avoid bad memory access for empty matrices + else: + symbol_col_ptrs.append(idx) + + if pattern_only: + sparse_matrix = None + else: + sparse_list = sp.Matrix(sparse_list) + + return symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, \ + sparse_matrix + + +def get_switch_statement(condition: str, cases: Dict[int, List[str]], + indentation_level: Optional[int] = 0, + indentation_step: Optional[str] = ' ' * 4): + """ + Generate code for switch statement + + :param condition: + Condition for switch + + :param cases: + Cases as dict with expressions as keys and statement as + list of strings + + :param indentation_level: + indentation level + + :param indentation_step: + indentation whitespace per level + + :return: + Code for switch expression as list of strings + + """ + lines = [] + + if not cases: + return lines + + for expression, statements in cases.items(): + if statements: + lines.append((indentation_level + 1) * indentation_step + + f'case {expression}:') + for statement in statements: + lines.append((indentation_level + 2) * indentation_step + + statement) + lines.append((indentation_level + 2) * indentation_step + 'break;') + + if lines: + lines.insert(0, indentation_level * indentation_step + + f'switch({condition}) {{') + lines.append(indentation_level * indentation_step + '}') + + return lines + diff --git a/python/amici/gradient_check.py b/python/amici/gradient_check.py index e703d9a69a..b4225a7ea7 100644 --- a/python/amici/gradient_check.py +++ b/python/amici/gradient_check.py @@ -14,20 +14,17 @@ from typing import Callable, Optional, List, Sequence -def assert_fun(x): - assert x - - -def check_finite_difference(x0: Sequence[float], - model: Model, - solver: Solver, - edata: ExpData, - ip: int, - fields: List[str], - assert_fun: Callable, - atol: Optional[float] = 1e-4, - rtol: Optional[float] = 1e-4, - epsilon: Optional[float] = 1e-3) -> None: +def check_finite_difference( + x0: Sequence[float], + model: Model, + solver: Solver, + edata: ExpData, + ip: int, + fields: List[str], + atol: Optional[float] = 1e-4, + rtol: Optional[float] = 1e-4, + epsilon: Optional[float] = 1e-3 +) -> None: """ Checks the computed sensitivity based derivatives against a finite difference approximation. @@ -50,10 +47,6 @@ def check_finite_difference(x0: Sequence[float], :param fields: rdata fields for which to check the gradient - :param assert_fun: - function that asserts the return values of comparison, enables - passing of custom assert function from testing frameworks - :param atol: absolute tolerance for comparison @@ -83,7 +76,8 @@ def check_finite_difference(x0: Sequence[float], if int(og_sensitivity_order) < int(SensitivityOrder.first): solver.setSensitivityOrder(SensitivityOrder.first) rdata = runAmiciSimulation(model, solver, edata) - assert_fun(rdata['status'] == AMICI_SUCCESS) + if rdata['status'] != AMICI_SUCCESS: + raise AssertionError(f"Simulation failed (status {rdata['status']}") # finite difference solver.setSensitivityOrder(SensitivityOrder.none) @@ -101,16 +95,18 @@ def check_finite_difference(x0: Sequence[float], # forward: model.setParameters(pf) rdataf = runAmiciSimulation(model, solver, edata) - assert_fun(rdataf['status'] == AMICI_SUCCESS) + if rdataf['status'] != AMICI_SUCCESS: + raise AssertionError(f"Simulation failed (status {rdataf['status']}") # backward: model.setParameters(pb) rdatab = runAmiciSimulation(model, solver, edata) - assert_fun(rdatab['status'] == AMICI_SUCCESS) + if rdatab['status'] != AMICI_SUCCESS: + raise AssertionError(f"Simulation failed (status {rdatab['status']}") for field in fields: sensi_raw = rdata[f's{field}'] - fd = (rdataf[field]-rdatab[field])/(pf[ip] - pb[ip]) + fd = (rdataf[field] - rdatab[field]) / (pf[ip] - pb[ip]) if len(sensi_raw.shape) == 1: sensi = sensi_raw[0] elif len(sensi_raw.shape) == 2: @@ -118,10 +114,9 @@ def check_finite_difference(x0: Sequence[float], elif len(sensi_raw.shape) == 3: sensi = sensi_raw[:, 0, :] else: - assert_fun(False) # not implemented - return + raise NotImplementedError() - check_close(sensi, fd, assert_fun, atol, rtol, field, ip=ip) + _check_close(sensi, fd, atol=atol, rtol=rtol, field=field, ip=ip) solver.setSensitivityOrder(og_sensitivity_order) model.setParameters(og_parameters) @@ -130,15 +125,16 @@ def check_finite_difference(x0: Sequence[float], edata.plist = og_eplist -def check_derivatives(model: Model, - solver: Solver, - edata: Optional[ExpData] = None, - assert_fun: Optional[Callable] = assert_fun, - atol: Optional[float] = 1e-4, - rtol: Optional[float] = 1e-4, - epsilon: Optional[float] = 1e-3, - check_least_squares: bool = True, - skip_zero_pars: bool = False) -> None: +def check_derivatives( + model: Model, + solver: Solver, + edata: Optional[ExpData] = None, + atol: Optional[float] = 1e-4, + rtol: Optional[float] = 1e-4, + epsilon: Optional[float] = 1e-3, + check_least_squares: bool = True, + skip_zero_pars: bool = False +) -> None: """ Finite differences check for likelihood gradient. @@ -151,10 +147,6 @@ def check_derivatives(model: Model, :param edata: exp data - :param assert_fun: - function that asserts the return values of comparison, enables - passing of custom assert function from testing frameworks - :param atol: absolute tolerance for comparison @@ -180,7 +172,8 @@ def check_derivatives(model: Model, rdata = runAmiciSimulation(model, solver, edata) solver.setSensitivityOrder(og_sens_order) - assert_fun(rdata['status'] == AMICI_SUCCESS) + if rdata['status'] != AMICI_SUCCESS: + raise AssertionError(f"Simulation failed (status {rdata['status']}") fields = [] @@ -200,14 +193,10 @@ def check_derivatives(model: Model, if check_least_squares and leastsquares_applicable: fields += ['res', 'y'] - check_results(rdata, 'FIM', - np.dot(rdata['sres'].T, rdata['sres']), - assert_fun, - 1e-8, 1e-4) - check_results(rdata, 'sllh', - -np.dot(rdata['res'].T, rdata['sres']), - assert_fun, - 1e-8, 1e-4) + _check_results(rdata, 'FIM', np.dot(rdata['sres'].T, rdata['sres']), + atol=1e-8, rtol=1e-4) + _check_results(rdata, 'sllh', -np.dot(rdata['res'].T, rdata['sres']), + atol=1e-8, rtol=1e-4) if edata is not None: fields.append('llh') @@ -216,17 +205,18 @@ def check_derivatives(model: Model, if pval == 0.0 and skip_zero_pars: continue check_finite_difference(p, model, solver, edata, ip, fields, - assert_fun, atol=atol, rtol=rtol, - epsilon=epsilon) - - -def check_close(result: np.array, - expected: np.array, - assert_fun: Callable, - atol: float, - rtol: float, - field: str, - ip: Optional[int] = None) -> None: + atol=atol, rtol=rtol, epsilon=epsilon) + + +def _check_close( + result: np.array, + expected: np.array, + atol: float, + rtol: float, + field: str, + ip: Optional[int] = None, + verbose: Optional[bool] = True, +) -> None: """ Compares computed values against expected values and provides rich output information. @@ -240,10 +230,6 @@ def check_close(result: np.array, :param field: rdata field for which the gradient is checked, only for error reporting - :param assert_fun: - function that asserts the return values of comparison, enables - passing of custom assert function from testing frameworks - :param atol: absolute tolerance for comparison @@ -251,33 +237,43 @@ def check_close(result: np.array, relative tolerance for comparison :param ip: - parameter index + parameter index, for more informative output + :param verbose: + produce a more verbose error message in case of unmatched expectations """ close = np.isclose(result, expected, atol=atol, rtol=rtol, equal_nan=True) + if close.all(): + return - if not close.all(): - if ip is None: - index_str = '' - check_type = 'Regression check' - else: - index_str = f'at index ip={ip} ' - check_type = 'FD check' - print(f'{check_type} failed for {field} {index_str}for ' - f'{close.size - close.sum()} indices:') - adev = np.abs(result - expected) - rdev = np.abs((result - expected)/(expected + atol)) - print(f'max(adev): {adev.max()}, max(rdev): {rdev.max()}') - - assert_fun(close.all()) - - -def check_results(rdata: ReturnData, - field: str, - expected: np.array, - assert_fun: Callable, - atol: float, - rtol: float) -> None: + if ip is None: + index_str = '' + check_type = 'Regression check' + else: + index_str = f'at index ip={ip} ' + check_type = 'FD check' + + lines = [f'{check_type} failed for {field} {index_str}for ' + f'{close.size - close.sum()} indices:'] + if verbose: + for idx in np.argwhere(~close): + idx = tuple(idx) + lines.append( + f"\tat {idx}: Expected {expected[idx]}, got {result[idx]}") + adev = np.abs(result - expected) + rdev = np.abs((result - expected) / (expected + atol)) + lines.append(f'max(adev): {adev.max()}, max(rdev): {rdev.max()}') + + raise AssertionError("\n".join(lines)) + + +def _check_results( + rdata: ReturnData, + field: str, + expected: np.array, + atol: float, + rtol: float + ) -> None: """ Checks whether rdata[field] agrees with expected according to provided tolerances. @@ -292,10 +288,6 @@ def check_results(rdata: ReturnData, :param expected: expected values - :param assert_fun: - function that asserts the return values of comparison, enables - passing of custom assert function from testing frameworks - :param atol: absolute tolerance for comparison @@ -307,4 +299,5 @@ def check_results(rdata: ReturnData, if type(result) is float: result = np.array(result) - check_close(result, expected, assert_fun, atol, rtol, field) + _check_close(result=result, expected=expected, + atol=atol, rtol=rtol, field=field) diff --git a/python/amici/numpy.py b/python/amici/numpy.py index 5d8fd51d0e..a2c593df9c 100644 --- a/python/amici/numpy.py +++ b/python/amici/numpy.py @@ -48,6 +48,9 @@ def __getitem__(self, item: str) -> Union[np.ndarray, float]: if item in self._cache: return self._cache[item] + if item == 'id': + return getattr(self._swigptr, item) + if item not in self._field_names: self.__missing__(item) diff --git a/python/amici/ode_export.py b/python/amici/ode_export.py index 1cc598ffe6..f48c778c24 100644 --- a/python/amici/ode_export.py +++ b/python/amici/ode_export.py @@ -30,14 +30,13 @@ Callable, Optional, Union, List, Dict, Tuple, SupportsFloat, Sequence, Set, Any ) +from dataclasses import dataclass from string import Template -from sympy.printing import cxxcode -from sympy.printing.cxx import _CXXCodePrinterBase from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.matrices.dense import MutableDenseMatrix from sympy.logic.boolalg import BooleanAtom from itertools import chain - +from .cxxcodeprinter import AmiciCxxCodePrinter, get_switch_statement from . import ( amiciSwigPath, amiciSrcPath, amiciModulePath, __version__, __commit__, @@ -57,261 +56,259 @@ MODEL_CMAKE_TEMPLATE_FILE = os.path.join(amiciSrcPath, 'CMakeLists.template.cmake') + +@dataclass +class _FunctionInfo: + """Information on a model-specific generated C++ function + + :ivar arguments: argument list of the function. input variables should be + ``const``. + :ivar return_type: the return type of the function + :ivar assume_pow_positivity: + identifies the functions on which ``assume_pow_positivity`` will have + an effect when specified during model generation. generally these are + functions that are used for solving the ODE, where negative values may + negatively affect convergence of the integration algorithm + :ivar sparse: + specifies whether the result of this function will be stored in sparse + format. sparse format means that the function will only return an + array of nonzero values and not a full matrix. + :ivar generate_body: + indicates whether a model-specific implementation is to be generated + :ivar body: + the actual function body. will be filled later + """ + arguments: str = '' + return_type: str = 'void' + assume_pow_positivity: bool = False + sparse: bool = False + generate_body: bool = True + body: str = '' + + +# Information on a model-specific generated C++ function # prototype for generated C++ functions, keys are the names of functions -# -# signature: defines the argument part of the function signature, -# input variables -# should have a const flag -# -# assume_pow_positivity: identifies the functions on which -# assume_pow_positivity will have an effect when specified during model -# generation. generally these are functions that are used for solving the -# ODE, where negative values may negatively affect convergence of the -# integration algorithm -# -# sparse: specifies whether the result of this function will be stored in -# sparse format. sparse format means that the function will only return an -# array of nonzero values and not a full matrix. functions = { - 'Jy': { - 'signature': - '(realtype *Jy, const int iy, const realtype *p, ' + 'Jy': + _FunctionInfo( + 'realtype *Jy, const int iy, const realtype *p, ' 'const realtype *k, const realtype *y, const realtype *sigmay, ' - 'const realtype *my)', - }, - 'dJydsigma': { - 'signature': - '(realtype *dJydsigma, const int iy, const realtype *p, ' + 'const realtype *my' + ), + 'dJydsigma': + _FunctionInfo( + 'realtype *dJydsigma, const int iy, const realtype *p, ' 'const realtype *k, const realtype *y, const realtype *sigmay, ' - 'const realtype *my)', - }, - 'dJydy': { - 'signature': - '(realtype *dJydy, const int iy, const realtype *p, ' + 'const realtype *my' + ), + 'dJydy': + _FunctionInfo( + 'realtype *dJydy, const int iy, const realtype *p, ' 'const realtype *k, const realtype *y, ' - 'const realtype *sigmay, const realtype *my)', - 'flags': ['sparse'] - }, - 'root': { - 'signature': - '(realtype *root, const realtype t, const realtype *x, ' - 'const realtype *p, const realtype *k, const realtype *h)' - }, - 'dwdp': { - 'signature': - '(realtype *dwdp, const realtype t, const realtype *x, ' + 'const realtype *sigmay, const realtype *my', + sparse=True + ), + 'root': + _FunctionInfo( + 'realtype *root, const realtype t, const realtype *x, ' + 'const realtype *p, const realtype *k, const realtype *h' + ), + 'dwdp': + _FunctionInfo( + 'realtype *dwdp, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w, const realtype *tcl, const realtype *dtcldp)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dwdx': { - 'signature': - '(realtype *dwdx, const realtype t, const realtype *x, ' + 'const realtype *w, const realtype *tcl, const realtype *dtcldp', + assume_pow_positivity=True, sparse=True + ), + 'dwdx': + _FunctionInfo( + 'realtype *dwdx, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w, const realtype *tcl)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dwdw': { - 'signature': - '(realtype *dwdw, const realtype t, const realtype *x, ' + 'const realtype *w, const realtype *tcl', + assume_pow_positivity=True, sparse=True + ), + 'dwdw': + _FunctionInfo( + 'realtype *dwdw, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w, const realtype *tcl)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dxdotdw': { - 'signature': - '(realtype *dxdotdw, const realtype t, const realtype *x, ' + 'const realtype *w, const realtype *tcl', + assume_pow_positivity=True, sparse=True + ), + 'dxdotdw': + _FunctionInfo( + 'realtype *dxdotdw, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dxdotdx_explicit': { - 'signature': - '(realtype *dxdotdx_explicit, const realtype t, ' + 'const realtype *w', + assume_pow_positivity=True, sparse=True + ), + 'dxdotdx_explicit': + _FunctionInfo( + 'realtype *dxdotdx_explicit, const realtype t, ' 'const realtype *x, const realtype *p, const realtype *k, ' - 'const realtype *h, const realtype *w)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dxdotdp_explicit': { - 'signature': - '(realtype *dxdotdp_explicit, const realtype t, ' + 'const realtype *h, const realtype *w', + assume_pow_positivity=True, sparse=True + ), + 'dxdotdp_explicit': + _FunctionInfo( + 'realtype *dxdotdp_explicit, const realtype t, ' 'const realtype *x, const realtype *p, const realtype *k, ' - 'const realtype *h, const realtype *w)', - 'flags': ['assume_pow_positivity', 'sparse'] - }, - 'dydx': { - 'signature': - '(realtype *dydx, const realtype t, const realtype *x, ' + 'const realtype *h, const realtype *w', + assume_pow_positivity=True, sparse=True + ), + 'dydx': + _FunctionInfo( + 'realtype *dydx, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w, const realtype *dwdx)', - }, - 'dydp': { - 'signature': - '(realtype *dydp, const realtype t, const realtype *x, ' + 'const realtype *w, const realtype *dwdx', + ), + 'dydp': + _FunctionInfo( + 'realtype *dydp, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const int ip, const realtype *w, const realtype *dtcldp)', - }, - 'dsigmaydp': { - 'signature': - '(realtype *dsigmaydp, const realtype t, const realtype *p, ' - 'const realtype *k, const int ip)', - }, - 'sigmay': { - 'signature': - '(realtype *sigmay, const realtype t, const realtype *p, ' - 'const realtype *k)', - }, - 'sroot': { - 'signature': - '(realtype *stau, const realtype t, const realtype *x, ' + 'const int ip, const realtype *w, const realtype *dtcldp', + ), + 'dsigmaydp': + _FunctionInfo( + 'realtype *dsigmaydp, const realtype t, const realtype *p, ' + 'const realtype *k, const int ip', + ), + 'sigmay': + _FunctionInfo( + 'realtype *sigmay, const realtype t, const realtype *p, ' + 'const realtype *k', + ), + 'sroot': + _FunctionInfo( + 'realtype *stau, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *sx, const int ip, const int ie)', - 'flags': ['dont_generate_body'] - }, - 'drootdt': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'drootdt_total': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'drootdp': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'drootdx': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'stau': { - 'signature': - '(realtype *stau, const realtype t, const realtype *x, ' + 'const realtype *sx, const int ip, const int ie', + generate_body=False + ), + 'drootdt': + _FunctionInfo(generate_body=False), + 'drootdt_total': + _FunctionInfo(generate_body=False), + 'drootdp': + _FunctionInfo(generate_body=False), + 'drootdx': + _FunctionInfo(generate_body=False), + 'stau': + _FunctionInfo( + 'realtype *stau, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *sx, const int ip, const int ie)' - }, - 'deltax': { - 'signature': - '(double *deltax, const realtype t, const realtype *x, ' + 'const realtype *sx, const int ip, const int ie' + ), + 'deltax': + _FunctionInfo( + 'double *deltax, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const int ie, const realtype *xdot, const realtype *xdot_old)' - }, - 'ddeltaxdx': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'ddeltaxdt': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'ddeltaxdp': { - 'signature': '()', - 'flags': ['dont_generate_body'] - }, - 'deltasx': { - 'signature': - '(realtype *deltasx, const realtype t, const realtype *x, ' + 'const int ie, const realtype *xdot, const realtype *xdot_old' + ), + 'ddeltaxdx': + _FunctionInfo(generate_body=False), + 'ddeltaxdt': + _FunctionInfo(generate_body=False), + 'ddeltaxdp': + _FunctionInfo(generate_body=False), + 'deltasx': + _FunctionInfo( + 'realtype *deltasx, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' 'const realtype *w, const int ip, const int ie, ' 'const realtype *xdot, const realtype *xdot_old, ' - 'const realtype *sx, const realtype *stau)' - }, - 'w': { - 'signature': - '(realtype *w, const realtype t, const realtype *x, ' + 'const realtype *sx, const realtype *stau' + ), + 'w': + _FunctionInfo( + 'realtype *w, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, ' - 'const realtype *h, const realtype *tcl)', - 'flags': ['assume_pow_positivity'] - }, - 'x0': { - 'signature': - '(realtype *x0, const realtype t, const realtype *p, ' - 'const realtype *k)', - }, - 'x0_fixedParameters': { - 'signature': - '(realtype *x0_fixedParameters, const realtype t, ' + 'const realtype *h, const realtype *tcl', + assume_pow_positivity=True + ), + 'x0': + _FunctionInfo( + 'realtype *x0, const realtype t, const realtype *p, ' + 'const realtype *k' + ), + 'x0_fixedParameters': + _FunctionInfo( + 'realtype *x0_fixedParameters, const realtype t, ' 'const realtype *p, const realtype *k, ' - 'gsl::span reinitialization_state_idxs)', - }, - 'sx0': { - 'signature': - '(realtype *sx0, const realtype t,const realtype *x, ' - 'const realtype *p, const realtype *k, const int ip)', - }, - 'sx0_fixedParameters': { - 'signature': - '(realtype *sx0_fixedParameters, const realtype t, ' + 'gsl::span reinitialization_state_idxs', + ), + 'sx0': + _FunctionInfo( + 'realtype *sx0, const realtype t,const realtype *x, ' + 'const realtype *p, const realtype *k, const int ip', + ), + 'sx0_fixedParameters': + _FunctionInfo( + 'realtype *sx0_fixedParameters, const realtype t, ' 'const realtype *x0, const realtype *p, const realtype *k, ' - 'const int ip, gsl::span reinitialization_state_idxs)', - }, - 'xdot': { - 'signature': - '(realtype *xdot, const realtype t, const realtype *x, ' + 'const int ip, gsl::span reinitialization_state_idxs', + ), + 'xdot': + _FunctionInfo( + 'realtype *xdot, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, const realtype *h, ' - 'const realtype *w)', - 'flags': ['assume_pow_positivity'] - }, - 'xdot_old': { - 'signature': '()', - 'flags': ['dont_generate_body'], - }, - 'y': { - 'signature': - '(realtype *y, const realtype t, const realtype *x, ' + 'const realtype *w', + assume_pow_positivity=True + ), + 'xdot_old': + _FunctionInfo(generate_body=False), + 'y': + _FunctionInfo( + 'realtype *y, const realtype t, const realtype *x, ' 'const realtype *p, const realtype *k, ' - 'const realtype *h, const realtype *w)', - }, - 'x_rdata': { - 'signature': - '(realtype *x_rdata, const realtype *x, const realtype *tcl)', - }, - 'total_cl': { - 'signature': - '(realtype *total_cl, const realtype *x_rdata)', - }, - 'x_solver': { - 'signature': - '(realtype *x_solver, const realtype *x_rdata)', - }, + 'const realtype *h, const realtype *w', + ), + 'x_rdata': + _FunctionInfo( + 'realtype *x_rdata, const realtype *x, const realtype *tcl' + ), + 'total_cl': + _FunctionInfo('realtype *total_cl, const realtype *x_rdata'), + + 'x_solver': + _FunctionInfo('realtype *x_solver, const realtype *x_rdata') } # list of sparse functions sparse_functions = [ - function for function in functions - if 'sparse' in functions[function].get('flags', []) + func_name for func_name, func_info in functions.items() + if func_info.sparse ] # list of nobody functions nobody_functions = [ - function for function in functions - if 'dont_generate_body' in functions[function].get('flags', []) + func_name for func_name, func_info in functions.items() + if not func_info.generate_body ] # list of sensitivity functions sensi_functions = [ - function for function in functions - if 'const int ip' in functions[function]['signature'] + func_name for func_name, func_info in functions.items() + if 'const int ip' in func_info.arguments ] # list of sensitivity functions sparse_sensi_functions = [ - function for function in functions - if 'const int ip' not in functions[function]['signature'] - and function.endswith('dp') or function.endswith('dp_explicit') + func_name for func_name, func_info in functions.items() + if 'const int ip' not in func_info.arguments + and func_name.endswith('dp') or func_name.endswith('dp_explicit') ] # list of event functions event_functions = [ - function for function in functions - if 'const int ie' in functions[function]['signature'] and - 'const int ip' not in functions[function]['signature'] + func_name for func_name, func_info in functions.items() + if 'const int ie' in func_info.arguments and + 'const int ip' not in func_info.arguments ] event_sensi_functions = [ - function for function in functions - if 'const int ie' in functions[function]['signature'] and - 'const int ip' in functions[function]['signature'] + func_name for func_name, func_info in functions.items() + if 'const int ie' in func_info.arguments and + 'const int ip' in func_info.arguments ] # list of multiobs functions multiobs_functions = [ - function for function in functions - if 'const int iy' in functions[function]['signature'] + func_name for func_name, func_info in functions.items() + if 'const int iy' in func_info.arguments ] # list of equations that have ids which may not be unique non_unique_id_symbols = [ @@ -351,8 +348,8 @@ def var_in_function_signature(name: str, varname: str) -> bool: """ return name in functions \ and re.search( - rf'const (realtype|double) \*{varname}[0]*[,)]+', - functions[name]['signature'] + rf'const (realtype|double) \*{varname}[0]*(,|$)+', + functions[name].arguments ) @@ -955,6 +952,9 @@ class ODEModel: :ivar _has_quadratic_nllh: whether all observables have a gaussian noise model, i.e. whether res and FIM make sense. + + :ivar _code_printer: + Code printer to generate C++ code """ def __init__(self, verbose: Optional[Union[bool, int]] = False, @@ -1041,10 +1041,16 @@ def __init__(self, verbose: Optional[Union[bool, int]] = False, self._has_quadratic_nllh: bool = True set_log_level(logger, verbose) + self._code_printer = AmiciCxxCodePrinter() + for fun in CUSTOM_FUNCTIONS: + self._code_printer.known_functions[fun['sympy']] = fun['c++'] + @log_execution_time('importing SbmlImporter', logger) - def import_from_sbml_importer(self, - si: 'sbml_import.SbmlImporter', - compute_cls: Optional[bool] = True) -> None: + def import_from_sbml_importer( + self, + si: 'sbml_import.SbmlImporter', + compute_cls: Optional[bool] = True + ) -> None: """ Imports a model specification from a :class:`amici.sbml_import.SbmlImporter` @@ -1052,6 +1058,8 @@ def import_from_sbml_importer(self, :param si: imported SBML model + :param compute_cls: + whether to compute conservation laws """ # get symbolic expression from SBML importers @@ -1263,7 +1271,6 @@ def add_conservation_law(self, self._states[ix].set_conservation_law(state_expr) - def get_observable_transformations(self) -> List[ObservableTransformation]: """ List of observable transformations @@ -1273,7 +1280,6 @@ def get_observable_transformations(self) -> List[ObservableTransformation]: """ return [obs.trafo for obs in self._observables] - def num_states_rdata(self) -> int: """ Number of states. @@ -1311,7 +1317,7 @@ def num_state_reinits(self) -> int: """ reinit_states = self.eq('x0_fixedParameters') solver_states = self.eq('x_solver') - return sum([1 for ix in reinit_states if ix in solver_states]) + return sum(ix in solver_states for ix in reinit_states) def num_obs(self) -> int: """ @@ -1502,7 +1508,6 @@ def name(self, name: str) -> List[str]: :return: list of names - """ if name not in self._names: self._generate_name(name) @@ -1697,10 +1702,9 @@ def _generate_sparse_symbol(self, name: str) -> None: self._syms[name] = [] for iy in range(self.num_obs()): symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, \ - sparse_matrix = csc_matrix(matrix[iy, :], - rownames=rownames, - colnames=colnames, - identifier=iy) + sparse_matrix = self._code_printer.csc_matrix( + matrix[iy, :], rownames=rownames, colnames=colnames, + identifier=iy) self._colptrs[name].append(symbol_col_ptrs) self._rowvals[name].append(symbol_row_vals) self._sparseeqs[name].append(sparse_list) @@ -1708,7 +1712,7 @@ def _generate_sparse_symbol(self, name: str) -> None: self._syms[name].append(sparse_matrix) else: symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, \ - sparse_matrix = csc_matrix( + sparse_matrix = self._code_printer.csc_matrix( matrix, rownames=rownames, colnames=colnames, pattern_only=name in nobody_functions ) @@ -1802,7 +1806,7 @@ def _compute_equation(self, name: str) -> None: self._x0_fixedParameters_idx = [ ix for ix, eq in enumerate(self.eq('x0')) - if any([sym in eq.free_symbols for sym in k]) + if any(sym in eq.free_symbols for sym in k) ] eq = self.eq('x0') self._eqs[name] = sp.Matrix([eq[ix] for ix in @@ -1925,7 +1929,7 @@ def _compute_equation(self, name: str) -> None: # Equations are there, but symbols for roots must be added self.sym('h') - if name in ['Jy', 'dydx']: + if name in {'Jy', 'dydx'}: # do not transpose if we compute the partial derivative as part of # a total derivative if not len(self._lock_total_derivative): @@ -1968,25 +1972,24 @@ def _derivative(self, eq: str, var: str, name: str = None) -> None: if not name: name = f'd{eq}d{var}' - # automatically detect chainrule - chainvars = [] ignore_chainrule = { ('xdot', 'p'): 'w', # has generic implementation in c++ code ('xdot', 'x'): 'w', # has generic implementation in c++ code ('w', 'w'): 'tcl', # dtcldw = 0 ('w', 'x'): 'tcl', # dtcldx = 0 } - for cv in ['w', 'tcl']: - if var_in_function_signature(eq, cv) \ - and cv not in self._lock_total_derivative \ - and var is not cv \ - and min(self.sym(cv).shape) \ - and ( - (eq, var) not in ignore_chainrule - or ignore_chainrule[(eq, var)] != cv - ): - chainvars.append(cv) - + # automatically detect chainrule + chainvars = [ + cv for cv in ['w', 'tcl'] + if var_in_function_signature(eq, cv) + and cv not in self._lock_total_derivative + and var is not cv + and min(self.sym(cv).shape) + and ( + (eq, var) not in ignore_chainrule + or ignore_chainrule[(eq, var)] != cv + ) + ] if len(chainvars): self._lock_total_derivative += chainvars self._total_derivative(name, eq, chainvars, var) @@ -1998,11 +2001,7 @@ def _derivative(self, eq: str, var: str, name: str = None) -> None: needs_stripped_symbols = eq == 'xdot' and var != 'x' # partial derivative - if eq == 'Jy': - sym_eq = self.eq(eq).transpose() - else: - sym_eq = self.eq(eq) - + sym_eq = self.eq(eq).transpose() if eq == 'Jy' else self.eq(eq) if pysb is not None and needs_stripped_symbols: needs_stripped_symbols = not any( isinstance(sym, pysb.Component) @@ -2162,18 +2161,14 @@ def _multiplication(self, name: str, x: str, y: str, if sign not in [-1, 1]: raise TypeError(f'sign must be +1 or -1, was {sign}') - variables = dict() - for varname in [x, y]: - if var_in_function_signature(name, varname): - variables[varname] = self.sym(varname) - else: - variables[varname] = self.eq(varname) - - if transpose_x: - xx = variables[x].transpose() - else: - xx = variables[x] + variables = { + varname: self.sym(varname) + if var_in_function_signature(name, varname) + else self.eq(varname) + for varname in [x, y] + } + xx = variables[x].transpose() if transpose_x else variables[x] yy = variables[y] self._eqs[name] = sign * smart_multiply(xx, yy) @@ -2194,12 +2189,10 @@ def _equation_from_component(self, name: str, component: str) -> None: ) def get_conservation_laws(self) -> List[Tuple[sp.Symbol, sp.Basic]]: - """ Returns a list of states with conservation law set - + """Returns a list of states with conservation law set :return: list of state identifiers - """ return [ (state.get_id(), state._conservation_law) @@ -2259,10 +2252,10 @@ def state_has_fixed_parameter_initial_condition(self, ix: int) -> bool: ic = self._states[ix].get_val() if not isinstance(ic, sp.Basic): return False - return any([ + return any( fp in [c.get_id() for c in self._constants] for fp in ic.free_symbols - ]) + ) def state_has_conservation_law(self, ix: int) -> bool: """ @@ -2327,17 +2320,16 @@ def _expr_is_time_dependent(self, expr: sp.Expr) -> bool: # Check if any time-dependent states are in the expression. state_syms = [str(sym) for sym in self._states] - for state in expr_syms.intersection(state_syms): - if not self.state_is_constant(state_syms.index(state)): - return True - - return False + return any( + not self.state_is_constant(state_syms.index(state)) + for state in expr_syms.intersection(state_syms) + ) def _get_unique_root( self, root_found: sp.Expr, roots: List[Event], - ) -> sp.Symbol: + ) -> Union[sp.Symbol, None]: """ Collects roots of Heaviside functions and events and stores them in the roots list. It checks for redundancy to not store symbolically @@ -2449,95 +2441,6 @@ def _process_heavisides( return dxdt -def _print_with_exception(math: sp.Expr) -> str: - """ - Generate C++ code for a symbolic expression - - :param math: - symbolic expression - - :return: - C++ code for the specified expression - """ - # get list of custom replacements - user_functions = {fun['sympy']: fun['c++'] for fun in CUSTOM_FUNCTIONS} - - try: - # Required until https://github.com/sympy/sympy/pull/20558 is released - with _monkeypatched(_CXXCodePrinterBase, '_print_Max', - _custom_print_max),\ - _monkeypatched(_CXXCodePrinterBase, '_print_Min', - _custom_print_min): - ret = cxxcode(math, standard='c++11', - user_functions=user_functions) - ret = re.sub(r'(^|\W)M_PI(\W|$)', r'\1amici::pi\2', ret) - return ret - except TypeError as e: - raise ValueError( - f'Encountered unsupported function in expression "{math}": ' - f'{e}!' - ) - - -def _get_sym_lines_array(equations: sp.Matrix, - variable: str, - indent_level: int) -> List[str]: - """ - Generate C++ code for assigning symbolic terms in symbols to C++ array - `variable`. - - :param equations: - vectors of symbolic expressions - - :param variable: - name of the C++ array to assign to - - :param indent_level: - indentation level (number of leading blanks) - - :return: - C++ code as list of lines - - """ - - return [' ' * indent_level + f'{variable}[{index}] = ' - f'{_print_with_exception(math)};' - for index, math in enumerate(equations) - if not (math == 0 or math == 0.0)] - - -def _get_sym_lines_symbols(symbols: sp.Matrix, - equations: sp.Matrix, - variable: str, - indent_level: int) -> List[str]: - """ - Generate C++ code for where array elements are directly replaced with - their corresponding macro symbol - - :param symbols: - vectors of symbols that equations are assigned to - - :param equations: - vectors of expressions - - :param variable: - name of the C++ array to assign to, only used in comments - - :param indent_level: - indentation level (number of leading blanks) - - :return: - C++ code as list of lines - - """ - - return [f'{" " * indent_level}{sym} = {_print_with_exception(math)};' - f' // {variable}[{index}]'.replace('\n', - '\n' + ' ' * indent_level) - for index, (sym, math) in enumerate(zip(symbols, equations)) - if not (math == 0 or math == 0.0)] - - class ODEExporter: """ The ODEExporter class generates AMICI C++ files for ODE model as @@ -2639,8 +2542,7 @@ def __init__( self.model: ODEModel = ode_model # To only generate a subset of functions, apply subselection here - self.functions: Dict[str, Dict[str, Union[str, List[str]]]] = \ - copy.deepcopy(functions) + self.functions: Dict[str, _FunctionInfo] = copy.deepcopy(functions) self.allow_reinit_fixpar_initcond: bool = allow_reinit_fixpar_initcond self._build_hints = set() @@ -2687,29 +2589,27 @@ def _generate_c_code(self) -> None: """ Create C++ code files for the model based on ODEExporter.model """ - for function in self.functions.keys(): - if function in sensi_functions + sparse_sensi_functions and \ + for func_name, func_info in self.functions.items(): + if func_name in sensi_functions + sparse_sensi_functions and \ not self.generate_sensitivity_code: continue - if 'dont_generate_body' not in \ - self.functions[function].get('flags', []): - dec = log_execution_time(f'writing {function}.cpp', logger) - dec(self._write_function_file)(function) - if function in sparse_functions \ - and 'body' in self.functions[function]: - self._write_function_index(function, 'colptrs') - self._write_function_index(function, 'rowvals') + if func_info.generate_body: + dec = log_execution_time(f'writing {func_name}.cpp', logger) + dec(self._write_function_file)(func_name) + if func_name in sparse_functions and func_info.body: + self._write_function_index(func_name, 'colptrs') + self._write_function_index(func_name, 'rowvals') for name in self.model.sym_names(): # only generate for those that have nontrivial implementation, # check for both basic variables (not in functions) and function # computed values - if (name in self.functions and - 'body' not in self.functions[name] and - name not in nobody_functions) or \ - (name not in self.functions and - len(self.model.sym(name)) == 0): + if (name in self.functions + and not self.functions[name].body + and name not in nobody_functions) \ + or (name not in self.functions and + len(self.model.sym(name)) == 0): continue self._write_index_files(name) @@ -2775,8 +2675,6 @@ def _generate_m_code(self) -> None: """ Create a Matlab script for compiling code files to a mex file """ - # creating the code lines for the Matlab compile script - lines = [] # Events are not yet implemented. Once this is done, the variable nz # will have to be replaced by "self.model.nz()" @@ -2789,24 +2687,22 @@ def _generate_m_code(self) -> None: nytrue = self.model.num_obs() o2flag = 0 - # a preliminary comment - lines.append('% This compile script was automatically created from' - ' Python SBML import.') - lines.append('% If mex compiler is set up within MATLAB, it can be run' - ' from MATLAB ') - lines.append('% in order to compile a mex-file from the Python' - ' generated C++ files.') - lines.append('') - - # write the actual compiling code - lines.append(f"modelName = '{self.model_name}';") - lines.append("amimodel.compileAndLinkModel" - "(modelName, '', [], [], [], []);") - lines.append(f"amimodel.generateMatlabWrapper({nxtrue_rdata}, " - f"{nytrue}, {self.model.num_par()}, " - f"{self.model.num_const()}, {nz}, {o2flag}, ...\n [], " - "['simulate_' modelName '.m'], modelName, ...\n" - " 'lin', 1, 1);") + lines = [ + '% This compile script was automatically created from' + ' Python SBML import.', + '% If mex compiler is set up within MATLAB, it can be run' + ' from MATLAB ', + '% in order to compile a mex-file from the Python' + ' generated C++ files.', + '', + f"modelName = '{self.model_name}';", + "amimodel.compileAndLinkModel(modelName, '', [], [], [], []);", + f"amimodel.generateMatlabWrapper({nxtrue_rdata}, " + f"{nytrue}, {self.model.num_par()}, " + f"{self.model.num_const()}, {nz}, {o2flag}, ...", + " [], ['simulate_' modelName '.m'], modelName, ...", + " 'lin', 1, 1);" + ] # write compile script (for mex) compile_script = os.path.join(self.model_path, 'compileMexFile.m') @@ -2822,27 +2718,24 @@ def _write_index_files(self, name: str) -> None: be written """ - lines = [] - if name in self.model.sym_names(): - if name in sparse_functions: - symbols = self.model.sparsesym(name) - else: - symbols = self.model.sym(name).T - # flatten multiobs - if isinstance(next(iter(symbols), None), list): - symbols = [symbol for obs in symbols for symbol in obs] - else: + if name not in self.model.sym_names(): raise ValueError(f'Unknown symbolic array: {name}') + symbols = self.model.sparsesym(name) if name in sparse_functions \ + else self.model.sym(name).T + + # flatten multiobs + if isinstance(next(iter(symbols), None), list): + symbols = [symbol for obs in symbols for symbol in obs] + + lines = [] for index, symbol in enumerate(symbols): symbol_name = strip_pysb(symbol) if str(symbol) == '0': continue if str(symbol_name) == '': raise ValueError(f'{name} contains a symbol called ""') - lines.append( - f'#define {symbol_name} {name}[{index}]' - ) + lines.append(f'#define {symbol_name} {name}[{index}]') filename = os.path.join(self.model_path, f'{self.model_name}_{name}.h') with open(filename, 'w') as fileout: @@ -2876,21 +2769,20 @@ def _write_function_file(self, function: str) -> None: '', '#include ', '#include ', + '#include ', + '' ] - # function signature - signature = self.functions[function]['signature'] - - lines.append('') + func_info = self.functions[function] # extract symbols that need definitions from signature # don't add includes for files that won't be generated. - # Unfortunately we cannot check for `self.functions[sym]['body']` + # Unfortunately we cannot check for `self.functions[sym].body` # here since it may not have been generated yet. - for match in re.findall( - fr'const (realtype|double) \*([\w]+)[0]*[,\)]+', signature + for sym in re.findall( + r'const (?:realtype|double) \*([\w]+)[0]*(?:,|$)', + func_info.arguments ): - sym = match[1] if sym not in self.model.sym_names(): continue @@ -2916,14 +2808,13 @@ def _write_function_file(self, function: str) -> None: 'namespace amici {', f'namespace model_{self.model_name} {{', '', + f'{func_info.return_type} {function}_{self.model_name}' + f'({func_info.arguments}){{' ]) - lines.append(f'void {function}_{self.model_name}{signature}{{') - # function body body = self._get_function_body(function, equations) - if self.assume_pow_positivity and 'assume_pow_positivity' \ - in self.functions[function].get('flags', []): + if self.assume_pow_positivity and func_info.assume_pow_positivity: body = [re.sub(r'(^|\W)std::pow\(', r'\1amici::pos_pow(', line) for line in body] # execute this twice to catch cases where the ending ( would be the @@ -2931,10 +2822,11 @@ def _write_function_file(self, function: str) -> None: body = [re.sub(r'(^|\W)std::pow\(', r'\1amici::pos_pow(', line) for line in body] - if body: - self.functions[function]['body'] = body - else: + if not body: return + + self.functions[function].body = body + lines += body lines.extend([ '}', @@ -2951,9 +2843,9 @@ def _write_function_file(self, function: str) -> None: lines.insert(0, fun['include']) # if not body is None: - with open(os.path.join( - self.model_path, f'{self.model_name}_{function}.cpp'), 'w' - ) as fileout: + filename = os.path.join(self.model_path, + f'{self.model_name}_{function}.cpp') + with open(filename, 'w') as fileout: fileout.write('\n'.join(lines)) def _write_function_index(self, function: str, indextype: str) -> None: @@ -2966,7 +2858,6 @@ def _write_function_index(self, function: str, indextype: str) -> None: :param indextype: type of index {'colptrs', 'rowvals'} - """ if indextype == 'colptrs': @@ -3013,10 +2904,12 @@ def _write_function_index(self, function: str, indextype: str) -> None: lines.append("}};") else: # single index vector - lines.append("static constexpr std::array {static_array_name} = {{") - lines.append(' ' + ', '.join(map(str, values))) - lines.append("};") + lines.extend([ + "static constexpr std::array {static_array_name} = {{", + ' ' + ', '.join(map(str, values)), + "};" + ]) lines.extend([ '', @@ -3048,9 +2941,11 @@ def _write_function_index(self, function: str, indextype: str) -> None: with open(filename, 'w') as fileout: fileout.write('\n'.join(lines)) - def _get_function_body(self, - function: str, - equations: sp.Matrix) -> List[str]: + def _get_function_body( + self, + function: str, + equations: sp.Matrix + ) -> List[str]: """ Generate C++ code for body of function `function`. @@ -3062,9 +2957,7 @@ def _get_function_body(self, :return: generated C++ code - """ - lines = [] if ( @@ -3077,8 +2970,10 @@ def _get_function_body(self, # dJydy is a list return lines - if not self.allow_reinit_fixpar_initcond \ - and function in ['sx0_fixedParameters', 'x0_fixedParameters']: + if not self.allow_reinit_fixpar_initcond and function in { + 'sx0_fixedParameters', + 'x0_fixedParameters', + }: return lines if function == 'sx0_fixedParameters': @@ -3104,9 +2999,10 @@ def _get_function_body(self, "_x0_fixedParameters_idxs.cend(), idx) != " "_x0_fixedParameters_idxs.cend())\n" " sx0_fixedParameters[idx] = 0.0;", - " }"]) + " }" + ]) - cases = dict() + cases = {} for ipar in range(self.model.num_par()): expressions = [] for index, formula in zip( @@ -3120,7 +3016,7 @@ def _get_function_body(self, f'reinitialization_state_idxs.cend(), {index}) != ' 'reinitialization_state_idxs.cend())', f' {function}[{index}] = ' - f'{_print_with_exception(formula)};' + f'{self.model._code_printer.doprint(formula)};' ]) cases[ipar] = expressions lines.extend(get_switch_statement('ip', cases, 1)) @@ -3135,12 +3031,16 @@ def _get_function_body(self, f'reinitialization_state_idxs.cend(), {index}) != ' 'reinitialization_state_idxs.cend())\n ' f'{function}[{index}] = ' - f'{_print_with_exception(formula)};') + f'{self.model._code_printer.doprint(formula)};' + ) elif function in event_functions: - cases = {ie: _get_sym_lines_array(equations[ie], function, 0) - for ie in range(self.model.num_events()) - if not smart_is_zero_matrix(equations[ie])} + cases = { + ie: self.model._code_printer._get_sym_lines_array( + equations[ie], function, 0) + for ie in range(self.model.num_events()) + if not smart_is_zero_matrix(equations[ie]) + } lines.extend(get_switch_statement('ie', cases, 1)) elif function in event_sensi_functions: @@ -3148,31 +3048,37 @@ def _get_function_body(self, for ie, inner_equations in enumerate(equations): inner_lines = [] inner_cases = { - ipar: _get_sym_lines_array(inner_equations[:, ipar], - function, 0) + ipar: self.model._code_printer._get_sym_lines_array( + inner_equations[:, ipar], function, 0) for ipar in range(self.model.num_par()) - if not smart_is_zero_matrix(inner_equations[:, ipar])} + if not smart_is_zero_matrix(inner_equations[:, ipar]) + } inner_lines.extend(get_switch_statement( 'ip', inner_cases, 0)) outer_cases[ie] = copy.copy(inner_lines) lines.extend(get_switch_statement('ie', outer_cases, 1)) elif function in sensi_functions: - cases = {ipar: _get_sym_lines_array(equations[:, ipar], function, - 0) - for ipar in range(self.model.num_par()) - if not smart_is_zero_matrix(equations[:, ipar])} + cases = { + ipar: self.model._code_printer._get_sym_lines_array( + equations[:, ipar], function, 0) + for ipar in range(self.model.num_par()) + if not smart_is_zero_matrix(equations[:, ipar]) + } lines.extend(get_switch_statement('ip', cases, 1)) elif function in multiobs_functions: if function == 'dJydy': - cases = {iobs: _get_sym_lines_array(equations[iobs], function, - 0) - for iobs in range(self.model.num_obs()) - if not smart_is_zero_matrix(equations[iobs])} + cases = { + iobs: self.model._code_printer._get_sym_lines_array( + equations[iobs], function, 0) + for iobs in range(self.model.num_obs()) + if not smart_is_zero_matrix(equations[iobs]) + } else: cases = { - iobs: _get_sym_lines_array(equations[:, iobs], function, 0) + iobs: self.model._code_printer._get_sym_lines_array( + equations[:, iobs], function, 0) for iobs in range(self.model.num_obs()) if not smart_is_zero_matrix(equations[:, iobs]) } @@ -3184,10 +3090,12 @@ def _get_function_body(self, symbols = self.model.sparsesym(function) else: symbols = self.model.sym(function, stripped=True) - lines += _get_sym_lines_symbols(symbols, equations, function, 4) + lines += self.model._code_printer._get_sym_lines_symbols( + symbols, equations, function, 4) else: - lines += _get_sym_lines_array(equations, function, 4) + lines += self.model._code_printer._get_sym_lines_array( + equations, function, 4) return [line for line in lines if line] @@ -3253,9 +3161,10 @@ def _write_model_header_cpp(self) -> None: 'NK': str(self.model.num_const()), 'O2MODE': 'amici::SecondOrderMode::none', # using cxxcode ensures proper handling of nan/inf - 'PARAMETERS': _print_with_exception(self.model.val('p'))[1:-1], - 'FIXED_PARAMETERS': _print_with_exception(self.model.val('k'))[ - 1:-1], + 'PARAMETERS': self.model._code_printer.doprint( + self.model.val('p'))[1:-1], + 'FIXED_PARAMETERS': self.model._code_printer.doprint( + self.model.val('k'))[1:-1], 'PARAMETER_NAMES_INITIALIZER_LIST': self._get_symbol_name_initializer_list('p'), 'STATE_NAMES_INITIALIZER_LIST': @@ -3293,56 +3202,56 @@ def _write_model_header_cpp(self) -> None: if self.model._has_quadratic_nllh else 'false', } - for fun, fundef in self.functions.items(): - if fun in nobody_functions: + for func_name, func_info in self.functions.items(): + if func_name in nobody_functions: continue - if 'body' not in fundef: - tpl_data[f'{fun.upper()}_DEF'] = '' + if not func_info.body: + tpl_data[f'{func_name.upper()}_DEF'] = '' - if fun in sensi_functions + sparse_sensi_functions and \ + if func_name in sensi_functions + sparse_sensi_functions and \ not self.generate_sensitivity_code: impl = '' else: impl = get_model_override_implementation( - fun, self.model_name, nobody=True + func_name, self.model_name, nobody=True ) - tpl_data[f'{fun.upper()}_IMPL'] = impl + tpl_data[f'{func_name.upper()}_IMPL'] = impl - if fun in sparse_functions: + if func_name in sparse_functions: for indexfield in ['colptrs', 'rowvals']: - if fun in sparse_sensi_functions and \ + if func_name in sparse_sensi_functions and \ not self.generate_sensitivity_code: impl = '' else: impl = get_sunindex_override_implementation( - fun, self.model_name, indexfield, nobody=True + func_name, self.model_name, indexfield, + nobody=True ) - tpl_data[f'{fun.upper()}_{indexfield.upper()}_DEF'] \ + tpl_data[f'{func_name.upper()}_{indexfield.upper()}_DEF'] \ = '' - tpl_data[f'{fun.upper()}_{indexfield.upper()}_IMPL'] \ + tpl_data[f'{func_name.upper()}_{indexfield.upper()}_IMPL'] \ = impl - continue - tpl_data[f'{fun.upper()}_DEF'] = \ - get_function_extern_declaration(fun, self.model_name) - tpl_data[f'{fun.upper()}_IMPL'] = \ - get_model_override_implementation(fun, self.model_name) - if fun in sparse_functions: - tpl_data[f'{fun.upper()}_COLPTRS_DEF'] = \ - get_sunindex_extern_declaration(fun, self.model_name, - 'colptrs') - tpl_data[f'{fun.upper()}_COLPTRS_IMPL'] = \ - get_sunindex_override_implementation(fun, self.model_name, - 'colptrs') - tpl_data[f'{fun.upper()}_ROWVALS_DEF'] = \ - get_sunindex_extern_declaration(fun, self.model_name, - 'rowvals') - tpl_data[f'{fun.upper()}_ROWVALS_IMPL'] = \ - get_sunindex_override_implementation(fun, self.model_name, - 'rowvals') + tpl_data[f'{func_name.upper()}_DEF'] = \ + get_function_extern_declaration(func_name, self.model_name) + tpl_data[f'{func_name.upper()}_IMPL'] = \ + get_model_override_implementation(func_name, self.model_name) + if func_name in sparse_functions: + tpl_data[f'{func_name.upper()}_COLPTRS_DEF'] = \ + get_sunindex_extern_declaration( + func_name, self.model_name, 'colptrs') + tpl_data[f'{func_name.upper()}_COLPTRS_IMPL'] = \ + get_sunindex_override_implementation( + func_name, self.model_name, 'colptrs') + tpl_data[f'{func_name.upper()}_ROWVALS_DEF'] = \ + get_sunindex_extern_declaration( + func_name, self.model_name, 'rowvals') + tpl_data[f'{func_name.upper()}_ROWVALS_IMPL'] = \ + get_sunindex_override_implementation( + func_name, self.model_name, 'rowvals') if self.model.num_states_solver() == self.model.num_states_rdata(): tpl_data['X_RDATA_DEF'] = '' @@ -3461,7 +3370,7 @@ def set_paths(self, output_dir: Optional[str] = None) -> None: relative or absolute path where the generated model code is to be placed. If ``None``, this will default to `amici-{self.model_name}` in the current working directory. - will be created if does not exists. + will be created if it does not exist. """ if output_dir is None: @@ -3493,7 +3402,7 @@ class TemplateAmici(Template): """ Template format used in AMICI (see string.template for more details). - :ivar delimiter: + :cvar delimiter: delimiter that identifies template variables """ @@ -3516,7 +3425,6 @@ def apply_template(source_file: str, :param template_data: template keywords to substitute (key is template variable without :attr:`TemplateAmici.delimiter`) - """ with open(source_file) as filein: src = TemplateAmici(filein.read()) @@ -3534,7 +3442,6 @@ def strip_pysb(symbol: sp.Basic) -> sp.Basic: :return: stripped expression - """ # strip pysb type and transform into a flat sympy.Symbol. # this ensures that the pysb type specific __repr__ is used when converting @@ -3557,10 +3464,9 @@ def get_function_extern_declaration(fun: str, name: str) -> str: :return: c++ function definition string - """ - return \ - f'extern void {fun}_{name}{functions[fun]["signature"]};' + f = functions[fun] + return f'extern {f.return_type} {fun}_{name}({f.arguments});' def get_sunindex_extern_declaration(fun: str, name: str, @@ -3580,7 +3486,6 @@ def get_sunindex_extern_declaration(fun: str, name: str, :return: c++ function declaration string - """ index_arg = ', int index' if fun in multiobs_functions else '' return \ @@ -3604,23 +3509,25 @@ def get_model_override_implementation(fun: str, name: str, :return: c++ function implementation string - """ - impl = 'virtual void f{fun}{signature} override {{' + impl = '{return_type} f{fun}({signature}) override {{' if nobody: impl += '}}\n' else: - impl += '\n{ind8}{fun}_{name}{eval_signature};\n{ind4}}}\n' + impl += '\n{ind8}{fun}_{name}({eval_signature});\n{ind4}}}\n' + + func_info = functions[fun] return impl.format( - ind4=' '*4, - ind8=' '*8, - fun=fun, - name=name, - signature=functions[fun]["signature"], - eval_signature=remove_typedefs(functions[fun]["signature"]) - ) + ind4=' ' * 4, + ind8=' ' * 8, + fun=fun, + name=name, + signature=func_info.arguments, + eval_signature=remove_typedefs(func_info.arguments), + return_type=func_info.return_type + ) def get_sunindex_override_implementation(fun: str, name: str, @@ -3644,27 +3551,26 @@ def get_sunindex_override_implementation(fun: str, name: str, :return: c++ function implementation string - """ index_arg = ', int index' if fun in multiobs_functions else '' index_arg_eval = ', index' if fun in multiobs_functions else '' - impl = 'virtual void f{fun}_{indextype}{signature} override {{' + impl = 'void f{fun}_{indextype}({signature}) override {{' if nobody: impl += '}}\n' else: - impl += '{ind8}{fun}_{indextype}_{name}{eval_signature};\n{ind4}}}\n' + impl += '{ind8}{fun}_{indextype}_{name}({eval_signature});\n{ind4}}}\n' return impl.format( - ind4=' '*4, - ind8=' '*8, - fun=fun, - indextype=indextype, - name=name, - signature=f'(SUNMatrixWrapper &{indextype}{index_arg})', - eval_signature=f'({indextype}{index_arg_eval})', - ) + ind4=' ' * 4, + ind8=' ' * 8, + fun=fun, + indextype=indextype, + name=name, + signature=f'SUNMatrixWrapper &{indextype}{index_arg}', + eval_signature=f'{indextype}{index_arg_eval}', + ) def remove_typedefs(signature: str) -> str: @@ -3678,7 +3584,7 @@ def remove_typedefs(signature: str) -> str: string that can be used to construct function calls with the same variable names and ordering as in the function signature """ - # remove * pefix for pointers (pointer must always be removed before + # remove * prefix for pointers (pointer must always be removed before # values otherwise we will inadvertently dereference values, # same applies for const specifications) # @@ -3701,130 +3607,6 @@ def remove_typedefs(signature: str) -> str: return signature -def get_switch_statement(condition: str, cases: Dict[int, List[str]], - indentation_level: Optional[int] = 0, - indentation_step: Optional[str] = ' ' * 4): - """ - Generate code for switch statement - - :param condition: - Condition for switch - - :param cases: - Cases as dict with expressions as keys and statement as - list of strings - - :param indentation_level: - indentation level - - :param indentation_step: - indentation whitespace per level - - :return: - Code for switch expression as list of strings - - """ - lines = list() - - if not cases: - return lines - - for expression, statements in cases.items(): - if statements: - lines.append((indentation_level + 1) * indentation_step - + f'case {expression}:') - for statement in statements: - lines.append((indentation_level + 2) * indentation_step - + statement) - lines.append((indentation_level + 2) * indentation_step + 'break;') - - if lines: - lines.insert(0, indentation_level * indentation_step - + f'switch({condition}) {{') - lines.append(indentation_level * indentation_step + '}') - - return lines - - -def csc_matrix(matrix: sp.Matrix, - rownames: List[sp.Symbol], - colnames: List[sp.Symbol], - identifier: Optional[int] = 0, - pattern_only: Optional[bool] = False) -> Tuple[ - List[int], List[int], sp.Matrix, List[str], sp.Matrix -]: - """ - Generates the sparse symbolic identifiers, symbolic identifiers, - sparse matrix, column pointers and row values for a symbolic - variable - - :param matrix: - dense matrix to be sparsified - - :param rownames: - ids of the variable of which the derivative is computed (assuming - matrix is the jacobian) - - :param colnames: - ids of the variable with respect to which the derivative is computed - (assuming matrix is the jacobian) - - :param identifier: - additional identifier that gets appended to symbol names to - ensure their uniqueness in outer loops - - :param pattern_only: - flag for computing sparsity pattern without whole matrix - - :return: - symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, - sparse_matrix - - """ - idx = 0 - - nrows, ncols = matrix.shape - - if not pattern_only: - sparse_matrix = sp.zeros(nrows, ncols) - symbol_list = [] - sparse_list = [] - symbol_col_ptrs = [] - symbol_row_vals = [] - - for col in range(0, ncols): - symbol_col_ptrs.append(idx) - for row in range(0, nrows): - if matrix[row, col] == 0: - continue - - symbol_row_vals.append(row) - idx += 1 - symbol_name = f'd{_print_with_exception(rownames[row])}' \ - f'_d{_print_with_exception(colnames[col])}' - if identifier: - symbol_name += f'_{identifier}' - symbol_list.append(symbol_name) - if pattern_only: - continue - - sparse_matrix[row, col] = sp.Symbol(symbol_name, real=True) - sparse_list.append(matrix[row, col]) - - if idx == 0: - symbol_col_ptrs = [] # avoid bad memory access for empty matrices - else: - symbol_col_ptrs.append(idx) - - if pattern_only: - sparse_matrix = None - else: - sparse_list = sp.Matrix(sparse_list) - - return symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, \ - sparse_matrix - - def is_valid_identifier(x: str) -> bool: """ Check whether `x` is a valid identifier for conditions, parameters, @@ -3931,7 +3713,6 @@ def _monkeypatched(obj: object, name: str, patch: Any): :param patch: patched value - """ pre_patched_value = getattr(obj, name) setattr(obj, name, patch) @@ -3943,7 +3724,7 @@ def _monkeypatched(obj: object, name: str, patch: Any): def _custom_pow_eval_derivative(self, s): """ - Custom Pow derivative that removes a removeable singularity for + Custom Pow derivative that removes a removable singularity for self.base == 0 and self.base.diff(s) == 0. This function is intended to be monkeypatched into sp.Pow._eval_derivative. @@ -3952,7 +3733,6 @@ def _custom_pow_eval_derivative(self, s): :param s: variable with respect to which the derivative will be computed - """ dbase = self.base.diff(s) dexp = self.exp.diff(s) @@ -3966,25 +3746,3 @@ def _custom_pow_eval_derivative(self, s): (self.base, sp.And(sp.Eq(self.base, 0), sp.Eq(dbase, 0))), (part2, True) ) - - -def _custom_print_max(self, expr): - """ - Custom Max printing function, see https://github.com/sympy/sympy/pull/20558 - """ - from sympy import Max - if len(expr.args) == 1: - return self._print(expr.args[0]) - return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]), - self._print(Max(*expr.args[1:]))) - - -def _custom_print_min(self, expr): - """ - Custom Min printing function, see https://github.com/sympy/sympy/pull/20558 - """ - from sympy import Min - if len(expr.args) == 1: - return self._print(expr.args[0]) - return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]), - self._print(Min(*expr.args[1:]))) diff --git a/python/amici/pandas.py b/python/amici/pandas.py index 8cf5610e46..740e32d411 100644 --- a/python/amici/pandas.py +++ b/python/amici/pandas.py @@ -1,7 +1,7 @@ """ Pandas Wrappers --------------- -This modules contains convenience wrappers that allow for easy interconversion +This module contains convenience wrappers that allow for easy interconversion between C++ objects from :mod:`amici.amici` and pandas DataFrames """ @@ -14,6 +14,15 @@ from .numpy import ExpDataView import amici +__all__ = [ + 'get_expressions_as_dataframe', + 'getEdataFromDataFrame', + 'getDataObservablesAsDataFrame', + 'getSimulationObservablesAsDataFrame', + 'getSimulationStatesAsDataFrame', + 'getResidualsAsDataFrame' +] + ExpDatas = Union[ List[amici.amici.ExpData], List[amici.ExpDataPtr], amici.amici.ExpData, amici.ExpDataPtr @@ -136,8 +145,8 @@ def getSimulationObservablesAsDataFrame( descriptive names. :return: - pandas DataFrame with conditions/timepoints as rows and state - variables as columns. + pandas DataFrame with conditions/timepoints as rows and observables as + columns. """ edata_list = _process_edata_list(edata_list) rdata_list = _process_rdata_list(rdata_list) @@ -145,7 +154,7 @@ def getSimulationObservablesAsDataFrame( # list of all column names using either names or ids cols = _get_extended_observable_cols(model, by_id=by_id) - # aggregate recrods + # aggregate records dicts = [] for edata, rdata in zip(edata_list, rdata_list): for i_time, timepoint in enumerate(rdata['t']): @@ -174,7 +183,7 @@ def getSimulationStatesAsDataFrame( rdata_list: ReturnDatas, by_id: Optional[bool] = False) -> pd.DataFrame: """ - Compute model residuals according to lists of ReturnData and ExpData. + Get model state according to lists of ReturnData and ExpData. :param model: Model instance. @@ -191,8 +200,8 @@ def getSimulationStatesAsDataFrame( If True, ids are used as identifiers, otherwise the possibly more descriptive names. - :return: pandas DataFrame with conditions/timpoints as rows and - observables as columns. + :return: pandas DataFrame with conditions/timepoints as rows and + state variables as columns. """ edata_list = _process_edata_list(edata_list) rdata_list = _process_rdata_list(rdata_list) @@ -222,12 +231,67 @@ def getSimulationStatesAsDataFrame( return pd.DataFrame.from_records(dicts, columns=cols) +def get_expressions_as_dataframe( + model: amici.Model, + edata_list: ExpDatas, + rdata_list: ReturnDatas, + by_id: Optional[bool] = False) -> pd.DataFrame: + """ + Get values of model expressions from lists of ReturnData as DataFrame. + + :param model: + Model instance. + + :param edata_list: + list of ExpData instances with experimental data. + May also be a single ExpData instance. + + :param rdata_list: + list of ReturnData instances corresponding to ExpData. + May also be a single ReturnData instance. + + :param by_id: + If True, ids are used as identifiers, otherwise the possibly more + descriptive names. + + :return: pandas DataFrame with conditions/timepoints as rows and + model expressions as columns. + """ + edata_list = _process_edata_list(edata_list) + rdata_list = _process_rdata_list(rdata_list) + + # get conditions and state column names by name or id + cols = _get_expression_cols(model, by_id=by_id) + + # aggregate records + dicts = [] + for edata, rdata in zip(edata_list, rdata_list): + for i_time, timepoint in enumerate(rdata['t']): + datadict = { + 'time': timepoint, + } + + # append expressions + for i_expr, expr in enumerate( + _get_names_or_ids(model, 'Expression', by_id=by_id)): + datadict[expr] = rdata['w'][i_time, i_expr] + + # use data to fill condition columns + _fill_conditions_dict(datadict, model, edata, by_id=by_id) + + # append to dataframe + dicts.append(datadict) + + return pd.DataFrame.from_records(dicts, columns=cols) + + def getResidualsAsDataFrame(model: amici.Model, edata_list: ExpDatas, rdata_list: ReturnDatas, by_id: Optional[bool] = False) -> pd.DataFrame: """ - Convert a list of ExpData to pandas DataFrame. + Convert a list of ReturnData and ExpData to pandas DataFrame with + residuals. :param model: Model instance. @@ -245,7 +309,7 @@ def getResidualsAsDataFrame(model: amici.Model, descriptive names. :return: - pandas DataFrame with conditions and observables. + pandas DataFrame with conditions and residuals. """ edata_list = _process_edata_list(edata_list) rdata_list = _process_rdata_list(rdata_list) @@ -313,6 +377,7 @@ def _fill_conditions_dict(datadict: Dict[str, float], dictionary with filled condition parameters. """ + datadict['condition_id'] = edata.id datadict['t_presim'] = edata.t_presim for i_par, par in enumerate( @@ -352,7 +417,7 @@ def _get_extended_observable_cols(model: AmiciModel, column names as list. """ return \ - ['time', 'datatype', 't_presim'] + \ + ['condition_id', 'time', 'datatype', 't_presim'] + \ _get_names_or_ids(model, 'FixedParameter', by_id=by_id) + \ [name + '_preeq' for name in _get_names_or_ids(model, 'FixedParameter', by_id=by_id)] + \ @@ -379,7 +444,7 @@ def _get_observable_cols(model: AmiciModel, column names as list. """ return \ - ['time', 't_presim'] + \ + ['condition_id', 'time', 't_presim'] + \ _get_names_or_ids(model, 'FixedParameter', by_id=by_id) + \ [name + '_preeq' for name in _get_names_or_ids(model, 'FixedParameter', by_id=by_id)] + \ @@ -404,7 +469,7 @@ def _get_state_cols(model: AmiciModel, column names as list. """ return \ - ['time', 't_presim'] + \ + ['condition_id', 'time', 't_presim'] + \ _get_names_or_ids(model, 'FixedParameter', by_id=by_id) + \ [name + '_preeq' for name in _get_names_or_ids(model, 'FixedParameter', by_id=by_id)] + \ @@ -413,6 +478,29 @@ def _get_state_cols(model: AmiciModel, _get_names_or_ids(model, 'State', by_id=by_id) +def _get_expression_cols(model: AmiciModel, by_id: bool) -> List[str]: + """Construction helper for expression dataframe headers. + + :param model: + Model instance. + + :param by_id: + If True, ids are used as identifiers, otherwise the possibly more + descriptive names. + + :return: + column names as list. + """ + return \ + ['condition_id', 'time', 't_presim'] + \ + _get_names_or_ids(model, 'FixedParameter', by_id=by_id) + \ + [name + '_preeq' for name in + _get_names_or_ids(model, 'FixedParameter', by_id=by_id)] + \ + [name + '_presim' for name in + _get_names_or_ids(model, 'FixedParameter', by_id=by_id)] + \ + _get_names_or_ids(model, 'Expression', by_id=by_id) + + def _get_names_or_ids(model: AmiciModel, variable: str, by_id: bool) -> List[str]: @@ -434,7 +522,9 @@ def _get_names_or_ids(model: AmiciModel, column names as list. """ # check whether variable type permitted - variable_options = ['Parameter', 'FixedParameter', 'Observable', 'State'] + variable_options = [ + 'Parameter', 'FixedParameter', 'Observable', 'State', 'Expression' + ] if variable not in variable_options: raise ValueError('Variable must be in ' + str(variable_options)) @@ -486,9 +576,6 @@ def _get_specialized_fixed_parameters( :return: overwritten FixedParameter as list. - - Raises: - """ cond = copy.deepcopy(condition) for field in overwrite: @@ -553,11 +640,11 @@ def constructEdataFromDataFrame( # fill in preequilibration parameters if any([overwrite_preeq[key] != condition[key] for key in - overwrite_preeq.keys()]): + overwrite_preeq]): edata.fixedParametersPreequilibration = \ _get_specialized_fixed_parameters( model, condition, overwrite_preeq, by_id=by_id) - elif len(overwrite_preeq.keys()): + elif len(overwrite_preeq): edata.fixedParametersPreequilibration = copy.deepcopy( edata.fixedParameters ) diff --git a/python/amici/petab_objective.py b/python/amici/petab_objective.py index 88ae41bd5b..b1da55d865 100644 --- a/python/amici/petab_objective.py +++ b/python/amici/petab_objective.py @@ -528,7 +528,9 @@ def create_edata_for_condition( # create an ExpData object edata = amici.ExpData(amici_model) - + edata.id = condition[SIMULATION_CONDITION_ID] + if condition.get(PREEQUILIBRATION_CONDITION_ID): + edata.id += "+" + condition.get(PREEQUILIBRATION_CONDITION_ID) ########################################################################## # enable initial parameters reinitialization species_in_condition_table = [ diff --git a/python/amici/pysb_import.py b/python/amici/pysb_import.py index cb1e82b811..0d38391e94 100644 --- a/python/amici/pysb_import.py +++ b/python/amici/pysb_import.py @@ -242,13 +242,14 @@ def _process_pysb_species(pysb_model: pysb.Model, for ix, specie in enumerate(pysb_model.species): init = sp.sympify('0.0') - for ic in pysb_model.odes.model.initial_conditions: - if pysb.pattern.match_complex_pattern(ic[0], specie, exact=True): + for ic in pysb_model.odes.model.initials: + if pysb.pattern.match_complex_pattern( + ic.pattern, specie, exact=True): # we don't want to allow expressions in initial conditions - if ic[1] in pysb_model.expressions: - init = pysb_model.expressions[ic[1].name].expand_expr() + if ic.value in pysb_model.expressions: + init = pysb_model.expressions[ic.value.name].expand_expr() else: - init = ic[1] + init = ic.value ode_model.add_component( State( diff --git a/python/amici/testing.py b/python/amici/testing.py new file mode 100644 index 0000000000..83980e02ed --- /dev/null +++ b/python/amici/testing.py @@ -0,0 +1,19 @@ +"""Test support functions""" + +import sys +from tempfile import TemporaryDirectory + + +class TemporaryDirectoryWinSafe(TemporaryDirectory): + """TemporaryDirectory that will not raise if cleanup fails. + + If any extension was loaded from the temporary directory, cleanup would + otherwise fail on Windows with a ``PermissionError``. This class ignores + such failures. + """ + def cleanup(self): + try: + super().cleanup() + except PermissionError as e: + if sys.platform not in {'win32', 'cygwin'}: + raise e diff --git a/python/sdist/amici/cxxcodeprinter.py b/python/sdist/amici/cxxcodeprinter.py new file mode 120000 index 0000000000..4a7a4c588b --- /dev/null +++ b/python/sdist/amici/cxxcodeprinter.py @@ -0,0 +1 @@ +../../amici/cxxcodeprinter.py \ No newline at end of file diff --git a/python/sdist/amici/testing.py b/python/sdist/amici/testing.py new file mode 120000 index 0000000000..3c889afbfa --- /dev/null +++ b/python/sdist/amici/testing.py @@ -0,0 +1 @@ +../../amici/testing.py \ No newline at end of file diff --git a/python/sdist/setup.cfg b/python/sdist/setup.cfg index 9e5093af44..c34c607740 100644 --- a/python/sdist/setup.cfg +++ b/python/sdist/setup.cfg @@ -28,10 +28,10 @@ package_dir = python_requires = >=3.7 install_requires = sympy>=1.9 - numpy>=1.14.5; python_version=='3.7' - numpy>=1.17.5; python_version=='3.8' - numpy>=1.19.3; python_version=='3.9' - numpy>=1.21.4; python_version>='3.10' + numpy>=1.14.5, <1.22.0; python_version=='3.7' + numpy>=1.17.5, <1.22.0; python_version=='3.8' + numpy>=1.19.3, <1.22.0; python_version=='3.9' + numpy>=1.21.4, <1.22.0; python_version>='3.10' python-libsbml h5py pandas diff --git a/python/tests/test_ode_export.py b/python/tests/test_ode_export.py index 4287a42fdf..83843348e8 100644 --- a/python/tests/test_ode_export.py +++ b/python/tests/test_ode_export.py @@ -1,15 +1,16 @@ """Miscellaneous AMICI Python interface tests""" -import amici import sympy as sp +from amici.cxxcodeprinter import AmiciCxxCodePrinter def test_csc_matrix(): """Test sparse CSC matrix creation""" + printer = AmiciCxxCodePrinter() matrix = sp.Matrix([[1, 0], [2, 3]]) symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ - = amici.ode_export.csc_matrix(matrix, rownames=['a1', 'a2'], - colnames=['b1', 'b2']) + = printer.csc_matrix(matrix, rownames=['a1', 'a2'], + colnames=['b1', 'b2']) assert symbol_col_ptrs == [0, 2, 3] assert symbol_row_vals == [0, 1, 1] @@ -20,9 +21,10 @@ def test_csc_matrix(): def test_csc_matrix_empty(): """Test sparse CSC matrix creation for empty matrix""" + printer = AmiciCxxCodePrinter() matrix = sp.Matrix() symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ - = amici.ode_export.csc_matrix(matrix, rownames=[], colnames=[]) + = printer.csc_matrix(matrix, rownames=[], colnames=[]) assert symbol_col_ptrs == [] assert symbol_row_vals == [] @@ -33,10 +35,10 @@ def test_csc_matrix_empty(): def test_csc_matrix_vector(): """Test sparse CSC matrix creation from matrix slice""" - + printer = AmiciCxxCodePrinter() matrix = sp.Matrix([[1, 0], [2, 3]]) symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ - = amici.ode_export.csc_matrix( + = printer.csc_matrix( matrix[:, 0], colnames=[sp.Symbol('b')], rownames=[sp.Symbol('a1'), sp.Symbol('a2')] ) @@ -49,7 +51,7 @@ def test_csc_matrix_vector(): # Test continuation of numbering of symbols symbol_col_ptrs, symbol_row_vals, sparse_list, symbol_list, sparse_matrix \ - = amici.ode_export.csc_matrix( + = printer.csc_matrix( matrix[:, 1], colnames=[sp.Symbol('b')], rownames=[sp.Symbol('a1'), sp.Symbol('a2')], identifier=1 ) diff --git a/python/tests/test_pregenerated_models.py b/python/tests/test_pregenerated_models.py index 470cc8ed86..f746ea4d6b 100755 --- a/python/tests/test_pregenerated_models.py +++ b/python/tests/test_pregenerated_models.py @@ -10,7 +10,7 @@ import h5py import numpy as np import pytest -from amici.gradient_check import check_derivatives, check_results +from amici.gradient_check import check_derivatives, _check_results cpp_test_dir = Path(__file__).parents[2] / 'tests' / 'cpp' options_file = str(cpp_test_dir / 'testOptions.h5') @@ -22,10 +22,6 @@ for case in list(expected_results[sub_test].keys())] -def assert_fun(x): - assert x - - @pytest.mark.skipif(os.environ.get('AMICI_SKIP_CMAKE_TESTS', '') == 'TRUE', reason='skipping cmake based test') @pytest.mark.parametrize("sub_test,case", model_cases) @@ -81,8 +77,7 @@ def test_pregenerated_model(sub_test, case): and len(model.getParameterList()) \ and not model_name.startswith('model_neuron') \ and not case.endswith('byhandpreeq'): - check_derivatives(model, solver, edata, assert_fun, - **check_derivative_opts) + check_derivatives(model, solver, edata, **check_derivative_opts) verify_simulation_opts = dict() @@ -165,8 +160,7 @@ def test_pregenerated_model(sub_test, case): if edata and solver.getSensitivityMethod() and \ solver.getSensitivityOrder() and len(model.getParameterList()): - check_derivatives(model, solver, edata, assert_fun, - **check_derivative_opts) + check_derivatives(model, solver, edata, **check_derivative_opts) chi2_ref = rdata.chi2 res_ref = rdata.res @@ -225,20 +219,20 @@ def verify_simulation_results(rdata, expected_results, fields=None, if subfield not in subfields: assert rdata[subfield] is None, field continue - check_results(rdata, subfield, - expected_results[field][subfield][()], - assert_fun, 1e-8, 1e-8) + _check_results(rdata, subfield, + expected_results[field][subfield][()], + atol=1e-8, rtol=1e-8) else: if field not in fields: assert rdata[field] is None, field continue if field == 's2llh': - check_results(rdata, field, expected_results[field][()], - assert_fun, 1e-4, 1e-3) + _check_results(rdata, field, expected_results[field][()], + atol=1e-4, rtol=1e-3) else: - check_results(rdata, field, expected_results[field][()], - assert_fun, atol, rtol) + _check_results(rdata, field, expected_results[field][()], + atol=atol, rtol=rtol) for attr in attrs: - check_results(rdata, attr, expected_results.attrs[attr], assert_fun, - atol, rtol) + _check_results(rdata, attr, expected_results.attrs[attr], + atol=atol, rtol=rtol) diff --git a/python/tests/test_sbml_import.py b/python/tests/test_sbml_import.py index a9b84c267c..ea624e51eb 100644 --- a/python/tests/test_sbml_import.py +++ b/python/tests/test_sbml_import.py @@ -1,18 +1,17 @@ """Tests related to amici.sbml_import""" - import os -import sys import re -from urllib.request import urlopen import shutil -from tempfile import TemporaryDirectory +from urllib.request import urlopen -import amici import libsbml import numpy as np import pytest + +import amici from amici.gradient_check import check_derivatives from amici.sbml_import import SbmlImporter +from amici.testing import TemporaryDirectoryWinSafe as TemporaryDirectory @pytest.fixture @@ -50,9 +49,11 @@ def test_sbml2amici_no_observables(simple_sbml_model): observables=None, compute_conservation_laws=False) + # Ensure import succeeds (no missing symbols) + module_module = amici.import_model_module("test", tmpdir) + assert hasattr(module_module, 'getModel') + -@pytest.mark.skipif(sys.platform in ['win32', 'cygwin'], - reason="windows stinks") def test_nosensi(simple_sbml_model): sbml_doc, sbml_model = simple_sbml_model sbml_importer = SbmlImporter(sbml_source=sbml_model, @@ -77,10 +78,6 @@ def test_nosensi(simple_sbml_model): assert rdata.status == amici.AMICI_ERROR -def assert_fun(x): - assert x - - @pytest.fixture def model_steadystate_module(): sbml_file = os.path.join(os.path.dirname(__file__), '..', @@ -153,7 +150,7 @@ def test_presimulation(sbml_example_presimulation_module): solver.setRelativeTolerance(1e-12) solver.setAbsoluteTolerance(1e-12) - check_derivatives(model, solver, edata, assert_fun, epsilon=1e-4) + check_derivatives(model, solver, edata, epsilon=1e-4) def test_steadystate_simulation(model_steadystate_module): @@ -163,8 +160,12 @@ def test_steadystate_simulation(model_steadystate_module): solver.setSensitivityOrder(amici.SensitivityOrder.first) rdata = amici.runAmiciSimulation(model, solver) edata = [amici.ExpData(rdata, 1, 0)] + edata[0].id = "some condition ID" rdata = amici.runAmiciSimulations(model, solver, edata) + assert rdata[0].status == amici.AMICI_SUCCESS + assert rdata[0].id == edata[0].id + # check roundtripping of DataFrame conversion df_edata = amici.getDataObservablesAsDataFrame(model, edata) edata_reconstructed = amici.getEdataFromDataFrame(model, df_edata) @@ -197,9 +198,13 @@ def test_steadystate_simulation(model_steadystate_module): df_obs[list(model.getObservableIds())].values).all() amici.getResidualsAsDataFrame(model, edata, rdata) + df_expr = amici.pandas.get_expressions_as_dataframe(model, edata, rdata) + assert np.isclose(rdata[0]['w'], + df_expr[list(model.getExpressionIds())].values).all() + solver.setRelativeTolerance(1e-12) solver.setAbsoluteTolerance(1e-12) - check_derivatives(model, solver, edata[0], assert_fun, atol=1e-3, + check_derivatives(model, solver, edata[0], atol=1e-3, rtol=1e-3, epsilon=1e-4) # Run some additional tests which need a working Model, @@ -301,7 +306,7 @@ def test_likelihoods(model_test_likelihoods): solver.setRelativeTolerance(1e-12) solver.setAbsoluteTolerance(1e-12) check_derivatives( - model, solver, edata, assert_fun, atol=1e-2, rtol=1e-2, + model, solver, edata, atol=1e-2, rtol=1e-2, epsilon=1e-5, check_least_squares=False ) @@ -381,7 +386,7 @@ def test_sympy_exp_monkeypatch(): # print sensitivity-related results assert rdata['status'] == amici.AMICI_SUCCESS - check_derivatives(model, solver, None, assert_fun, atol=1e-2, rtol=1e-2, + check_derivatives(model, solver, None, atol=1e-2, rtol=1e-2, epsilon=1e-3) diff --git a/python/tests/test_sbml_import_special_functions.py b/python/tests/test_sbml_import_special_functions.py index df496ad63f..67e1368f30 100644 --- a/python/tests/test_sbml_import_special_functions.py +++ b/python/tests/test_sbml_import_special_functions.py @@ -14,10 +14,6 @@ from amici.gradient_check import check_derivatives -def assert_fun(x): - assert x - - @pytest.fixture def model_special_likelihoods(): """Test model for special likelihood functions.""" @@ -104,7 +100,7 @@ def test_special_likelihoods(model_special_likelihoods): solver.setSensitivityMethod(sensi_method) solver.setSensitivityOrder(amici.SensitivityOrder.first) check_derivatives( - model, solver, edata, assert_fun, atol=1e-1, rtol=1e-1, + model, solver, edata, atol=1e-1, rtol=1e-1, check_least_squares=False) # Test for m > y, i.e. in region with 0 density diff --git a/python/tests/test_swig_interface.py b/python/tests/test_swig_interface.py index 3459c5c38d..1b8e733f85 100644 --- a/python/tests/test_swig_interface.py +++ b/python/tests/test_swig_interface.py @@ -3,6 +3,7 @@ Test getters, setters, etc. """ +import copy import numbers import amici @@ -179,6 +180,76 @@ def test_model_instance_settings(pysb_example_presimulation_module): ]) +def test_interdependent_settings(pysb_example_presimulation_module): + """Test settings that were not tested in `test_model_instance_settings`. + + `StateIsNonNegative` is still skipped, due to conservation laws in the + test model. + """ + model = pysb_example_presimulation_module.getModel() + + original_settings = { + 'FixedParameters': (9.0, 1.0), + 'ParameterList': (0, 1, 2, 3, 4, 5), + 'ParameterScale': [0, 0, 0, 0, 0, 0], + 'ReinitializationStateIdxs': tuple(), + 'ReinitializeFixedParameterInitialStates': False, + 'StateIsNonNegative': (False, False, False), + } + + expected_settings = { + 'FixedParameters': (8.0, 2.0), + 'ParameterList': (0, 1, 2, 3, 4), + 'ParameterScale': [1, 0, 0, 0, 0, 0], + 'ReinitializationStateIdxs': (0,), + 'ReinitializeFixedParameterInitialStates': True, + # Skipped due to conservation laws in the test model. + # 'StateIsNonNegative': None, + } + + # Some values need to be transformed to be tested in Python + # (e.g. SWIG objects). Default transformer is no transformation + # (the identity function). + getter_transformers = { + setting: (lambda x: x) + for setting in original_settings + } + getter_transformers.update({ + # Convert from SWIG object. + 'ParameterScale': lambda x: list(x) + }) + + default_settings = amici.get_model_settings(model) + for original_setting, original_setting_value in original_settings.items(): + test_value = getter_transformers[original_setting]( + default_settings[original_setting], + ) + # The original model is as expected (to ensure the test is still + # valid). + assert test_value == original_setting_value + + for setting, expected_value in expected_settings.items(): + input_settings = {setting: copy.deepcopy(expected_value)} + + amici.set_model_settings(model, input_settings) + output_settings = amici.get_model_settings(model) + test_value = getter_transformers[setting]( + output_settings[setting] + ) + # The setter works. + assert test_value == expected_value + + input_settings = {setting: output_settings[setting]} + amici.set_model_settings(model, input_settings) + output_settings = amici.get_model_settings(model) + test_value = getter_transformers[setting]( + output_settings[setting] + ) + # (round-trip) The output of the getter can be used as input to the + # setter, and does not change the value. + assert test_value == expected_value + + def test_unhandled_settings(pysb_example_presimulation_module): """Detect possible getters and setters that are not yet handled. diff --git a/python/tests/valgrind-python.supp b/python/tests/valgrind-python.supp index ac2c0f1f8a..26499682b4 100644 --- a/python/tests/valgrind-python.supp +++ b/python/tests/valgrind-python.supp @@ -484,3 +484,39 @@ obj:/usr/bin/python3.* ... } + +{ + PyDict_SetDefault + Memcheck:Cond + fun:bcmp + obj:/usr/bin/python3.* + ... +} + +{ + PyUnicode_Contains + Memcheck:Cond + fun:memchr + fun:PyUnicode_Contains + ... +} + +{ + _Py_write + Memcheck:Param + write(buf) + fun:__libc_write + fun:write + fun:_Py_write + obj:/usr/bin/python3.* +} + +{ + _PyObject_GC_New + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + fun:_PyObject_GC_New + ... + obj:/usr/bin/python3.* +} diff --git a/src/amici.cpp b/src/amici.cpp index 87e929060c..ee7bb8fcd1 100644 --- a/src/amici.cpp +++ b/src/amici.cpp @@ -112,6 +112,9 @@ AmiciApplication::runAmiciSimulation(Solver& solver, std::unique_ptr rdata = std::make_unique(solver, model); + if(edata) { + rdata->id = edata->id; + } std::unique_ptr preeq {}; std::unique_ptr fwd {}; @@ -302,18 +305,14 @@ AmiciApplication::checkFinite(gsl::span array, const char* fun) for (int idx = 0; idx < (int)array.size(); idx++) { if (isNaN(array[idx])) { warningF("AMICI:NaN", - "AMICI encountered a NaN value at index %i/%i in %s!", - idx, - (int)array.size()-1, - fun); + "AMICI encountered a NaN value for %s[%i]!", + fun, idx); return AMICI_RECOVERABLE_ERROR; } if (isInf(array[idx])) { warningF("AMICI:Inf", - "AMICI encountered an Inf value at index %i/%i in %s!", - idx, - (int)array.size()-1, - fun); + "AMICI encountered an Inf value for %s[%i]!", + fun, idx); return AMICI_RECOVERABLE_ERROR; } } diff --git a/src/backwardproblem.cpp b/src/backwardproblem.cpp index 61cfff8393..495837ea1b 100644 --- a/src/backwardproblem.cpp +++ b/src/backwardproblem.cpp @@ -184,7 +184,7 @@ realtype BackwardProblem::getTnext(const int it) { it, discs_.size(), this->t_ ); } - + if (!discs_.empty() && (it < 0 || discs_.back() > model_->getTimepoint(it))) { double tdisc = discs_.back(); diff --git a/src/edata.cpp b/src/edata.cpp index d2dbf70f1b..1842cf669f 100644 --- a/src/edata.cpp +++ b/src/edata.cpp @@ -98,7 +98,9 @@ ExpData::ExpData(ReturnData const& rdata, std::vector sigma_y, observed_events_.at(iz + rdata.nztrue * ie) = rdata.z.at(iz + rdata.nz * ie) + e(gen); observed_data_std_dev_.at(iz + rdata.nztrue * ie) = sigma; } - } + } + + id = rdata.id; } void ExpData::setTimepoints(const std::vector &ts) { diff --git a/src/hdf5.cpp b/src/hdf5.cpp index 626f3af249..7248a5c963 100644 --- a/src/hdf5.cpp +++ b/src/hdf5.cpp @@ -112,6 +112,10 @@ std::unique_ptr readSimulationExpData(std::string const& hdf5Filename, auto edata = std::unique_ptr(new ExpData(model)); + if(attributeExists(file, hdf5Root, "id")) { + edata->id = getStringAttribute(file, hdf5Root, "id"); + } + if (model.ny * model.nt() > 0) { if(locationExists(file, hdf5Root + "/Y")) { auto my = getDoubleDataset2D(file, hdf5Root + "/Y", m, n); @@ -192,6 +196,10 @@ void writeSimulationExpData(const ExpData &edata, H5::H5File const& file, if(!locationExists(file, hdf5Location)) createGroup(file, hdf5Location); + H5LTset_attribute_string(file.getId(), hdf5Location.c_str(), "id", + edata.id.c_str()); + + if (edata.nt()) createAndWriteDouble1DDataset(file, hdf5Location + "/ts", edata.getTimepoints()); @@ -245,6 +253,9 @@ void writeReturnData(const ReturnData &rdata, H5::H5File const& file, const std: if (!rdata.ts.empty()) createAndWriteDouble1DDataset(file, hdf5Location + "/t", rdata.ts); + H5LTset_attribute_string(file.getId(), hdf5Location.c_str(), "id", + rdata.id.c_str()); + H5LTset_attribute_double(file.getId(), hdf5Location.c_str(), "llh", &rdata.llh, 1); H5LTset_attribute_double(file.getId(), hdf5Location.c_str(), @@ -461,6 +472,34 @@ void writeReturnData(ReturnData const& rdata, writeReturnData(rdata, file, hdf5Location); } +std::string getStringAttribute(H5::H5File const& file, + std::string const& optionsObject, + std::string const& attributeName) { + hsize_t dims; + H5T_class_t type_class; + size_t type_size; + auto status = H5LTget_attribute_info(file.getId(), optionsObject.c_str(), + attributeName.c_str(), &dims, + &type_class,&type_size); + if(status < 0) { + throw AmiException("Could get info for attribute %s for object %s.", + attributeName.c_str(), optionsObject.c_str()); + } + std::vector value(type_size); + status = H5LTget_attribute_string(file.getId(), optionsObject.c_str(), + attributeName.c_str(), value.data()); + +#ifdef AMI_HDF5_H_DEBUG + printf("%s: %s\n", attributeName.c_str(), value.data()); +#endif + + if(status < 0) + throw AmiException("Attribute %s not found for object %s.", + attributeName.c_str(), optionsObject.c_str()); + + return std::string(value.data()); +} + double getDoubleScalarAttribute(H5::H5File const& file, std::string const& optionsObject, std::string const& attributeName) { diff --git a/src/model.cpp b/src/model.cpp index e37b7409db..4916c1e956 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -911,7 +911,7 @@ void Model::getEventSensitivity(gsl::span sz, const int ie, const realtype t, const AmiVector &x, const AmiVectorArray &sx) { for (int ip = 0; ip < nplist(); ip++) { - fsz(&sz.at(ip * nz), ie, t, x.data(), state_.unscaledParameters.data(), + fsz(&sz[ip * nz], ie, t, x.data(), state_.unscaledParameters.data(), state_.fixedParameters.data(), state_.h.data(), sx.data(ip), plist(ip)); } @@ -924,7 +924,7 @@ void Model::getUnobservedEventSensitivity(gsl::span sz, for (int iz = 0; iz < nz; ++iz) if (z2event_.at(iz) - 1 == ie) for (int ip = 0; ip < nplist(); ++ip) - sz.at(ip * nz + iz) = 0.0; + sz[ip * nz + iz] = 0.0; } void Model::getEventRegularization(gsl::span rz, const int ie, @@ -938,7 +938,7 @@ void Model::getEventRegularizationSensitivity(gsl::span srz, const AmiVector &x, const AmiVectorArray &sx) { for (int ip = 0; ip < nplist(); ip++) { - fsrz(&srz.at(ip * nz), ie, t, x.data(), state_.unscaledParameters.data(), + fsrz(&srz[ip * nz], ie, t, x.data(), state_.unscaledParameters.data(), state_.fixedParameters.data(), state_.h.data(), sx.data(ip), plist(ip)); } @@ -1280,7 +1280,7 @@ void Model::writeSliceEvent(gsl::span slice, checkBufferSize(buffer, z2event_.size()); for (unsigned izt = 0; izt < z2event_.size(); ++izt) if (z2event_.at(izt) - 1 == ie) - buffer.at(izt) = slice.at(izt); + buffer[izt] = slice[izt]; } void Model::writeSensitivitySliceEvent(gsl::span slice, @@ -1291,7 +1291,7 @@ void Model::writeSensitivitySliceEvent(gsl::span slice, for (int ip = 0; ip < nplist(); ++ip) for (unsigned izt = 0; izt < z2event_.size(); ++izt) if (z2event_.at(izt) - 1 == ie) - buffer.at(ip * nztrue + izt) = slice.at(ip * nztrue + izt); + buffer[ip * nztrue + izt] = slice[ip * nztrue + izt]; } void Model::writeLLHSensitivitySlice(const std::vector &dLLhdp, diff --git a/src/model_header.ODE_template.h b/src/model_header.ODE_template.h index c35d07918a..84cbfad356 100644 --- a/src/model_header.ODE_template.h +++ b/src/model_header.ODE_template.h @@ -120,25 +120,27 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Clone this model instance. * @return A deep copy of this instance. */ - virtual amici::Model *clone() const override { + amici::Model *clone() const override { return new Model_TPL_MODELNAME(*this); } - /** model specific implementation of fJrz + /** + * @brief model specific implementation of fJrz * @param nllh regularization for event measurements z * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint - **/ - virtual void fJrz(realtype *nllh, const int iz, const realtype *p, - const realtype *k, const realtype *rz, - const realtype *sigmaz) override {} + */ + void fJrz(realtype *nllh, const int iz, const realtype *p, + const realtype *k, const realtype *rz, + const realtype *sigmaz) override {} TPL_JY_IMPL - /** model specific implementation of fJz + /** + * @brief model specific implementation of fJz * @param nllh negative log-likelihood for event measurements z * @param iz event output index * @param p parameter vector @@ -146,12 +148,13 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurements at timepoint - **/ - virtual void fJz(realtype *nllh, const int iz, const realtype *p, - const realtype *k, const realtype *z, - const realtype *sigmaz, const realtype *mz) override {} + */ + void fJz(realtype *nllh, const int iz, const realtype *p, + const realtype *k, const realtype *z, + const realtype *sigmaz, const realtype *mz) override {} - /** model specific implementation of fdJrzdsigma + /** + * @brief model specific implementation of fdJrzdsigma * @param dJrzdsigma Sensitivity of event penalization Jrz w.r.t. * standard deviation sigmaz * @param iz event output index @@ -159,27 +162,29 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param k constant vector * @param rz model root output at timepoint * @param sigmaz event measurement standard deviation at timepoint - **/ - virtual void fdJrzdsigma(realtype *dJrzdsigma, const int iz, - const realtype *p, const realtype *k, - const realtype *rz, - const realtype *sigmaz) override {} + */ + void fdJrzdsigma(realtype *dJrzdsigma, const int iz, + const realtype *p, const realtype *k, + const realtype *rz, + const realtype *sigmaz) override {} - /** model specific implementation of fdJrzdz + /** + * @brief model specific implementation of fdJrzdz * @param dJrzdz partial derivative of event penalization Jrz * @param iz event output index * @param p parameter vector * @param k constant vector * @param rz model root output at timepoint * @param sigmaz event measurement standard deviation at timepoint - **/ - virtual void fdJrzdz(realtype *dJrzdz, const int iz, const realtype *p, - const realtype *k, const realtype *rz, - const realtype *sigmaz) override {} + */ + void fdJrzdz(realtype *dJrzdz, const int iz, const realtype *p, + const realtype *k, const realtype *rz, + const realtype *sigmaz) override {} TPL_DJYDSIGMA_IMPL - /** model specific implementation of fdJzdsigma + /** + * @brief model specific implementation of fdJzdsigma * @param dJzdsigma Sensitivity of event measurement * negative log-likelihood Jz w.r.t. standard deviation sigmaz * @param iz event output index @@ -188,27 +193,29 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurement at timepoint - **/ - virtual void fdJzdsigma(realtype *dJzdsigma, const int iz, - const realtype *p, const realtype *k, - const realtype *z, const realtype *sigmaz, - const realtype *mz) override {} + */ + void fdJzdsigma(realtype *dJzdsigma, const int iz, + const realtype *p, const realtype *k, + const realtype *z, const realtype *sigmaz, + const realtype *mz) override {} - /** model specific implementation of fdJzdz + /** + * @brief model specific implementation of fdJzdz * @param dJzdz partial derivative of event measurement negative - *log-likelihood Jz + * log-likelihood Jz * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurement at timepoint - **/ - virtual void fdJzdz(realtype *dJzdz, const int iz, const realtype *p, - const realtype *k, const realtype *z, - const realtype *sigmaz, const realtype *mz) override {} + */ + void fdJzdz(realtype *dJzdz, const int iz, const realtype *p, + const realtype *k, const realtype *z, + const realtype *sigmaz, const realtype *mz) override {} - /** model specific implementation of fdeltasx + /** + * @brief model specific implementation of fdeltasx * @param deltaqB sensitivity update * @param t current time * @param x current state @@ -220,19 +227,20 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param xdot new model right hand side * @param xdot_old previous model right hand side * @param xB adjoint state - **/ - virtual void fdeltaqB(realtype *deltaqB, const realtype t, - const realtype *x, const realtype *p, - const realtype *k, const realtype *h, const int ip, - const int ie, const realtype *xdot, - const realtype *xdot_old, - const realtype *xB) override {} + */ + void fdeltaqB(realtype *deltaqB, const realtype t, + const realtype *x, const realtype *p, + const realtype *k, const realtype *h, const int ip, + const int ie, const realtype *xdot, + const realtype *xdot_old, + const realtype *xB) override {} TPL_DELTASX_IMPL TPL_DELTAX_IMPL - /** model specific implementation of fdeltaxB + /** + * @brief model specific implementation of fdeltaxB * @param deltaxB adjoint state update * @param t current time * @param x current state @@ -243,16 +251,17 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param xdot new model right hand side * @param xdot_old previous model right hand side * @param xB current adjoint state - **/ - virtual void fdeltaxB(realtype *deltaxB, const realtype t, - const realtype *x, const realtype *p, - const realtype *k, const realtype *h, const int ie, - const realtype *xdot, const realtype *xdot_old, - const realtype *xB) override {} - - /** model specific implementation of fdrzdp + */ + void fdeltaxB(realtype *deltaxB, const realtype t, + const realtype *x, const realtype *p, + const realtype *k, const realtype *h, const int ie, + const realtype *xdot, const realtype *xdot_old, + const realtype *xB) override {} + + /** + * @brief model specific implementation of fdrzdp * @param drzdp partial derivative of root output rz w.r.t. model parameters - *p + * p * @param ie event index * @param t current time * @param x current state @@ -260,12 +269,13 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param k constant vector * @param h heaviside vector * @param ip parameter index w.r.t. which the derivative is requested - **/ - virtual void fdrzdp(realtype *drzdp, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h, const int ip) override {} + */ + void fdrzdp(realtype *drzdp, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h, const int ip) override {} - /** model specific implementation of fdrzdx + /** + * @brief model specific implementation of fdrzdx * @param drzdx partial derivative of root output rz w.r.t. model states x * @param ie event index * @param t current time @@ -273,24 +283,25 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param p parameter vector * @param k constant vector * @param h heaviside vector - **/ - virtual void fdrzdx(realtype *drzdx, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h) override {} + */ + void fdrzdx(realtype *drzdx, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h) override {} TPL_DSIGMAYDP_IMPL - /** model specific implementation of fsigmaz + /** + * @brief model specific implementation of fsigmaz * @param dsigmazdp partial derivative of standard deviation of event - *measurements + * measurements * @param t current time * @param p parameter vector * @param k constant vector * @param ip sensitivity index - **/ - virtual void fdsigmazdp(realtype *dsigmazdp, const realtype t, - const realtype *p, const realtype *k, - const int ip) override {} + */ + void fdsigmazdp(realtype *dsigmazdp, const realtype t, + const realtype *p, const realtype *k, + const int ip) override {} TPL_DJYDY_IMPL TPL_DJYDY_COLPTRS_IMPL @@ -324,9 +335,10 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { TPL_DYDP_IMPL - /** model specific implementation of fdzdp + /** + * @brief model specific implementation of fdzdp * @param dzdp partial derivative of event-resolved output z w.r.t. model - *parameters p + * parameters p * @param ie event index * @param t current time * @param x current state @@ -334,53 +346,57 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param k constant vector * @param h heaviside vector * @param ip parameter index w.r.t. which the derivative is requested - **/ - virtual void fdzdp(realtype *dzdp, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h, const int ip) override {} + */ + void fdzdp(realtype *dzdp, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h, const int ip) override {} - /** model specific implementation of fdzdx + /** + * @brief model specific implementation of fdzdx * @param dzdx partial derivative of event-resolved output z w.r.t. model - *states x + * states x * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector - **/ - virtual void fdzdx(realtype *dzdx, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h) override {} + */ + void fdzdx(realtype *dzdx, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h) override {} TPL_ROOT_IMPL - /** model specific implementation of frz + /** + * @brief model specific implementation of frz * @param rz value of root function at current timepoint (non-output events - *not included) + * not included) * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector - **/ - virtual void frz(realtype *rz, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h) override {} + */ + void frz(realtype *rz, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h) override {} TPL_SIGMAY_IMPL - /** model specific implementation of fsigmaz + /** + * @brief model specific implementation of fsigmaz * @param sigmaz standard deviation of event measurements * @param t current time * @param p parameter vector * @param k constant vector - **/ - virtual void fsigmaz(realtype *sigmaz, const realtype t, const realtype *p, - const realtype *k) override {} + */ + void fsigmaz(realtype *sigmaz, const realtype t, const realtype *p, + const realtype *k) override {} - /** model specific implementation of fsrz + /** + * @brief model specific implementation of fsrz * @param srz Sensitivity of rz, total derivative * @param ie event index * @param t current time @@ -390,17 +406,18 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param sx current state sensitivity * @param h heaviside vector * @param ip sensitivity index - **/ - virtual void fsrz(realtype *srz, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h, const realtype *sx, - const int ip) override {} + */ + void fsrz(realtype *srz, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h, const realtype *sx, + const int ip) override {} TPL_STAU_IMPL TPL_SX0_IMPL TPL_SX0_FIXEDPARAMETERS_IMPL - /** model specific implementation of fsz + /** + * @brief model specific implementation of fsz * @param sz Sensitivity of rz, total derivative * @param ie event index * @param t current time @@ -410,11 +427,11 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param h heaviside vector * @param sx current state sensitivity * @param ip sensitivity index - **/ - virtual void fsz(realtype *sz, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h, const realtype *sx, - const int ip) override {} + */ + void fsz(realtype *sz, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h, const realtype *sx, + const int ip) override {} TPL_W_IMPL @@ -426,7 +443,8 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { TPL_Y_IMPL - /** model specific implementation of fz + /** + * @brief model specific implementation of fz * @param z value of event output * @param ie event index * @param t current time @@ -434,10 +452,10 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @param p parameter vector * @param k constant vector * @param h heaviside vector - **/ - virtual void fz(realtype *z, const int ie, const realtype t, - const realtype *x, const realtype *p, const realtype *k, - const realtype *h) override {} + */ + void fz(realtype *z, const int ie, const realtype t, + const realtype *x, const realtype *p, const realtype *k, + const realtype *h) override {} TPL_X_RDATA_IMPL @@ -453,7 +471,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get names of the model parameters * @return the names */ - virtual std::vector getParameterNames() const override { + std::vector getParameterNames() const override { return std::vector(parameterNames.begin(), parameterNames.end()); } @@ -462,7 +480,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get names of the model states * @return the names */ - virtual std::vector getStateNames() const override { + std::vector getStateNames() const override { return std::vector(stateNames.begin(), stateNames.end()); } @@ -470,7 +488,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get names of the fixed model parameters * @return the names */ - virtual std::vector getFixedParameterNames() const override { + std::vector getFixedParameterNames() const override { return std::vector(fixedParameterNames.begin(), fixedParameterNames.end()); } @@ -479,7 +497,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get names of the observables * @return the names */ - virtual std::vector getObservableNames() const override { + std::vector getObservableNames() const override { return std::vector(observableNames.begin(), observableNames.end()); } @@ -488,7 +506,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get names of model expressions * @return Expression names */ - virtual std::vector getExpressionNames() const override { + std::vector getExpressionNames() const override { return std::vector(expressionNames.begin(), expressionNames.end()); } @@ -497,7 +515,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get ids of the model parameters * @return the ids */ - virtual std::vector getParameterIds() const override { + std::vector getParameterIds() const override { return std::vector(parameterIds.begin(), parameterIds.end()); } @@ -506,7 +524,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get ids of the model states * @return the ids */ - virtual std::vector getStateIds() const override { + std::vector getStateIds() const override { return std::vector(stateIds.begin(), stateIds.end()); } @@ -514,7 +532,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get ids of the fixed model parameters * @return the ids */ - virtual std::vector getFixedParameterIds() const override { + std::vector getFixedParameterIds() const override { return std::vector(fixedParameterIds.begin(), fixedParameterIds.end()); } @@ -523,7 +541,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get ids of the observables * @return the ids */ - virtual std::vector getObservableIds() const override { + std::vector getObservableIds() const override { return std::vector(observableIds.begin(), observableIds.end()); } @@ -532,18 +550,18 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief Get IDs of model expressions * @return Expression IDs */ - virtual std::vector getExpressionIds() const override { + std::vector getExpressionIds() const override { return std::vector(expressionIds.begin(), expressionIds.end()); } /** - * @brief function indicating whether reinitialization of states depending on - fixed parameters is permissible + * @brief function indicating whether reinitialization of states depending + * on fixed parameters is permissible * @return flag indicating whether reinitialization of states depending on - fixed parameters is permissible + * fixed parameters is permissible */ - virtual bool isFixedParameterStateReinitializationAllowed() const override { + bool isFixedParameterStateReinitializationAllowed() const override { return TPL_REINIT_FIXPAR_INITCOND; } @@ -551,7 +569,7 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief returns the AMICI version that was used to generate the model * @return AMICI version string */ - virtual std::string getAmiciVersion() const override { + std::string getAmiciVersion() const override { return "TPL_AMICI_VERSION_STRING"; } @@ -559,15 +577,15 @@ class Model_TPL_MODELNAME : public amici::Model_ODE { * @brief returns the amici version that was used to generate the model * @return AMICI git commit hash */ - virtual std::string getAmiciCommit() const override { + std::string getAmiciCommit() const override { return "TPL_AMICI_COMMIT_STRING"; } - virtual bool hasQuadraticLLH() const override { + bool hasQuadraticLLH() const override { return TPL_QUADRATIC_LLH; } - virtual ObservableScaling getObservableScaling(int iy) const override { + ObservableScaling getObservableScaling(int iy) const override { return observableScalings.at(iy); } }; diff --git a/src/rdata.cpp b/src/rdata.cpp index 38fcf8562c..d0fe49067b 100644 --- a/src/rdata.cpp +++ b/src/rdata.cpp @@ -810,11 +810,11 @@ void ReturnData::fres(const int it, Model &model, const ExpData &edata) { int iyt = iy + it * edata.nytrue(); if (!edata.isSetObservedData(it, iy)) continue; - + res.at(iyt) = amici::fres(y_it.at(iy), observedData[iy], sigmay_it.at(iy), model.getObservableScaling(iy)); - + if (sigma_res) res.at(iyt + nt * nytrue) = fres_error(sigmay_it.at(iy), sigma_offset); @@ -874,7 +874,7 @@ void ReturnData::fsres(const int it, Model &model, const ExpData &edata) { continue; for (int ip = 0; ip < nplist; ++ip) { int idx = (iy + it * edata.nytrue()) * nplist + ip; - + sres.at(idx) = amici::fsres(y_it.at(iy), sy_it.at(iy + ny * ip), observedData[iy], sigmay_it.at(iy), ssigmay_it.at(iy + ny * ip), diff --git a/src/sundials_matrix_wrapper.cpp b/src/sundials_matrix_wrapper.cpp index 9fb2fee025..bd3fda4fb8 100644 --- a/src/sundials_matrix_wrapper.cpp +++ b/src/sundials_matrix_wrapper.cpp @@ -34,8 +34,8 @@ SUNMatrixWrapper::SUNMatrixWrapper(sunindextype M, sunindextype N) throw std::bad_alloc(); finish_init(); - assert(M == rows()); - assert(N == columns()); + assert(M == rows() || !matrix_); + assert(N == columns() || !matrix_); } SUNMatrixWrapper::SUNMatrixWrapper(sunindextype M, sunindextype ubw, @@ -243,7 +243,7 @@ void SUNMatrixWrapper::multiply(gsl::span c, } check_csc(this); for (sunindextype icol = 0; icol < columns(); ++icol) { - scatter(icol, b.at(icol) * alpha, nullptr, c, icol+1, nullptr, 0); + scatter(icol, b[icol] * alpha, nullptr, c, icol+1, nullptr, 0); } break; default: @@ -288,8 +288,8 @@ void SUNMatrixWrapper::multiply(gsl::span c, if (transpose) { auto cols_size = cols.size(); for (std::size_t icols = 0; icols < cols_size; ++icols) { - auto idx_next_col = get_indexptr(cols.at(icols) + 1); - for (sunindextype idx = get_indexptr(cols.at(icols)); + auto idx_next_col = get_indexptr(cols[icols] + 1); + for (sunindextype idx = get_indexptr(cols[icols]); idx < idx_next_col; ++idx) { auto idx_val = get_indexval(idx); @@ -302,9 +302,9 @@ void SUNMatrixWrapper::multiply(gsl::span c, } else { auto num_cols = static_cast(columns()); for (std::size_t icols = 0; icols < num_cols; ++icols) { - auto idx_next_col = get_indexptr(cols.at(icols) + 1); + auto idx_next_col = get_indexptr(cols[icols] + 1); - for (sunindextype idx = get_indexptr(cols.at(icols)); + for (sunindextype idx = get_indexptr(cols[icols]); idx < idx_next_col; ++idx) { auto idx_val = get_indexval(idx); diff --git a/src/symbolic_functions.cpp b/src/symbolic_functions.cpp index 2b99cc0e92..df8397644f 100644 --- a/src/symbolic_functions.cpp +++ b/src/symbolic_functions.cpp @@ -25,40 +25,12 @@ namespace amici { -/** - * c++ interface to the isNaN function - * - * @param what argument - * @return isnan(what) - * - */ int isNaN(double what) { return std::isnan(what); } -/** - * c++ interface to the isinf function - * - * @param what argument - * @return isnan(what) - * - */ int isInf(double what) { return std::isinf(what); } -/** - * function returning nan - * - * @return NaN - * - */ double getNaN() { return NAN; } -/** - * C implementation of log function, this prevents returning NaN values for - * negative values - * - * @param x argument - * @return if(x>0) then log(x) else -Inf - * - */ double log(double x) { if (x <= 0) { return -std::log(DBL_MAX); @@ -66,13 +38,6 @@ double log(double x) { return std::log(x); } -/** - * C implementation of matlab function dirac - * - * @param x argument - * @return if(x==0) then INF else 0 - * - */ double dirac(double x) { if (x == 0.0) { return DBL_MAX; @@ -96,13 +61,6 @@ double heaviside(double x, double x0) { return 1.0; } -/** - * c implementation of matlab function sign - * - * @param x argument - * @return 0 - * - */ double sign(double x) { if (x > 0.0) return 1.0; @@ -113,14 +71,6 @@ double sign(double x) { return 0.0; } -/** - * c implementation of matlab function max - * - * @param a value1 - * @param b value2 - * @return if(a > b) then a else b - * - */ double max(double a, double b, double /*c*/) { int anan = isNaN(a), bnan = isNaN(b); if (anan || bnan) { @@ -133,29 +83,10 @@ double max(double a, double b, double /*c*/) { return (std::max(a, b)); } -/** - * c implementation of matlab function min - * - * @param a value1 - * @param b value2 - * @param c bogus parameter to ensure correct parsing as a function - * @return if(a < b) then a else b - * - */ double min(double a, double b, double c) { return (-max(-a,-b,c)); } -/** - * parameter derivative of c implementation of matlab function max - * - * @param id argument index for differentiation - * @param a value1 - * @param b value2 - * @return id == 1: if(a > b) then 1 else 0 - * @return id == 2: if(a > b) then 0 else 1 - * - */ double Dmax(int id, double a, double b, double /*c*/) { if (id == 1.0) { if (a > b) @@ -168,49 +99,18 @@ double Dmax(int id, double a, double b, double /*c*/) { return 1.0; } -/** - * parameter derivative of c implementation of matlab function max - * - * @param id argument index for differentiation - * @param a value1 - * @param b value2 - * @param c bogus parameter to ensure correct parsing as a function - * @return id == 1: if(a > b) then 1 else 0 - * @return id == 2: if(a > b) then 0 else 1 - * - */ double Dmin(int id, double a, double b, double c) { return Dmax(id,-a,-b,c); } -/** - * specialized pow functions that assumes positivity of the first argument - * - * @param base base - * @param exponent exponent - * @return pow(max(base,0.0),exponent) - * - */ double pos_pow(double base, double exponent) { // we do NOT want to propagate NaN values here, if base is nan, so should the output be return pow(std::max(base, 0.0),exponent); } -/** - * @brief Spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments must be of type - * double. - * - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return spline(t) - * - */ + + +// Legacy spline implementation in C (MATLAB only) double spline(double t, int num, ...) { va_list valist; @@ -247,21 +147,6 @@ double spline(double t, int num, ...) { return uout; } -/** - * @brief Exponentiated spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments must be of type - * double. - * - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return spline(t) - * - */ double spline_pos(double t, int num, ...) { va_list valist; @@ -299,23 +184,6 @@ double spline_pos(double t, int num, ...) { return exp(uout); } -/** - * @brief Derivation of a spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments but id must be of - * type double. - * - * @param id index of node to which the derivative of the corresponding spline - * coefficient should be computed - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return dsplinedp(t) - * - */ double Dspline(int id, double t, int num, ...) { va_list valist; @@ -356,23 +224,6 @@ double Dspline(int id, double t, int num, ...) { return uout; } -/** - * @brief Derivation of an exponentiated spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments but id must be of - * type double. - * - * @param id index of node to which the derivative of the corresponding spline - * coefficient should be computed - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return dsplinedp(t) - * - */ double Dspline_pos(int id, double t, int num, ...) { va_list valist; @@ -421,45 +272,8 @@ double Dspline_pos(int id, double t, int num, ...) { return uout; } -/** - * @brief Second derivation of a spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments but id1 and id2 - * must be of type double. - * - * @param id1 index of node to which the first derivative of the corresponding - * spline coefficient should be computed - * @param id2 index of node to which the second derivative of the corresponding - * spline coefficient should be computed - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return ddspline(t) - */ double DDspline(int /*id1*/, int /*id2*/, double /*t*/, int /*num*/, ...) { return 0.0; } -/** - * @brief Derivation of an exponentiated spline function - * - * Takes variable argument pairs (ti,pi) with `ti`: location of node i and - * `pi`: spline value at node i. the last two arguments are always `ss`: flag - * indicating whether slope at first node should be user defined - * and `dudt` user defined slope at first node. All arguments but id1 and id2 - * must be of type double. - * - * @param id1 index of node to which the first derivative of the corresponding - * spline coefficient should be computed - * @param id2 index of node to which the second derivative of the corresponding - * spline coefficient should be computed - * @param t point at which the spline should be evaluated - * @param num number of spline nodes - * - * @return ddspline(t) - * - */ double DDspline_pos(int id1, int id2, double t, int num, ...) { va_list valist; diff --git a/src/vector.cpp b/src/vector.cpp index ed1e1618b2..25502e7888 100644 --- a/src/vector.cpp +++ b/src/vector.cpp @@ -1,6 +1,7 @@ #include "amici/vector.h" #include +#include namespace amici { diff --git a/swig/amici.i b/swig/amici.i index 7253545d60..09b74411b9 100644 --- a/swig/amici.i +++ b/swig/amici.i @@ -131,8 +131,18 @@ std::vector parameterScalingFromIntVector(std::vector const& intVec) { + std::vector result(intVec.size()); + for (int i = 0; i < (int) result.size(); ++i) { + result[i] = static_cast(intVec[i]); + } + $self->setParameterScale(result); + } +} namespace amici { std::vector parameterScalingFromIntVector(std::vector const& intVec); + void Model::setParameterScale(std::vector const& intVec); } %template(ParameterScalingVector) std::vector; diff --git a/tests/cpp/unittests/testSerialization.cpp b/tests/cpp/unittests/testSerialization.cpp index 15c8df9d84..f349424408 100644 --- a/tests/cpp/unittests/testSerialization.cpp +++ b/tests/cpp/unittests/testSerialization.cpp @@ -11,6 +11,7 @@ void checkReturnDataEqual(amici::ReturnData const& r, amici::ReturnData const& s) { + ASSERT_EQ(r.id, s.id); ASSERT_EQ(r.np, s.np); ASSERT_EQ(r.nk, s.nk); ASSERT_EQ(r.nx, s.nx); @@ -227,7 +228,7 @@ TEST(ReturnDataSerializationTest, ToString) std::vector(nz, 0)); amici::ReturnData r(solver, m); - + r.id = "some_id"; std::string serialized = amici::serializeToString(r); checkReturnDataEqual( diff --git a/tests/petab_test_suite/test_petab_suite.py b/tests/petab_test_suite/test_petab_suite.py index 5e0695c3e1..59c13c72b4 100755 --- a/tests/petab_test_suite/test_petab_suite.py +++ b/tests/petab_test_suite/test_petab_suite.py @@ -136,9 +136,6 @@ def check_derivatives(problem: petab.Problem, model: amici.Model) -> None: model.setSteadyStateSensitivityMode( SteadyStateSensitivityMode_simulationFSA) - def assert_true(x): - assert x - for edata in create_parameterized_edatas( amici_model=model, petab_problem=problem, problem_parameters=problem_parameters): @@ -147,7 +144,7 @@ def assert_true(x): model.setParameterScale(edata.pscale) edata.parameters = [] edata.pscale = amici.parameterScalingFromIntVector([]) - amici_check_derivatives(model, solver, edata, assert_true) + amici_check_derivatives(model, solver, edata) def run(): diff --git a/version.txt b/version.txt index cf65fa62c8..b76fc26753 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -0.11.22 +0.11.23