Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion bindings/python/src/stochastic/applications/fractures.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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" ),
Expand Down
8 changes: 8 additions & 0 deletions bindings/python/tests/stochastic/test-py-simulation-errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
5 changes: 5 additions & 0 deletions include/geode/stochastic/applications/fractures.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
6 changes: 6 additions & 0 deletions include/geode/stochastic/common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 7 additions & 5 deletions include/geode/stochastic/models/energy_terms/energy_term.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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_ );
Expand Down Expand Up @@ -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_;
Expand Down
108 changes: 78 additions & 30 deletions include/geode/stochastic/models/model.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 } )
{
Expand Down Expand Up @@ -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 )
{
Expand All @@ -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 )
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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." );

Expand Down
1 change: 1 addition & 0 deletions src/geode/stochastic/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
9 changes: 7 additions & 2 deletions src/geode/stochastic/applications/observed_intensity.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 4 additions & 3 deletions src/geode/stochastic/models/model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

#include <geode/stochastic/sampling/direct/object_set_sampler/segment_set_sampler.hpp>

#include <cmath>

#include <geode/geometry/angle.hpp>
#include <geode/geometry/basic_objects/segment.hpp>
#include <geode/geometry/basic_objects/sphere.hpp>
Expand All @@ -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 "
Expand Down Expand Up @@ -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 )
Expand Down
Loading
Loading