diff --git a/bindings/python/src/stochastic/applications/fractures.hpp b/bindings/python/src/stochastic/applications/fractures.hpp index 7bae11e..6ce9d70 100644 --- a/bindings/python/src/stochastic/applications/fractures.hpp +++ b/bindings/python/src/stochastic/applications/fractures.hpp @@ -106,7 +106,11 @@ namespace geode "expected_total_length, if given, is the expected mean of " "the statistic of the term (the total length of the " "fractures inside the domain). The set is looked up when the " - "simulation is built." ) + "simulation is built. p21 > 1, which favors long fractures, " + "needs a bounded length law on the set (a finite max_value, " + "not Gaussian), otherwise OpenGeodeDataError is raised: the " + "energy weight of a fracture is its whole length, so the model " + "is not integrable with an unbounded law." ) .def( "add_minimal_spacing", &FractureProcessBuilder::add_minimal_spacing, pybind11::arg( "set_name" ), pybind11::arg( "minimal_spacing" ), diff --git a/bindings/python/tests/stochastic/test-py-simulation-errors.py b/bindings/python/tests/stochastic/test-py-simulation-errors.py index b9a9e62..1bafae2 100644 --- a/bindings/python/tests/stochastic/test-py-simulation-errors.py +++ b/bindings/python/tests/stochastic/test-py-simulation-errors.py @@ -155,6 +155,14 @@ def test_builder_errors(): builder, fset = small_builder() fset.dynamics = stochastic.ObjectSetDynamicsConfig(birth_ratio=0.0, death_ratio=0.0, change_ratio=0.0) raises(og.OpenGeodeDataError, lambda: builder.build_simulation_runner(), "No move at all") + # p21 > 1 needs a bounded length law: the energy weight of a fracture is + # its whole length + builder, fset = small_builder() + fset.sampler.length = stochastic.DoubleDistributionDescription( + "TruncatedLogNormal", mean=0.0, standard_deviation=0.5, min_value=0.5 + ) + builder.add_intensity("fset", 2.0) + raises(og.OpenGeodeDataError, lambda: builder.build_simulation_runner(), "p21 > 1 on an unbounded law") print("test_builder_errors: OK") diff --git a/include/geode/stochastic/applications/fractures.hpp b/include/geode/stochastic/applications/fractures.hpp index f7ce61c..fdc923e 100644 --- a/include/geode/stochastic/applications/fractures.hpp +++ b/include/geode/stochastic/applications/fractures.hpp @@ -79,6 +79,11 @@ namespace geode IntensityScope scope = IntensityScope::free_objects ); /// Intensity term (fracture length per unit area) on a fracture set. + /// p21 > 1, which favors long fractures, needs a bounded length law + /// on the set (a finite max_value, not Gaussian): the energy weight of + /// a fracture is its whole length, so the model is otherwise not + /// integrable. Checked when the simulation is built, and by + /// Model::set_thetas afterwards. void add_intensity( std::string_view set_name, double p21, std::optional< double > expected_total_length = std::nullopt ); diff --git a/include/geode/stochastic/common.hpp b/include/geode/stochastic/common.hpp index 675026b..401d375 100644 --- a/include/geode/stochastic/common.hpp +++ b/include/geode/stochastic/common.hpp @@ -39,4 +39,10 @@ namespace geode static constexpr double LOG_PROB_INVALID = -std::numeric_limits< double >::infinity(); + + /// Tolerance for the quantities without unit: ratios, weights, exponents, + /// numbers of objects. GLOBAL_EPSILON is a length tolerance (it depends on + /// the units): use it for lengths and distances only. Never use either as + /// a threshold on a model parameter, which is in physical units. + static constexpr double DIMENSIONLESS_EPSILON{ 1E-6 }; } // namespace geode \ No newline at end of file diff --git a/include/geode/stochastic/models/energy_terms/energy_term.hpp b/include/geode/stochastic/models/energy_terms/energy_term.hpp index 6ec27e8..83c87be 100644 --- a/include/geode/stochastic/models/energy_terms/energy_term.hpp +++ b/include/geode/stochastic/models/energy_terms/energy_term.hpp @@ -50,9 +50,10 @@ namespace geode public: /// gamma is the parameter of the term, in the user space: the energy - /// is -log( gamma ) times the energy statistic. gamma below - /// GLOBAL_EPSILON makes the term a hard-core constraint: any - /// configuration with a positive energy statistic is forbidden. + /// is -log( gamma ) times the energy statistic. gamma = 0 makes the + /// term a hard-core constraint: any configuration with a positive + /// energy statistic is forbidden. Any positive gamma, however small, + /// is an ordinary term (the parameters are in physical units). explicit EnergyTerm( std::string_view name, double gamma, std::vector< uuid >&& impacted_set_ids, @@ -63,7 +64,7 @@ namespace geode OpenGeodeStochasticStochasticException::check_exception( gamma >= 0., nullptr, OpenGeodeException::TYPE::data, "[EnergyTerm] Model parameter cannot be negative." ); - hard_core_ = gamma < GLOBAL_EPSILON; + hard_core_ = gamma == 0.; theta_ = hard_core_ ? -std::numeric_limits< double >::infinity() : std::log( gamma ); absl::c_sort( impacted_set_ids_ ); @@ -91,7 +92,8 @@ namespace geode /// True if theta may be positive (gamma > 1) and keep the model /// integrable. Set by the model, which knows the other terms (see - /// detail::attraction_allowed); false for a term outside a model. + /// detail::attraction_allowed and Model::forbid_attraction); false for + /// a term outside a model. [[nodiscard]] bool attraction_allowed() const { return attraction_allowed_; diff --git a/include/geode/stochastic/models/model.hpp b/include/geode/stochastic/models/model.hpp index 1b1d6b1..c221fd7 100644 --- a/include/geode/stochastic/models/model.hpp +++ b/include/geode/stochastic/models/model.hpp @@ -83,21 +83,35 @@ namespace geode std::vector< EnergyTermConfig > terms; }; - /// Throws if the model is not well defined (not integrable): an attractive - /// pairwise term (gamma > 1) requires each of its object sets to have an - /// intra-set hard-core (gamma = 0) at a strictly positive distance. - /// Without it, the Strauss model with gamma > 1 is not integrable - /// (Baddeley, Rubak and Turner, 2015). - opengeode_stochastic_stochastic_api void check_model_integrability( + /*! + * Integrability of the model: exp( sum theta_i s_i ) must be integrable + * with respect to the laws of the set samplers (Moller and Waagepetersen, + * 2004). The statistics are non negative, so theta <= 0 is always + * integrable. The sources of non integrability and their checks: + * 1. attractive pairwise term (theta > 0) without intra-set hard-cores + * (Kelly and Ripley, 1976; Baddeley, Rubak and Turner, 2015): + * check_attractions_have_hard_cores; + * 2. length term with theta > 0 on an unbounded length law: + * build_simulation_context, which knows the sampler laws, calls + * Model::forbid_attraction on such a term; + * 3. Model::set_thetas checks each new theta against both rules (see + * EnergyTerm::attraction_allowed). + */ + + /// Throws if an attractive pairwise term (gamma > 1) has an object set + /// without an intra-set hard-core (gamma = 0) at a strictly positive + /// distance (rule 1 of the model integrability above). + opengeode_stochastic_stochastic_api void check_attractions_have_hard_cores( const ModelConfig& config ); namespace detail { /// For each term of the config, true if its parameter may be greater - /// than 1 (theta > 0) and keep the model integrable: always for a - /// single object term, and for a pairwise term only if all its object - /// sets have an intra-set hard-core at a strictly positive distance - /// (same rule as check_model_integrability). + /// than 1 (theta > 0) and keep the model integrable as far as the + /// config tells: always for a single object term (rule 2, which needs + /// the sampler laws, is applied by Model::forbid_attraction), and for + /// a pairwise term only if all its object sets have an intra-set + /// hard-core at a strictly positive distance (rule 1). [[nodiscard]] opengeode_stochastic_stochastic_api std::vector< bool > attraction_allowed( const ModelConfig& config ); } // namespace detail @@ -112,12 +126,12 @@ namespace geode ~Model() = default; /// Builds the terms of the config. Throws if the model is not - /// integrable (see check_model_integrability). + /// integrable (see check_attractions_have_hard_cores). Model( const ModelConfig& config, const ObjectSets< ObjectType >& object_sets, const SpatialDomain< ObjectType::dim >& domain ) { - check_model_integrability( config ); + check_attractions_have_hard_cores( config ); const auto attraction = detail::attraction_allowed( config ); for( const auto term : Indices{ config.terms } ) { @@ -145,15 +159,12 @@ namespace geode * Changes the parameters of all the terms, given in the order of the * terms (see thetas()). All of them are checked before any is * written: if one is refused, the model is unchanged. A hard-core term - * keeps -infinity; any other term needs a finite theta, at least - * log( GLOBAL_EPSILON ) (lower parameters make a hard-core at - * construction), and at most 0 if its attraction is not integrable + * keeps -infinity; any other term needs a finite theta (however + * negative: the parameters are in physical units), at most 0 if its + * attraction is not integrable * (see EnergyTerm::attraction_allowed). * The model is read-only during a simulation: change it between two * simulations, never while a sampler walks in another thread. - * Known limit: the energy weight of a segment length term is the whole - * length, so a positive theta with an unbounded length law (no - * max_value) gives a non integrable model. It is not refused here. */ void set_thetas( absl::Span< const double > thetas ) { @@ -172,6 +183,28 @@ namespace geode } } + /*! + * Forbids a positive theta on a term: its attraction is not + * integrable because of the laws of the set samplers, which the model + * config does not know (rule 2 of the model integrability: a length + * term on an unbounded length law). build_simulation_context calls + * it; a model built otherwise must call it itself. Throws, and leaves + * the term unchanged, if its theta is already positive. + */ + void forbid_attraction( index_t term ) + { + OpenGeodeStochasticStochasticException::check_exception( + term < nb_terms(), nullptr, OpenGeodeException::TYPE::data, + "[Model] Unknown term index ", term, " (", nb_terms(), + " terms)." ); + auto& energy_term = *terms_collection_.energy_terms()[term]; + if( !energy_term.is_hard_core() ) + { + check_attraction( energy_term, energy_term.theta(), false ); + } + energy_term.allow_attraction( false ); + } + /// Changes the parameter of one term, with the rules of set_thetas. /// A hard-core term cannot be changed. void set_theta( index_t term, double theta ) @@ -309,7 +342,16 @@ namespace geode double sum = 0.0; for( const auto& term : terms_collection_.energy_terms() ) { - sum += term_value( *term ); + const auto value = term_value( *term ); + // an infinite energy (a violated hard-core, or an ordinary + // term overflowing) forbids the configuration whatever the + // other terms: stopping here avoids +inf - inf = NaN when + // another term overflows to -inf + if( value == std::numeric_limits< double >::infinity() ) + { + return value; + } + sum += value; } return sum; } @@ -345,18 +387,24 @@ namespace geode std::isfinite( theta ), nullptr, OpenGeodeException::TYPE::data, "[Model] Term '", name, "': the parameter theta must be finite, not ", theta, "." ); + check_attraction( + energy_term, theta, energy_term.attraction_allowed() ); + } + + static void check_attraction( + const EnergyTerm< ObjectType >& energy_term, + double theta, + bool allowed ) + { OpenGeodeStochasticStochasticException::check_exception( - theta >= std::log( GLOBAL_EPSILON ), nullptr, - OpenGeodeException::TYPE::data, "[Model] Term '", name, - "': theta = ", theta, " is lower than log( GLOBAL_EPSILON ) = ", - std::log( GLOBAL_EPSILON ), - ", which would make it a hard-core at construction." ); - OpenGeodeStochasticStochasticException::check_exception( - theta <= 0. || energy_term.attraction_allowed(), nullptr, - OpenGeodeException::TYPE::data, "[Model] Attractive term '", - name, "' (theta = ", theta, - " > 0) is not integrable: its object sets require a hard-core " - "interaction (gamma = 0) at a strictly positive distance." ); + theta <= 0. || allowed, nullptr, OpenGeodeException::TYPE::data, + "[Model] Attractive term '", + energy_term.name().value_or( "unnamed" ), "' (theta = ", theta, + " > 0, gamma > 1) is not integrable: a pairwise term requires " + "a hard-core interaction (gamma = 0) at a strictly positive " + "distance on each of its object sets, a length term a bounded " + "length law (a finite max_value, not Gaussian) on each of its " + "object sets." ); } private: diff --git a/include/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.hpp b/include/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.hpp index 9ec7cdc..787539a 100644 --- a/include/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.hpp +++ b/include/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.hpp @@ -90,4 +90,9 @@ namespace geode double rotation_probability_; }; + /// True if the length law has a finite maximal value (a Gaussian has + /// none, even with a max_value): segments never exceed it. + [[nodiscard]] opengeode_stochastic_stochastic_api bool + is_bounded_length_law( + const DoubleSampler::DistributionDescription& length ); } // namespace geode \ No newline at end of file diff --git a/include/geode/stochastic/sampling/mcmc/helpers/simulation_context.hpp b/include/geode/stochastic/sampling/mcmc/helpers/simulation_context.hpp index 05a87fc..dbac0a8 100644 --- a/include/geode/stochastic/sampling/mcmc/helpers/simulation_context.hpp +++ b/include/geode/stochastic/sampling/mcmc/helpers/simulation_context.hpp @@ -100,6 +100,29 @@ namespace geode geode::ModelConfig model; }; + namespace detail + { + /// Indices of the terms whose attraction (theta > 0) the laws of the + /// set samplers make non integrable (rule 2 of the model + /// integrability, see model.hpp). None for these object types. + template < typename ObjectType > + [[nodiscard]] std::vector< index_t > attraction_forbidden_by_laws( + const SimulationContextConfig< ObjectType >& config ) + { + geode_unused( config ); + return {}; + } + + /// Segments: the length terms (SegmentLengthInsideBoxFeature) on an + /// object set whose length law is not bounded (see + /// is_bounded_length_law). The energy weight of a segment is its + /// whole length: with an unbounded law, theta > 0 (gamma > 1, which + /// favors long fractures) gives a non integrable model. + [[nodiscard]] opengeode_stochastic_stochastic_api std::vector< index_t > + attraction_forbidden_by_laws( + const SimulationContextConfig< OwnerSegment2D >& config ); + } // namespace detail + template < typename ObjectType > [[nodiscard]] geode::SimulationContext< ObjectType > build_simulation_context( @@ -138,6 +161,10 @@ namespace geode // ------------------------- context.model = geode::build_model< ObjectType >( config.model, *context.object_sets, *context.domain ); + for( const auto term : detail::attraction_forbidden_by_laws( config ) ) + { + context.model->forbid_attraction( term ); + } // ------------------------- // MH sampler diff --git a/include/geode/stochastic/sampling/mcmc/proposal/proposal_kernel.hpp b/include/geode/stochastic/sampling/mcmc/proposal/proposal_kernel.hpp index 090b114..c64f34e 100644 --- a/include/geode/stochastic/sampling/mcmc/proposal/proposal_kernel.hpp +++ b/include/geode/stochastic/sampling/mcmc/proposal/proposal_kernel.hpp @@ -138,7 +138,7 @@ namespace geode // Ensure total > 0 OpenGeodeStochasticStochasticException::check_exception( - total > GLOBAL_EPSILON, nullptr, + total > DIMENSIONLESS_EPSILON, nullptr, OpenGeodeException::TYPE::internal, "[ProposalKernel] - The probability of every moves is zero." ); diff --git a/src/geode/stochastic/CMakeLists.txt b/src/geode/stochastic/CMakeLists.txt index 93959e0..7a278be 100644 --- a/src/geode/stochastic/CMakeLists.txt +++ b/src/geode/stochastic/CMakeLists.txt @@ -41,6 +41,7 @@ add_geode_library( "models/energy_terms/energy_term_builder.cpp" "models/model.cpp" "sampling/random_engine.cpp" + "sampling/mcmc/helpers/simulation_context.cpp" "common.cpp" PUBLIC_HEADERS "applications/fractures.hpp" diff --git a/src/geode/stochastic/applications/observed_intensity.cpp b/src/geode/stochastic/applications/observed_intensity.cpp index 7619279..6358b83 100644 --- a/src/geode/stochastic/applications/observed_intensity.cpp +++ b/src/geode/stochastic/applications/observed_intensity.cpp @@ -145,14 +145,19 @@ namespace geode } const auto nb_expected = lambda * touching_domain_area( *domain, set.sampler ); + // numbers of objects: an absolute tolerance, independent of the units + const auto nb_unobserved = nb_expected - nb_fixed; OpenGeodeStochasticStochasticException::check_exception( - nb_expected - nb_fixed >= -GLOBAL_EPSILON, nullptr, + nb_unobserved >= -DIMENSIONLESS_EPSILON, nullptr, OpenGeodeException::TYPE::data, "[IntensityScope] Object set '", set.name, "': lambda = ", lambda, " gives ", nb_expected, " objects expected to touch the domain, fewer than its ", nb_fixed, " fixed objects touching it: lambda is underestimated." ); + // all observed up to the tolerance (e.g. the rounding of lambda * A): + // exactly 0 left, so that the observation term is a hard-core (only + // gamma = 0 is one) const auto observed_ratio = - nb_expected > 0. ? std::min( nb_fixed / nb_expected, 1. ) : 0.; + nb_unobserved > DIMENSIONLESS_EPSILON ? nb_fixed / nb_expected : 1.; Logger::info( "[IntensityScope] Object set '", set.name, "': ", nb_fixed, " fixed objects touch the domain, out of ", nb_expected, diff --git a/src/geode/stochastic/models/model.cpp b/src/geode/stochastic/models/model.cpp index e40979d..2ee4729 100644 --- a/src/geode/stochastic/models/model.cpp +++ b/src/geode/stochastic/models/model.cpp @@ -49,8 +49,9 @@ namespace bool is_hard_core( const geode::PairwiseTermConfig& term ) { - // gamma below epsilon is handled as 0 by the energy scale - if( term.gamma >= geode::GLOBAL_EPSILON ) + // only gamma = 0 is a hard-core: a weak repulsion does not bound the + // number of objects + if( term.gamma != 0. ) { return false; } @@ -106,7 +107,7 @@ namespace namespace geode { - void check_model_integrability( const ModelConfig& config ) + void check_attractions_have_hard_cores( const ModelConfig& config ) { const auto hard_cores = hard_core_sets( config ); for( const auto& term_cfg : config.terms ) diff --git a/src/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.cpp b/src/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.cpp index 84275e8..761938d 100644 --- a/src/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.cpp +++ b/src/geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include #include @@ -40,11 +42,7 @@ namespace void check_buffer_size( const geode::SpatialDomain< 2 >& domain, const geode::DoubleSampler::DistributionDescription& length ) { - const auto bounded = - length.max_value.has_value() - && length.distribution_type - != geode::Gaussian::distribution_type_static(); - if( !bounded ) + if( !geode::is_bounded_length_law( length ) ) { geode::Logger::warning( "[UniformSegmentSetSampler] Unbounded " "length distribution: segments longer than " @@ -73,6 +71,15 @@ namespace namespace geode { + bool is_bounded_length_law( + const DoubleSampler::DistributionDescription& length ) + { + return length.max_value.has_value() + && std::isfinite( length.max_value.value() ) + && length.distribution_type + != Gaussian::distribution_type_static(); + } + UniformSegmentSetSampler::UniformSegmentSetSampler( const SpatialDomain< 2 >& domain, const ObjectSamplerConfig< OwnerSegment2D >& config ) diff --git a/src/geode/stochastic/sampling/mcmc/helpers/simulation_context.cpp b/src/geode/stochastic/sampling/mcmc/helpers/simulation_context.cpp new file mode 100644 index 0000000..7e803fb --- /dev/null +++ b/src/geode/stochastic/sampling/mcmc/helpers/simulation_context.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include + +namespace +{ + bool is_length_term( const geode::EnergyTermConfig& term_config ) + { + const auto* term = + std::get_if< geode::SingleObjectTermConfig >( &term_config ); + return term != nullptr + && std::holds_alternative< + geode::SegmentLengthInsideBoxFeatureConfig >( + term->object_feature ); + } +} // namespace + +namespace geode +{ + namespace detail + { + std::vector< index_t > attraction_forbidden_by_laws( + const SimulationContextConfig< OwnerSegment2D >& config ) + { + std::vector< index_t > terms; + for( const auto term : Indices{ config.model.terms } ) + { + const auto& term_config = config.model.terms[term]; + if( !is_length_term( term_config ) ) + { + continue; + } + const auto& set_names = + std::get< SingleObjectTermConfig >( term_config ) + .object_set_names; + const auto unbounded = absl::c_any_of( + config.sets, [&set_names]( const auto& set ) { + return absl::c_linear_search( set_names, set.name ) + && !is_bounded_length_law( set.sampler.length ); + } ); + if( unbounded ) + { + terms.push_back( term ); + } + } + return terms; + } + } // namespace detail +} // namespace geode diff --git a/src/geode/stochastic/sampling/random_engine.cpp b/src/geode/stochastic/sampling/random_engine.cpp index 0cc8d75..5721d94 100644 --- a/src/geode/stochastic/sampling/random_engine.cpp +++ b/src/geode/stochastic/sampling/random_engine.cpp @@ -264,7 +264,7 @@ namespace geode // Uniform approximation for very small concentration (nearly // uniform) - if( law.concentration < geode::GLOBAL_EPSILON ) + if( law.concentration < geode::DIMENSIONLESS_EPSILON ) { UniformClosedOpen< double > uniform_dist; uniform_dist.max_value = 2.0 * M_PI; @@ -354,7 +354,7 @@ namespace geode // [xmin, xmax], written with the ratio x / xmin so that no power // of xmin or xmax overflows. is_valid() ensures that xmax is // finite when alpha <= 1. - if( std::fabs( law.alpha - 1.0 ) <= geode::GLOBAL_EPSILON + if( std::fabs( law.alpha - 1.0 ) <= geode::DIMENSIONLESS_EPSILON && std::isfinite( xmax ) ) { // bounded by the finite xmax: cannot overflow diff --git a/tests/stochastic/applications/test-fractures.cpp b/tests/stochastic/applications/test-fractures.cpp index 86bbd31..64c2e65 100644 --- a/tests/stochastic/applications/test-fractures.cpp +++ b/tests/stochastic/applications/test-fractures.cpp @@ -324,6 +324,146 @@ namespace geode::Logger::info( "--> SUCCESS!" ); } + geode::FractureProcessBuilder length_term_builder( + const geode::DoubleSampler::DistributionDescription& length, + double p21 ) + { + // NOLINTBEGIN(*-magic-numbers) + geode::FractureProcessBuilder fractures; + geode::SpatialDomainConfig< 2 > domain; + domain.min_point = geode::Point2D{ { 0., 0. } }; + domain.max_point = geode::Point2D{ { 10., 10. } }; + domain.buffer_size = 5.; + fractures.set_domain( domain ); + auto& fset = fractures.add_fracture_set( "fset", 0.1 ); + fset.sampler.length = length; + fset.sampler.azimuth.distribution_type = + geode::UniformClosed< double >::distribution_type_static(); + fset.sampler.azimuth.min_value = 0.; + fset.sampler.azimuth.max_value = 180.; + fractures.add_intensity( "fset", p21 ); + // NOLINTEND(*-magic-numbers) + return fractures; + } + + bool build_throws( const geode::FractureProcessBuilder& fractures ) + { + try + { + const auto context = fractures.build_simulation_context(); + return false; + } + catch( const geode::OpenGeodeException& ) + { + return true; + } + } + + bool set_theta_throws( geode::Model< geode::OwnerSegment2D >& model, + geode::index_t term, + double theta ) + { + try + { + model.set_theta( term, theta ); + return false; + } + catch( const geode::OpenGeodeException& ) + { + return true; + } + } + + geode::index_t length_term_index( + const geode::Model< geode::OwnerSegment2D >& model ) + { + return model.term_index( model.terms().get_term_uuid( "fset_p21" ) ); + } + + /// The energy weight of a fracture in a length term is its whole length: + /// with an unbounded length law, p21 > 1 (theta > 0, favoring long + /// fractures) gives a non integrable model; p21 <= 1 stays integrable. + void test_length_term_needs_bounded_length_law() + { + geode::Logger::info( "TEST - LENGTH TERM NEEDS A BOUNDED LENGTH LAW" ); + // NOLINTBEGIN(*-magic-numbers) + constexpr double ATTRACTIVE_P21{ 2. }; + constexpr double REPULSIVE_P21{ 0.5 }; + geode::DoubleSampler::DistributionDescription log_normal; + log_normal.distribution_type = + geode::TruncatedLogNormal::distribution_type_static(); + log_normal.mean = 0.; + log_normal.standard_deviation = 0.5; + log_normal.min_value = 0.5; + geode::OpenGeodeStochasticStochasticException::test( + build_throws( length_term_builder( log_normal, ATTRACTIVE_P21 ) ), + "[Fractures] p21 > 1 on an unbounded length law accepted" ); + + // p21 <= 1 on an unbounded law is integrable, but cannot become > 1 + auto repulsive = length_term_builder( log_normal, REPULSIVE_P21 ) + .build_simulation_context(); + const auto unbounded_term = length_term_index( *repulsive.model ); + geode::OpenGeodeStochasticStochasticException::test( + set_theta_throws( *repulsive.model, unbounded_term, 1. ), + "[Fractures] set_theta > 0 on an unbounded length law accepted" ); + geode::OpenGeodeStochasticStochasticException::test( + !set_theta_throws( *repulsive.model, unbounded_term, -1. ), + "[Fractures] set_theta < 0 on an unbounded length law refused" ); + + // an infinite max_value is no bound + log_normal.max_value = std::numeric_limits< double >::infinity(); + geode::OpenGeodeStochasticStochasticException::test( + !geode::is_bounded_length_law( log_normal ), + "[Fractures] a length law with an infinite max_value is bounded" ); + geode::OpenGeodeStochasticStochasticException::test( + build_throws( length_term_builder( log_normal, ATTRACTIVE_P21 ) ), + "[Fractures] p21 > 1 on a length law with an infinite max_value " + "accepted" ); + + log_normal.max_value = 4.; + auto bounded = length_term_builder( log_normal, ATTRACTIVE_P21 ) + .build_simulation_context(); + geode::OpenGeodeStochasticStochasticException::test( + !set_theta_throws( + *bounded.model, length_term_index( *bounded.model ), 1. ), + "[Fractures] set_theta > 0 on a bounded length law refused" ); + + geode::DoubleSampler::DistributionDescription power_law; + power_law.distribution_type = + geode::TruncatedPowerLaw::distribution_type_static(); + power_law.alpha = 2.; + power_law.min_value = 0.5; + power_law.max_value = 4.; + geode::OpenGeodeStochasticStochasticException::test( + !build_throws( length_term_builder( power_law, ATTRACTIVE_P21 ) ), + "[Fractures] p21 > 1 on a bounded power law refused" ); + + // a Gaussian is unbounded, even with a max_value + geode::DoubleSampler::DistributionDescription gaussian; + gaussian.distribution_type = + geode::Gaussian::distribution_type_static(); + gaussian.mean = 2.; + gaussian.standard_deviation = 0.5; + gaussian.max_value = 4.; + geode::OpenGeodeStochasticStochasticException::test( + build_throws( length_term_builder( gaussian, ATTRACTIVE_P21 ) ), + "[Fractures] p21 > 1 on a Gaussian length law accepted" ); + + // a set without length term keeps its unbounded law (warning only) + log_normal.max_value.reset(); + auto fractures = length_term_builder( power_law, ATTRACTIVE_P21 ); + auto& other = fractures.add_fracture_set( "other", 0.1 ); + other.sampler.length = log_normal; + other.sampler.azimuth.distribution_type = + geode::UniformClosed< double >::distribution_type_static(); + other.sampler.azimuth.min_value = 0.; + other.sampler.azimuth.max_value = 180.; + geode::OpenGeodeStochasticStochasticException::test( + !build_throws( fractures ), + "[Fractures] unbounded law on a set without length term refused" ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } } // namespace int main() @@ -338,6 +478,7 @@ int main() test_observed_fractures(); test_two_fracture_sets(); test_attractive_x_node_is_rejected(); + test_length_term_needs_bounded_length_law(); return 0; } catch( ... ) diff --git a/tests/stochastic/applications/test-observed-intensity.cpp b/tests/stochastic/applications/test-observed-intensity.cpp index 503bdf9..9deba78 100644 --- a/tests/stochastic/applications/test-observed-intensity.cpp +++ b/tests/stochastic/applications/test-observed-intensity.cpp @@ -281,6 +281,41 @@ namespace geode::Logger::info( "--> SUCCESS!" ); } + // lambda * |D| = 7 + gap with 7 fixed points: within DIMENSIONLESS_EPSILON + // of an object, all the objects are observed (rounding of lambda * |D|, + // e.g. 0.07 * 100 = 7.000000000000001, or a gap of a fraction of object). + void test_all_objects_observed_up_to_tolerance() + { + geode::Logger::info( + "TEST - ALL THE OBJECTS OBSERVED UP TO THE TOLERANCE" ); + // NOLINTNEXTLINE(*-magic-numbers) + for( const auto lambda : { 0.07, ( 7. + 5e-7 ) / 100. } ) + { + geode::PoissonProcessBuilder< geode::Point2D > poisson; + poisson.set_domain( square_domain( 10., 2. ) ); + auto& set_config = poisson.add_set( "set_A", lambda, std::nullopt, + geode::IntensityScope::all_objects ); + // NOLINTNEXTLINE(*-magic-numbers) + for( const auto i : geode::Range{ 7 } ) + { + set_config.fixed_objects.emplace_back( + geode::Point2D{ { 0.5 + i, 5. } } ); + } + const auto context = poisson.build_simulation_context(); + const auto& terms = context.model->terms(); + const auto& observation = + terms.get( terms.get_term_uuid( "set_A_observation" ) ); + geode::OpenGeodeStochasticStochasticException::test( + observation.is_hard_core(), + "[ObservedIntensity] all observed up to the tolerance (lambda " + "= ", + lambda, + "): the observation term should be a hard-core, theta = ", + observation.theta() ); + } + geode::Logger::info( "--> SUCCESS!" ); + } + // lambda * |D| = 5 < 10 fixed points void test_underestimated_density() { @@ -515,6 +550,7 @@ int main() test_touching_domain_area(); test_underestimated_density(); test_all_objects_observed(); + test_all_objects_observed_up_to_tolerance(); test_points_all_objects(); test_fractures_all_objects(); test_three_observation_cases(); diff --git a/tests/stochastic/models/energy_terms/test-pairwise-term.cpp b/tests/stochastic/models/energy_terms/test-pairwise-term.cpp index 9988527..28d04e9 100644 --- a/tests/stochastic/models/energy_terms/test-pairwise-term.cpp +++ b/tests/stochastic/models/energy_terms/test-pairwise-term.cpp @@ -139,7 +139,7 @@ void test_pairwise_term_zero_gamma( // --- energy double total = term->energy( pattern ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( total ), - "[PairwiseTerm] energy with gammadelta_energy_add( pattern, p4_ref ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( delta ), "[PairwiseTerm] delta_energy_add with " - "gammadelta_energy_add( pattern, buffer_ref ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( delta ), "[PairwiseTerm] delta_energy_add buffer with " - "gammadelta_energy_change( pattern, obj_id, p4_ref ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( delta ), "[PairwiseTerm] delta_energy_change VOI->VOI with " - "gammadelta_energy_change( pattern, old_buffer, p4_ref ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( delta ), "[PairwiseTerm] delta_energy_change buffer->VOI with " - "gammadelta_energy_change( pattern, obj_id, buffer_ref ); geode::OpenGeodeStochasticStochasticException::test( std::isinf( delta ), "[PairwiseTerm] delta_energy_change VOI->buffer with " - "gammadelta_energy_remove( pattern, obj_id ); geode::OpenGeodeStochasticStochasticException::test( delta == 0, "[PairwiseTerm] delta_energy_remove VOI with " - "gammaobserved_statistic( pattern ); @@ -310,12 +310,12 @@ int main() test_pairwise_term( pw_interaction_cfg, pattern, domain ); - pw_interaction_cfg.gamma = geode::GLOBAL_EPSILON; + pw_interaction_cfg.gamma = 1e-6; test_pairwise_term( pw_interaction_cfg, pattern, domain ); pw_interaction_cfg.gamma = 2.0; test_pairwise_term( pw_interaction_cfg, pattern, domain ); - pw_interaction_cfg.gamma = 0.9999 * geode::GLOBAL_EPSILON; + pw_interaction_cfg.gamma = 0.; test_pairwise_term_zero_gamma( pw_interaction_cfg, pattern, domain ); test_segment_intersection_statistic(); diff --git a/tests/stochastic/models/energy_terms/test-single-object-term-count.cpp b/tests/stochastic/models/energy_terms/test-single-object-term-count.cpp index 2907a6b..16cadb7 100644 --- a/tests/stochastic/models/energy_terms/test-single-object-term-count.cpp +++ b/tests/stochastic/models/energy_terms/test-single-object-term-count.cpp @@ -152,7 +152,7 @@ int main() // Test different lambda values including near-zero run_density_test( term_config, pattern, domain ); - term_config.lambda = geode::GLOBAL_EPSILON; + term_config.lambda = 1e-6; run_density_test( term_config, pattern, domain ); term_config.lambda = 100.0021165; run_density_test( term_config, pattern, domain ); @@ -175,7 +175,7 @@ int main() term_config.term_name = "zero"; term_config.object_set_names = { set_name }; - term_config.lambda = -geode::GLOBAL_EPSILON; + term_config.lambda = -1e-6; term_config.object_feature = geode::ObjectCountFeatureConfig{}; auto term = geode::build_energy_term< geode::Point2D >( diff --git a/tests/stochastic/models/energy_terms/test-single-object-term-length.cpp b/tests/stochastic/models/energy_terms/test-single-object-term-length.cpp index 76307aa..a58fbc2 100644 --- a/tests/stochastic/models/energy_terms/test-single-object-term-length.cpp +++ b/tests/stochastic/models/energy_terms/test-single-object-term-length.cpp @@ -181,7 +181,7 @@ int main() term_config.object_feature = object_length; run_intensity_test( term_config, pattern, domain, L0 ); - term_config.lambda = geode::GLOBAL_EPSILON; + term_config.lambda = 1e-6; run_intensity_test( term_config, pattern, domain, L0 ); term_config.lambda = 50.0; run_intensity_test( term_config, pattern, domain, L0 ); diff --git a/tests/stochastic/models/test-model-integrability.cpp b/tests/stochastic/models/test-model-integrability.cpp index 661fcb1..7b7c9fe 100644 --- a/tests/stochastic/models/test-model-integrability.cpp +++ b/tests/stochastic/models/test-model-integrability.cpp @@ -22,6 +22,7 @@ */ #include +#include namespace { @@ -43,7 +44,7 @@ namespace { try { - geode::check_model_integrability( config ); + geode::check_attractions_have_hard_cores( config ); return true; } catch( const geode::OpenGeodeException& ) @@ -99,6 +100,20 @@ namespace "integrable" ); } + void test_attractive_model_with_tiny_repulsion() + { + // NOLINTBEGIN(*-magic-numbers) + geode::ModelConfig config; + config.terms.emplace_back( + pairwise_term( "attraction", { { "A", "A" } }, 2., 1. ) ); + // a weak but positive repulsion does not bound the number of objects + config.terms.emplace_back( + pairwise_term( "spacing", { { "A", "A" } }, 1e-7, 0.1 ) ); + // NOLINTEND(*-magic-numbers) + check( config, false, + "attractive model with a tiny repulsion should not be integrable" ); + } + void test_attractive_model_with_hard_core() { // NOLINTBEGIN(*-magic-numbers) @@ -141,6 +156,41 @@ namespace "inter-set hard-core should not make the model integrable" ); // NOLINTEND(*-magic-numbers) } + + /// A length term on an unbounded length law cannot be attractive: the + /// model config does not know the laws, the simulation context does. + void test_length_term_needs_bounded_length_law() + { + // NOLINTBEGIN(*-magic-numbers) + geode::SimulationContextConfig< geode::OwnerSegment2D > config; + auto& set = config.add_set( "A" ); + set.sampler.length.distribution_type = + geode::TruncatedLogNormal::distribution_type_static(); + set.sampler.length.mean = 0.; + set.sampler.length.standard_deviation = 0.5; + set.sampler.length.min_value = 0.5; + config.model.terms.emplace_back( + pairwise_term( "spacing", { { "A", "A" } }, 0., 0.1 ) ); + geode::SingleObjectTermConfig length_term; + length_term.term_name = "A_p21"; + length_term.object_set_names = { "A" }; + length_term.lambda = 2.; + length_term.object_feature = + geode::SegmentLengthInsideBoxFeatureConfig{ 1. }; + config.model.terms.emplace_back( length_term ); + geode::OpenGeodeStochasticStochasticException::test( + geode::detail::attraction_forbidden_by_laws( config ) + == std::vector< geode::index_t >{ 1 }, + "[ModelIntegrability] length term on an unbounded length law " + "should not allow attraction" ); + + set.sampler.length.max_value = 4.; + geode::OpenGeodeStochasticStochasticException::test( + geode::detail::attraction_forbidden_by_laws( config ).empty(), + "[ModelIntegrability] length term on a bounded length law should " + "allow attraction" ); + // NOLINTEND(*-magic-numbers) + } } // namespace int main() @@ -153,8 +203,10 @@ int main() test_repulsive_model(); test_attractive_model_without_hard_core(); test_attractive_model_with_zero_hard_core(); + test_attractive_model_with_tiny_repulsion(); test_attractive_model_with_hard_core(); test_attractive_inter_set_model(); + test_length_term_needs_bounded_length_law(); geode::Logger::info( "--> SUCCESS!" ); return 0; diff --git a/tests/stochastic/models/test-model-parameters.cpp b/tests/stochastic/models/test-model-parameters.cpp index 9aeb69a..e965c26 100644 --- a/tests/stochastic/models/test-model-parameters.cpp +++ b/tests/stochastic/models/test-model-parameters.cpp @@ -79,6 +79,11 @@ namespace /// Terms: density A, hard-core (A,A), attraction (A,A), repulsion (A,B), /// density B. A has a hard-core: its attraction is integrable; B has none. + constexpr geode::index_t DENSITY_A{ 0 }; + constexpr geode::index_t ATTRACTION_A{ 2 }; + constexpr geode::index_t REPULSION_AB{ 3 }; + constexpr geode::index_t DENSITY_B{ 4 }; + std::vector< double > point_gammas() { // NOLINTNEXTLINE(*-magic-numbers) @@ -281,7 +286,6 @@ namespace message ); }; const auto nan = std::numeric_limits< double >::quiet_NaN(); - const auto too_small = std::log( geode::GLOBAL_EPSILON ) - 1.; check_refused( throws( [&model, &initial] { model.set_thetas( absl::MakeConstSpan( initial.data(), initial.size() - 1 ) ); @@ -295,7 +299,7 @@ namespace model.set_theta( 1, 0. ); } ), "set_theta on a hard-core" ); - for( const auto theta : { nan, INF, -INF, too_small } ) + for( const auto theta : { nan, INF, -INF } ) { check_refused( throws( [&model, &with, theta] { model.set_thetas( with( 0, theta ) ); @@ -339,10 +343,14 @@ namespace geode::build_simulation_context( point_config( point_gammas() ) ); auto& model = *context.model; // NOLINTBEGIN(*-magic-numbers) - model.set_theta( 2, 0.4 ); - model.set_theta( 0, 700. ); + model.set_theta( ATTRACTION_A, 0.4 ); + model.set_theta( DENSITY_A, 700. ); + // far below log( 1e-6 ): a tiny density, not a hard-core + model.set_theta( DENSITY_B, -700. ); geode::OpenGeodeStochasticStochasticException::test( - model.thetas()[2] == 0.4 && model.thetas()[0] == 700., + model.thetas()[ATTRACTION_A] == 0.4 + && model.thetas()[DENSITY_A] == 700. + && model.thetas()[DENSITY_B] == -700., "[ModelParameters] valid parameters not set" ); const auto energy = model.energy( *context.object_sets ); geode::OpenGeodeStochasticStochasticException::test( @@ -429,6 +437,27 @@ namespace geode::OpenGeodeStochasticStochasticException::test( model.thetas() == thetas, "[ModelParameters] fracture parameters not set" ); + // a huge density parameter overflows -theta * statistic to -inf: + // with the violated hard-core (+inf), the energy must stay +inf + // NOLINTNEXTLINE(*-magic-numbers) + model.set_theta( + model.term_index( model.terms().get_term_uuid( "A_p20" ) ), 1e308 ); + const auto overflow_energy = model.energy( state ); + geode::OpenGeodeStochasticStochasticException::test( + overflow_energy == INF, + "[ModelParameters] energy with a violated hard-core and an " + "overflowing term should be +inf, not ", + overflow_energy ); + // a birth crossing a fixed fracture: +inf, whatever the overflow + const geode::OwnerSegment2D crossing{ geode::Point2D{ { 4.5, 4. } }, + geode::Point2D{ { 4.5, 6. } } }; + const auto overflow_delta = model.delta_energy_add( state, + geode::ObjectRef< geode::OwnerSegment2D >{ crossing, set_id } ); + geode::OpenGeodeStochasticStochasticException::test( + overflow_delta == INF, + "[ModelParameters] birth crossing a fixed fracture with an " + "overflowing term should be +inf, not ", + overflow_delta ); geode::Logger::info( "--> SUCCESS!" ); } @@ -551,6 +580,77 @@ namespace // NOLINTEND(*-magic-numbers) geode::Logger::info( "--> SUCCESS!" ); } + + /// A tiny but positive gamma (e.g. a density of 1 per km2 in m-2) is an + /// ordinary term, not a hard-core. + void test_tiny_gamma_is_not_hard_core() + { + geode::Logger::info( "TEST - TINY GAMMA IS NOT A HARD-CORE" ); + auto gammas = point_gammas(); + // NOLINTNEXTLINE(*-magic-numbers) + gammas[DENSITY_B] = 1e-7; + auto context = + geode::build_simulation_context( point_config( gammas ) ); + const auto& term = *context.model->terms().energy_terms()[DENSITY_B]; + geode::OpenGeodeStochasticStochasticException::test( + !term.is_hard_core() + && term.theta() == std::log( gammas[DENSITY_B] ), + "[ModelParameters] gamma = 1e-7 should be an ordinary term" ); + geode::Logger::info( "--> SUCCESS!" ); + } + + /// Tiny gammas on a pairwise and a single object term: the energy deltas + /// match the energy variations and no energy is NaN along a walk. + void test_stability_with_tiny_gammas() + { + geode::Logger::info( "TEST - STABILITY WITH TINY GAMMAS" ); + // NOLINTNEXTLINE(*-magic-numbers) + for( const auto tiny : { 1e-12, 1e-300 } ) + { + auto gammas = point_gammas(); + gammas[REPULSION_AB] = tiny; + gammas[DENSITY_B] = tiny; + auto context = + geode::build_simulation_context( point_config( gammas ) ); + const auto& model = *context.model; + auto& state = *context.object_sets; + geode::RandomEngine engine; + engine.set_seed( "@model-parameters-tiny@" ); + // NOLINTNEXTLINE(*-magic-numbers) + for( const auto operation : geode::Range{ 200 } ) + { + geode_unused( operation ); + const auto set_index = random_index( engine, 2 ); + const auto set_id = + state.get_set_uuid( set_index == 0 ? "A" : "B" ); + const auto before = model.energy( state ); + auto object = context.set_samplers[set_index]->sample( engine ); + const auto delta = model.delta_energy_add( state, + geode::ObjectRef< geode::Point2D >{ object, set_id } ); + state.add_object( std::move( object ), set_id, false ); + const auto after = model.energy( state ); + geode::OpenGeodeStochasticStochasticException::test( + !std::isnan( after ) && !std::isnan( delta ), + "[ModelParameters] NaN energy with gamma = ", tiny ); + if( std::isfinite( before ) && std::isfinite( after ) ) + { + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( after - before - delta ) + < 1e-9 * ( 1. + std::fabs( after ) ), + "[ModelParameters] delta inconsistent with gamma = ", + tiny ); + } + } + // NOLINTNEXTLINE(*-magic-numbers) + context.mh_sampler->walk( state, engine, 2000 ); + geode::OpenGeodeStochasticStochasticException::test( + !std::isnan( model.energy( state ) ), + "[ModelParameters] NaN energy after a walk with gamma = ", + tiny ); + } + geode::Logger::info( "--> SUCCESS!" ); + } + } // namespace int main() @@ -563,6 +663,8 @@ int main() test_mh_sees_new_parameters(); test_rejections(); test_accepted(); + test_tiny_gamma_is_not_hard_core(); + test_stability_with_tiny_gammas(); test_fixed_objects_violating_hard_core(); test_fracture_parameters_match_rebuilt_model(); return 0;