diff --git a/README.md b/README.md index 0a77687..ef37c64 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ ## Documentation +* [Statistics and parameter inference (ABC shadow)](docs/statistics.md) + ## Questions For questions and support please use the official [slack](https://geode-solutions.com/#slack) and go to the channel #module_template. The issue list of this repo is exclusively for bug reports and feature requests. @@ -48,6 +50,7 @@ https://gitlab.univ-lorraine.fr/labos/iecl/drlib * Illian J, Penttinen A, Stoyan H, Stoyan D (2008) Statistical analysis and modelling of spatial point patterns.Wiley, Chichester.https://doi.org/10.1002/9780470725160 * Mardia KV, Jupp PE (2000) Directional statistics. Wiley, Chichester. https://doi.org/10.1002/9780470316979 * Mauldon M (1998) Estimating mean fracture trace length and density from observations in convex windows. Rock Mechanics and Rock Engineering 31(4):201–216. https://doi.org/10.1007/s006030050021 + * Stoica RS, Philippe A, Gregori P, Mateu J (2017) ABC Shadow algorithm: a tool for statistical analysis of spatial patterns. Statistics and Computing 27:1225–1238. https://doi.org/10.1007/s11222-016-9682-x * Stoica RS (2025) Random patterns and structures in spatial data. Chapman & Hall, CRC Press, Boca Raton.https://doi.org/10.1201/9781003380382 * Van Lieshout MNM (2000) Markov point processes and their applications. Imperial College Press, London.https://doi.org/10.1142/p060 diff --git a/docs/statistics.md b/docs/statistics.md new file mode 100644 index 0000000..91cd42c --- /dev/null +++ b/docs/statistics.md @@ -0,0 +1,170 @@ +# Statistics and parameter inference + +The models of OpenGeode-Stochastic are Gibbs point processes in the exponential +family: the energy of a configuration x is + + U(x) = - sum_i theta_i s_i(x), theta_i = log(gamma_i) + +where gamma_i is the parameter given to the builders (a density, an +intensity, an interaction parameter) and s_i the statistic of term i. A +hard-core term (gamma = 0) is a constraint, not a parameter. + +Each term has two statistics: + +- the **energy statistic**, computed on the extended domain (the domain plus + its buffer) and multiplied by theta in the energy; +- the **observed statistic**, computed inside the domain D only: + `Model::observed_statistics`. This is the value compared with the data. + +The inference compares observed statistics on both sides: t_obs measured on +the data in D, and t(y) measured in D on patterns y simulated on the extended +domain. This keeps the edge correction of the buffer and was validated on a +Strauss process (see below). + +## The statistics + +| Term (builder name) | Parameter | Observed statistic in D | Rule at the boundary of D | +|---|---|---|---| +| Point density `_density` (Poisson, Strauss) | lambda | number of points in D | a point on the boundary counts | +| Fracture density `_p20` | p20 (an activity, not the observed P20 once there are interactions) | number of fracture endpoints strictly inside D, divided by 2 | a fracture cut by the window counts 1/2 per endpoint inside; a crossing fracture counts 0 (Mauldon 1998); unbiased: its mean is lambda.\|D\| for a stationary Poisson process | +| Fracture intensity `_p21` | p21 (an activity) | total length of the fractures inside D (divided by a characteristic length of 1) | only the part inside D counts | +| Point interaction `pwint_` (Strauss) | gamma in [0, 1] (above 1 only on sets with a hard-core) | number of pairs closer than the distance whose middle is in D | location of a pair: the middle of the two points | +| Fracture spacing `_spacing` | hard-core | (constraint, not inferred) | | +| X-nodes `x_node_` | beta in [0, 1] (above 1 only on sets with a hard-core) | number of crossings between fractures of different sets, in D | location: the intersection point | +| Observation `_observation` | 1 - observed ratio | fixed objects only (see `IntensityScope`) | | + +The parameters are activities, not observed densities: with interactions, +the observed statistic of a density term differs from lambda.|D|. Only the +inference links the parameters to the observed statistics. + +### Measuring t_obs on an outcrop + +t(y) is always computed on simulated patterns with a buffer. Measuring t_obs +on the data needs the same rules, which is not always possible on an outcrop: + +- point and fracture counts, lengths and X-nodes only need the objects seen in + D (the intersection point of an X-node in D is seen with both traces); +- a distance interaction (Strauss pairs, spacing) counts a pair whose middle is + in D even if one of its objects lies outside D, within the interaction + distance: such a partner is not seen on the outcrop. Counting only the + visible pairs underestimates t_obs. Measurement tools for outcrops are + planned. + +## Inference: ABC shadow + +`run_abc_shadow` (`inference/abc_shadow.hpp`) samples the posterior of the +parameters of the named terms, given their observed statistics, with the ABC +shadow algorithm (Stoica et al., 2017). It works on a `SimulationContext` +built by a builder: + +```cpp +#include +#include + +auto context = strauss.build_simulation_context(); // starting parameters +geode::AbcShadowConfig config; +config.parameters = { + { "A_density", 99. }, // term name and t_obs; box and step by default + { "pwint_A", 19. } +}; +config.outer_iterations = 2000; +config.shadow_steps = 100; +config.mh_steps = 3000; +config.burn_in_steps = 200000; +geode::RandomEngine engine; +engine.set_seed( 42 ); +const auto trace = geode::run_abc_shadow( context, config, engine ); +// trace.thetas: one line of theta = log(gamma) per outer iteration +``` + +Each outer iteration simulates mh_steps Metropolis-Hastings steps at the +current theta, measures t_y in D, then runs a shadow chain of shadow_steps +proposals on theta with the acceptance ratio exp(), computed in log. The terms not named keep their parameters. + +### Defaults + +- **Prior box:** uniform. theta_max defaults to the integrability bound of + the term (`Model::theta_bounds`): 0 for an interaction whose attraction is + not integrable, no bound otherwise; a larger theta_max is refused. + theta_min defaults to -infinity (a flat prior on theta, log-uniform on + gamma). +- **Nothing observed:** t_obs = 0 pushes theta to -infinity (the data suggest + a hard-core): give a finite theta_min, which then regularizes; it is + refused otherwise. +- **Steps:** calibrated, unless all of them are given. A calibration that + fails (a statistic that does not vary) has already simulated: the context + state has moved, the model parameters have not. +- **Fixed objects:** refused for now (conditioning needs a constant + observation rate). + +### Tuning the inference + +The shadow chain uses t_y frozen during its shadow_steps = m proposals. Over +these proposals theta drifts by (h/2)(t_obs - t_y), with h = m.delta^2/12, and +the outer chain behaves like an unadjusted Langevin chain whose stability is +set by h.P, P ~ Cov(t) being the Fisher information: + +- h.P < 4: stable; h.P ~ 0.1 to 0.2: close to the posterior (the variance is + inflated by about (1 + hP/4)/(1 - hP/4), to first order); +- the shadow chain then accepts almost every proposal (~97 % in the tests): **do not tune + delta for a Metropolis acceptance rate such as 0.3**, which leads to the + unstable regime; +- a smaller delta is always stable but slower: the outer autocorrelation is + 1 - hP/2, so a delta ten times smaller costs a hundred times more + simulations. + +The **calibration** chooses delta for you: `calibration.iterations` (100 by +default, at least 30) simulations at the starting theta estimate Cov(t), then +delta_i = sqrt(12 s_eff / (m_i Cov_ii)) with s = `calibration.step_scale` +(0.2), m_i = m/K in `one_coordinate` mode (m in `all_coordinates`), and +s_eff = s divided by the largest row sum of |correlations|, so that +correlated statistics stay stable. The trace gives Cov(t), s_eff and the +deltas: reuse them in another run by giving the deltas. + +**Checking delta after a run:** `trace.estimated_step_scales` gives h.P per +parameter, with P estimated by Var(t_y)/2 over the trace (t_y varies with the +simulation noise and with theta). About 0.2 is right. Above 1, delta is too +large and the posterior is inflated; below 0.02, delta is too small and the +chain mixes slowly; `run_abc_shadow` logs a warning in both cases. Remedy: +rerun (the steps are recalibrated at the last theta, near the posterior), or +give the deltas, scaled by sqrt(0.2 / estimated h.P). + +Advice: + +- **mh_steps** must decorrelate successive t_y: the calibration warns when + their lag 1 correlation exceeds 0.5 (`trace.statistic_lag_correlations`). +- **Starting far from the posterior:** Cov(t) is estimated at the starting + theta, so delta can be off. Run a first call, discard its trace, then a + second call: it continues the chain from the last theta and recalibrates + near the posterior. +- **Correlated statistics** (density and pairs of a Strauss process) mix + slowly along their least informative direction: run more iterations and + check the effective sample size of each theta. +- **Continuing a chain:** the model keeps the last theta and the context its + last state; call `run_abc_shadow` again. + +### Validation + +- shadow chain alone: its stationary law is the truncated exponential + exp(theta (t_obs - t_y)) on the box; +- synthetic Gaussian family: the calibrated delta recovers the posterior, a + delta giving h.P = 2 inflates it as predicted, a much larger one fails; +- Poisson process: posterior of log(lambda) recovered (tolerances 0.25 + posterior standard deviation on the mean and 20 % on the standard + deviation around digamma(n) - log|D| and sqrt(trigamma(n)); measured: 0.5 % + and 0.7 %); +- Strauss process (simulated on the extended domain, statistics compared in + D on both sides): parameters recovered within the posterior + spread, spread consistent with the Fisher information, and at the posterior + mean the model gives the observed statistics on average + (`tests/stochastic/inference/test-abc-shadow-strauss.cpp`). + +## References + +- Mauldon M (1998) Estimating mean fracture trace length and density from + observations in convex windows. Rock Mechanics and Rock Engineering + 31(4):201–216. https://doi.org/10.1007/s006030050021 +- Stoica RS, Philippe A, Gregori P, Mateu J (2017) ABC Shadow algorithm: a tool + for statistical analysis of spatial patterns. Statistics and Computing + 27:1225–1238. https://doi.org/10.1007/s11222-016-9682-x diff --git a/include/geode/stochastic/inference/abc_shadow.hpp b/include/geode/stochastic/inference/abc_shadow.hpp index 1daba84..b0db8c7 100644 --- a/include/geode/stochastic/inference/abc_shadow.hpp +++ b/include/geode/stochastic/inference/abc_shadow.hpp @@ -19,4 +19,532 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * - */ \ No newline at end of file + */ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include + +/*! + * ABC shadow: approximate Bayesian computation of the parameters theta of a + * Gibbs model U(x) = -sum_i theta_i s_i(x), from statistics t_obs observed on + * a pattern (Stoica et al., 2017). + * + * The outer chain simulates a pattern y at the current theta, computes its + * statistics t_y, and moves theta by a shadow chain: a Metropolis chain on + * theta whose acceptance ratio, the ratio of the likelihoods of the data and + * of y, is exp( < theta' - theta, t_obs - t_y > ) and needs no normalizing + * constant. The shadow chain only approximates the ideal chain: see + * calibrate_deltas for the choice of its step. + * + * Stoica RS, Philippe A, Gregori P, Mateu J (2017) ABC Shadow algorithm: a + * tool for statistical analysis of spatial patterns. Statistics and Computing + * 27:1225-1238. https://doi.org/10.1007/s11222-016-9682-x + * See docs/statistics.md for the statistics and the tuning. + */ + +namespace geode +{ + class RandomEngine; +} // namespace geode + +namespace geode +{ + /// How the shadow chain perturbs theta at each proposal. + enum struct ShadowProposal + { + /// one coordinate drawn uniformly, the others unchanged + one_coordinate, + /// all the coordinates at once + all_coordinates + }; + + /// Uniform prior box and step of one parameter of the shadow chain. + struct ShadowParameter + { + /// lower bound of the box, included (may be -infinity) + double theta_min; + /// upper bound of the box, included (may be +infinity) + double theta_max; + /// width of the uniform step: theta_i + delta * ( U - 1/2 ) + double delta; + }; + + /// Counts of a shadow chain, per coordinate. + struct ShadowStepResult + { + /// proposals that moved this coordinate + std::vector< index_t > nb_proposals; + /// accepted among them + std::vector< index_t > nb_accepted; + }; + + /*! + * Runs the shadow chain: nb_proposals Metropolis proposals on thetas + * (updated in place), whether accepted or not. + * A proposal theta' = theta + delta * ( U - 1/2 ), on one coordinate or on + * all of them (see ShadowProposal), is refused outside the box (uniform + * prior, bounds included), and otherwise accepted if + * log U < < theta' - theta, statistic_differences > + * computed in log, never as a product of exponentials. + * @param[in,out] thetas the parameters, inside their boxes + * @param[in] statistic_differences t_obs - t_y, one per parameter + * @param[in] parameters box and step of each parameter + * @param[in] proposal one or all coordinates per proposal + * @param[in] nb_proposals number of proposals, not of acceptances + * @param[in] engine the only source of randomness: a chain is replayed + * with the same seed + * @return the proposals and acceptances of each coordinate (in + * all_coordinates mode, each proposal counts for every coordinate) + * @exception OpenGeodeException (data) if the sizes differ + */ + [[nodiscard]] ShadowStepResult opengeode_stochastic_stochastic_api + shadow_step( absl::Span< double > thetas, + absl::Span< const double > statistic_differences, + absl::Span< const ShadowParameter > parameters, + ShadowProposal proposal, + index_t nb_proposals, + RandomEngine& engine ); + /// Steps of the shadow chain calibrated by calibrate_deltas. + struct DeltaCalibrationResult + { + /// one step per parameter + std::vector< double > deltas; + /// step_scale divided by the Gershgorin bound of the correlations + double effective_step_scale{ 0 }; + }; + + /*! + * Steps of the shadow chain from the covariance of the statistics. + * + * t_y is frozen during the shadow chain: over m proposals of step delta + * on a coordinate, theta drifts on average by ( h / 2 ) ( t_obs - t_y ) + * with h = m delta^2 / 12, plus a noise of variance h. As + * t_obs - t_y ~ -P ( theta - theta* ), P ~ Cov( t ) the Fisher information, + * the outer chain is an unadjusted Langevin chain: stable only if h.P < 4, + * and close to the posterior for h.P ~ 0.1 - 0.2 (variance inflated by + * ( 1 + hP / 4 ) / ( 1 - hP / 4 ), to first order only: 1.57 measured + * against 1.73 predicted at h.P = 2). This holds if delta |t_obs - t_y| is + * small (shadow acceptance close to 1, not a Metropolis target such as + * 0.3) and if the outer simulations decorrelate t_y. + * + * delta_i = sqrt( 12 s_eff / ( m_i Cov_ii ) ), with m_i = m / K (as a + * double) in one_coordinate mode, m in all_coordinates mode, and + * s_eff = step_scale / max_i sum_j |Corr_ij|, a Gershgorin bound on the + * largest eigenvalue of the correlation matrix (1 without correlation, + * 1 + |rho| for two statistics): the most informative direction keeps + * h.P <= step_scale. The least informative one mixes slowly when the + * statistics are strongly correlated. + * @param[in] covariance Cov( t ), K x K, row-major (Cov( t_i, t_j ) at + * i * K + j) + * @param[in] shadow_steps m, the number of proposals of a shadow chain + * @param[in] proposal one or all coordinates per proposal + * @param[in] step_scale h.P aimed at, e.g. 0.2 + * @exception OpenGeodeException (data) if the covariance is not square, + * a variance is not positive or too small for a finite step, step_scale + * is not positive or m is zero + */ + [[nodiscard]] DeltaCalibrationResult opengeode_stochastic_stochastic_api + calibrate_deltas( absl::Span< const double > covariance, + index_t shadow_steps, + ShadowProposal proposal, + double step_scale ); + /// One inferred parameter: the term, its observed statistic and, + /// optionally, its prior box and step. + struct AbcParameterConfig + { + /// name of the term in the model (e.g. "_density") + std::string term_name; + /// t_obs: the statistic of the term measured on the data (see + /// Model::observed_statistics), non negative + double observed_statistic{ 0 }; + /// lower bound of the uniform prior on theta; -infinity by default (a + /// flat prior on theta, log-uniform on gamma). Required if the + /// observed statistic is 0: the data then push theta to -infinity + /// (they suggest a hard-core) and only this bound regularizes. + std::optional< double > theta_min; + /// upper bound of the prior; by default the integrability bound of the + /// term (Model::theta_bounds), which it cannot exceed + std::optional< double > theta_max; + /// step of the shadow chain; calibrated by default (see + /// calibrate_deltas). Give all the deltas or none. + std::optional< double > delta; + }; + + /// Calibration of the steps, used when no delta is given. + struct DeltaCalibration + { + /// simulations at the starting theta to estimate Cov( t ); at least + /// 30 (with very few, the variance can be underestimated a thousand + /// times, and the chain made unstable) + index_t iterations{ 100 }; + /// h.P aimed at (see calibrate_deltas) + double step_scale{ 0.2 }; + }; + + /// Configuration of run_abc_shadow. + struct AbcShadowConfig + { + /// the inferred terms, at least one; the others keep their parameters + std::vector< AbcParameterConfig > parameters; + /// iterations of the outer chain, one trace line each + index_t outer_iterations{ 0 }; + /// m: proposals of each shadow chain + index_t shadow_steps{ 0 }; + /// Metropolis-Hastings steps between two outer iterations: enough to + /// decorrelate t_y (see the lag 1 correlations of the trace) + index_t mh_steps{ 0 }; + /// Metropolis-Hastings steps before the calibration and the chain + index_t burn_in_steps{ 0 }; + /// one coordinate per proposal (default) or all of them + ShadowProposal proposal{ ShadowProposal::one_coordinate }; + /// used only when no delta is given + DeltaCalibration calibration; + }; + + /// Result of run_abc_shadow, in memory. + struct AbcTrace + { + /// inferred terms, in the order of the configuration + std::vector< std::string > term_names; + /// theta after each outer iteration + std::vector< std::vector< double > > thetas; + /// t_y that guided each outer iteration + std::vector< std::vector< double > > statistics; + /// acceptance rate of the shadow chain of each outer iteration + std::vector< double > acceptance_rates; + /// steps used, given or calibrated: reusable for another run + std::vector< double > deltas; + /// Cov( t ) of the calibration, K x K row-major (empty without + /// calibration) + std::vector< double > statistic_covariance; + /// s_eff of the calibration (0 without calibration) + double effective_step_scale{ 0 }; + /// lag 1 correlation of t_y during the calibration, per statistic: + /// above 0.5, mh_steps is too small (empty without calibration) + std::vector< double > statistic_lag_correlations; + /// h.P estimated after the run, per parameter: h = m_i delta_i^2 / 12 + /// and P ~ Var( t_y ) / 2 over the trace (t_y varies with the + /// simulation noise, P, and with theta, about P). About 0.2 when + /// delta is well calibrated; above 1, delta is too large (posterior + /// inflated); below 0.02, too small (slow chain): a warning is logged, + /// rerun (it recalibrates at the last theta) or give the deltas + std::vector< double > estimated_step_scales; + }; + + namespace detail + { + struct AbcSetup + { + std::vector< index_t > terms; + std::vector< ShadowParameter > parameters; + std::vector< double > observed; + bool calibrate{ false }; + }; + + template < typename ObjectType > + AbcSetup check_abc_config( + const SimulationContext< ObjectType >& context, + const AbcShadowConfig& config ) + { + constexpr auto infinity = std::numeric_limits< double >::infinity(); + OpenGeodeStochasticStochasticException::check_exception( + !config.parameters.empty(), nullptr, + OpenGeodeException::TYPE::data, + "[ABCShadow] There is no parameter to infer." ); + const auto& model = *context.model; + const auto names = model.term_names(); + const auto bounds = model.theta_bounds(); + const auto thetas = model.thetas(); + AbcSetup setup; + absl::flat_hash_set< index_t > seen; + index_t nb_deltas{ 0 }; + for( const auto& parameter : config.parameters ) + { + const auto& name = parameter.term_name; + index_t term{ 0 }; + while( term < names.size() && names[term] != name ) + { + term++; + } + OpenGeodeStochasticStochasticException::check_exception( + term < names.size(), nullptr, + OpenGeodeException::TYPE::data, + "[ABCShadow] Unknown term '", name, "'." ); + OpenGeodeStochasticStochasticException::check_exception( + seen.insert( term ).second, nullptr, + OpenGeodeException::TYPE::data, "[ABCShadow] Term '", name, + "' is given twice." ); + OpenGeodeStochasticStochasticException::check_exception( + !model.terms().energy_terms()[term]->is_hard_core(), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Term '", name, + "' is a hard-core: its parameter cannot be inferred." ); + const auto observed = parameter.observed_statistic; + OpenGeodeStochasticStochasticException::check_exception( + observed >= 0. && std::isfinite( observed ), nullptr, + OpenGeodeException::TYPE::data, "[ABCShadow] Term '", name, + "': the observed statistic ", observed, + " is negative or not finite (the statistics are non " + "negative)." ); + const auto theta_max = + parameter.theta_max.value_or( bounds[term].max ); + OpenGeodeStochasticStochasticException::check_exception( + theta_max <= bounds[term].max, nullptr, + OpenGeodeException::TYPE::data, "[ABCShadow] Term '", name, + "': theta_max = ", theta_max, " is above the bound ", + bounds[term].max, + " of the term: an attraction that is not integrable (see " + "Model::theta_bounds)." ); + OpenGeodeStochasticStochasticException::check_exception( + observed > 0. + || ( parameter.theta_min + && std::isfinite( *parameter.theta_min ) ), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Term '", name, + "': nothing observed (statistic 0): the data suggest a " + "hard-core and push theta to -infinity; give a finite " + "theta_min, the lower bound that regularizes." ); + const auto theta_min = + parameter.theta_min.value_or( -infinity ); + OpenGeodeStochasticStochasticException::check_exception( + theta_min < theta_max && theta_min < infinity + && theta_max > -infinity, + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Term '", name, "': theta_min = ", theta_min, + " should be below theta_max = ", theta_max, "." ); + OpenGeodeStochasticStochasticException::check_exception( + thetas[term] >= theta_min && thetas[term] <= theta_max, + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Term '", name, "': the starting theta ", + thetas[term], + " of the model is outside the box [theta_min = ", theta_min, + ", theta_max = ", theta_max, "]." ); + if( parameter.delta ) + { + nb_deltas++; + OpenGeodeStochasticStochasticException::check_exception( + *parameter.delta > 0. + && std::isfinite( *parameter.delta ), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Term '", name, + "': delta = ", *parameter.delta, + " should be positive and finite." ); + } + setup.terms.push_back( term ); + setup.parameters.push_back( + { theta_min, theta_max, parameter.delta.value_or( 0. ) } ); + setup.observed.push_back( observed ); + } + OpenGeodeStochasticStochasticException::check_exception( + nb_deltas == 0 || nb_deltas == config.parameters.size(), + nullptr, OpenGeodeException::TYPE::data, "[ABCShadow] ", + nb_deltas, " deltas given for ", config.parameters.size(), + " parameters: give them for all the parameters or none (then " + "they are calibrated)." ); + setup.calibrate = nb_deltas == 0; + OpenGeodeStochasticStochasticException::check_exception( + config.outer_iterations > 0, nullptr, + OpenGeodeException::TYPE::data, + "[ABCShadow] The number of outer iterations should be " + "positive." ); + OpenGeodeStochasticStochasticException::check_exception( + config.shadow_steps > 0, nullptr, + OpenGeodeException::TYPE::data, + "[ABCShadow] The number of shadow steps should be positive." ); + OpenGeodeStochasticStochasticException::check_exception( + config.mh_steps > 0, nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] The number of Metropolis-Hastings steps per outer " + "iteration should be positive." ); + if( setup.calibrate ) + { + constexpr index_t MIN_CALIBRATION_ITERATIONS{ 30 }; + OpenGeodeStochasticStochasticException::check_exception( + config.calibration.iterations >= MIN_CALIBRATION_ITERATIONS, + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] The calibration needs at least ", + MIN_CALIBRATION_ITERATIONS, " iterations, not ", + config.calibration.iterations, "." ); + OpenGeodeStochasticStochasticException::check_exception( + config.calibration.step_scale > 0. + && std::isfinite( config.calibration.step_scale ), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] The step scale of the calibration should be " + "positive, not ", + config.calibration.step_scale, "." ); + } + const auto& object_sets = *context.object_sets; + for( const auto& set_name : object_sets.set_names() ) + { + const auto nb_fixed = + object_sets.get_set( object_sets.get_set_uuid( set_name ) ) + .nb_fixed_objects(); + OpenGeodeStochasticStochasticException::check_exception( + nb_fixed == 0, nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] Object set '", set_name, "' has ", nb_fixed, + " fixed objects: conditioning by fixed objects needs a " + "constant observation rate, not supported yet." ); + } + return setup; + } + + template < typename ObjectType > + std::vector< double > statistics_of_terms( + const SimulationContext< ObjectType >& context, + absl::Span< const index_t > terms ) + { + const auto all = + context.model->observed_statistics( *context.object_sets ); + std::vector< double > values; + values.reserve( terms.size() ); + for( const auto term : terms ) + { + values.push_back( all[term] ); + } + return values; + } + + /// Covariance (unbiased, row-major) and lag 1 correlations of the + /// statistics of successive simulations. + void opengeode_stochastic_stochastic_api calibration_moments( + const std::vector< std::vector< double > >& samples, + AbcTrace& trace ); + + /// Fills AbcTrace::estimated_step_scales and warns when delta is + /// badly calibrated. + void opengeode_stochastic_stochastic_api estimate_step_scales( + index_t shadow_steps, ShadowProposal proposal, AbcTrace& trace ); + } // namespace detail + + /*! + * Infers the parameters of the named terms of the model of a simulation + * context by the ABC shadow algorithm (Stoica et al., 2017). + * + * The configuration is checked first, before any simulation (see + * AbcParameterConfig: the default box is the integrability domain of the + * term, and its prior is uniform; the starting theta is the current one + * of the model). Then: + * - burn_in_steps Metropolis-Hastings steps; + * - if no delta is given, calibration: calibration.iterations times + * mh_steps steps at the starting theta, fixed, give Cov( t ) and the + * steps (calibrate_deltas), frozen afterwards; + * - outer_iterations times: the model takes theta, mh_steps steps from + * the current state give t_y (Model::observed_statistics, in the + * domain), and a shadow chain of shadow_steps proposals moves theta + * (shadow_step). One trace line per iteration. + * At the end, AbcTrace::estimated_step_scales checks the steps (a warning + * if they are badly calibrated), the model carries the last theta of the + * trace and the context its last state: a second call continues the chain, + * and recalibrates the steps near the posterior (useful when the starting + * theta is far from it). + * The terms not inferred keep their parameters. Object sets with fixed + * objects are refused until the observation rate is constant. + * @exception OpenGeodeException (data) for an invalid configuration + */ + template < typename ObjectType > + [[nodiscard]] AbcTrace run_abc_shadow( + SimulationContext< ObjectType >& context, + const AbcShadowConfig& config, + RandomEngine& engine ) + { + auto setup = detail::check_abc_config( context, config ); + auto& model = *context.model; + auto& state = *context.object_sets; + const auto nb_parameters = setup.terms.size(); + AbcTrace trace; + const auto names = model.term_names(); + for( const auto term : setup.terms ) + { + trace.term_names.push_back( names[term] ); + } + const auto all_thetas = model.thetas(); + std::vector< double > thetas; + for( const auto term : setup.terms ) + { + thetas.push_back( all_thetas[term] ); + } + if( config.burn_in_steps > 0 ) + { + context.mh_sampler->walk( state, engine, config.burn_in_steps ); + } + if( setup.calibrate ) + { + std::vector< std::vector< double > > samples; + samples.reserve( config.calibration.iterations ); + for( const auto iteration : Range{ config.calibration.iterations } ) + { + geode_unused( iteration ); + context.mh_sampler->walk( state, engine, config.mh_steps ); + samples.push_back( + detail::statistics_of_terms( context, setup.terms ) ); + } + detail::calibration_moments( samples, trace ); + const auto calibration = calibrate_deltas( + trace.statistic_covariance, config.shadow_steps, + config.proposal, config.calibration.step_scale ); + trace.effective_step_scale = calibration.effective_step_scale; + for( const auto parameter : Range{ nb_parameters } ) + { + setup.parameters[parameter].delta = + calibration.deltas[parameter]; + } + } + for( const auto& parameter : setup.parameters ) + { + trace.deltas.push_back( parameter.delta ); + } + trace.thetas.reserve( config.outer_iterations ); + trace.statistics.reserve( config.outer_iterations ); + trace.acceptance_rates.reserve( config.outer_iterations ); + std::vector< double > differences( nb_parameters ); + for( const auto iteration : Range{ config.outer_iterations } ) + { + geode_unused( iteration ); + for( const auto parameter : Range{ nb_parameters } ) + { + model.set_theta( setup.terms[parameter], thetas[parameter] ); + } + context.mh_sampler->walk( state, engine, config.mh_steps ); + auto statistics = + detail::statistics_of_terms( context, setup.terms ); + for( const auto parameter : Range{ nb_parameters } ) + { + differences[parameter] = + setup.observed[parameter] - statistics[parameter]; + } + const auto result = shadow_step( absl::MakeSpan( thetas ), + differences, setup.parameters, config.proposal, + config.shadow_steps, engine ); + index_t nb_accepted{ 0 }; + index_t nb_proposed{ 0 }; + for( const auto parameter : Range{ nb_parameters } ) + { + nb_accepted += result.nb_accepted[parameter]; + nb_proposed += result.nb_proposals[parameter]; + } + trace.acceptance_rates.push_back( + static_cast< double >( nb_accepted ) + / static_cast< double >( nb_proposed ) ); + trace.thetas.push_back( thetas ); + trace.statistics.push_back( std::move( statistics ) ); + } + for( const auto parameter : Range{ nb_parameters } ) + { + model.set_theta( setup.terms[parameter], thetas[parameter] ); + } + detail::estimate_step_scales( + config.shadow_steps, config.proposal, trace ); + return trace; + } +} // namespace geode diff --git a/include/geode/stochastic/inference/statistics_tools.hpp b/include/geode/stochastic/inference/statistics_tools.hpp index 867def3..77ba736 100644 --- a/include/geode/stochastic/inference/statistics_tools.hpp +++ b/include/geode/stochastic/inference/statistics_tools.hpp @@ -22,13 +22,78 @@ */ #pragma once +#include + #include +#include + +#include #include #include namespace geode::statistics { + /// Means and covariance of samples of K values each. + struct SampleMoments + { + /// K means + std::vector< double > means; + /// unbiased covariance (divided by the number of samples minus 1), + /// K x K row-major + std::vector< double > covariance; + }; + + /*! + * Means and covariance of samples already in memory (e.g. the thetas or + * the statistics of an AbcTrace). To follow the statistics of the model + * terms during a simulation without storing them, use StatisticsTracker + * instead (means and variances only). + * @param[in] samples at least two samples of the same size K + * @exception OpenGeodeException (data) if there are fewer than 2 samples + */ + inline SampleMoments sample_moments( + absl::Span< const std::vector< double > > samples ) + { + const auto nb_samples = samples.size(); + OpenGeodeStochasticStochasticException::check_exception( + nb_samples >= 2, nullptr, OpenGeodeException::TYPE::data, + "[Statistics] Moments need at least 2 samples, not ", nb_samples, + "." ); + const auto nb_values = samples.front().size(); + SampleMoments moments; + moments.means.assign( nb_values, 0. ); + for( const auto& sample : samples ) + { + for( const auto value : Range{ nb_values } ) + { + moments.means[value] += sample[value]; + } + } + for( auto& mean : moments.means ) + { + mean /= static_cast< double >( nb_samples ); + } + moments.covariance.assign( nb_values * nb_values, 0. ); + for( const auto& sample : samples ) + { + for( const auto row : Range{ nb_values } ) + { + const auto deviation = sample[row] - moments.means[row]; + for( const auto column : Range{ nb_values } ) + { + moments.covariance[row * nb_values + column] += + deviation * ( sample[column] - moments.means[column] ); + } + } + } + for( auto& value : moments.covariance ) + { + value /= static_cast< double >( nb_samples - 1 ); + } + return moments; + } + template < typename ObjectType > void validate( const StatisticsTracker< ObjectType >& tracker, const TargetStatistics< ObjectType >& targets ) diff --git a/include/geode/stochastic/models/model.hpp b/include/geode/stochastic/models/model.hpp index c221fd7..c9c7033 100644 --- a/include/geode/stochastic/models/model.hpp +++ b/include/geode/stochastic/models/model.hpp @@ -116,6 +116,17 @@ namespace geode attraction_allowed( const ModelConfig& config ); } // namespace detail + /// Interval of the valid parameters theta of a term (bounds included). + struct ThetaBounds + { + /// -infinity: excluded (theta must be finite), except for a + /// hard-core, whose theta is fixed at -infinity + double min; + /// 0 if the attraction of the term is not integrable, +infinity + /// otherwise, -infinity for a hard-core + double max; + }; + template < typename ObjectType > class Model { @@ -155,6 +166,26 @@ namespace geode } ); } + /*! + * Valid parameters of each term, in the order of the terms: the single + * source of the rules of set_thetas and of the prior box of an + * inference. A hard-core term is fixed at -infinity ({-inf, -inf}); + * any other term takes a finite theta, at most 0 if its attraction is + * not integrable (see EnergyTerm::attraction_allowed), with no upper + * bound otherwise. The lower bound -infinity is excluded (theta must + * be finite). + */ + [[nodiscard]] std::vector< ThetaBounds > theta_bounds() const + { + std::vector< ThetaBounds > bounds; + bounds.reserve( nb_terms() ); + for( const auto& term : terms_collection_.energy_terms() ) + { + bounds.push_back( term_bounds( *term ) ); + } + return bounds; + } + /*! * Changes the parameters of all the terms, given in the order of the * terms (see thetas()). All of them are checked before any is @@ -369,6 +400,18 @@ namespace geode return values; } + static ThetaBounds term_bounds( + const EnergyTerm< ObjectType >& energy_term ) + { + constexpr auto infinity = std::numeric_limits< double >::infinity(); + if( energy_term.is_hard_core() ) + { + return { -infinity, -infinity }; + } + return { -infinity, + energy_term.attraction_allowed() ? infinity : 0. }; + } + static void check_theta( const EnergyTerm< ObjectType >& energy_term, double theta ) { @@ -388,7 +431,7 @@ namespace geode "[Model] Term '", name, "': the parameter theta must be finite, not ", theta, "." ); check_attraction( - energy_term, theta, energy_term.attraction_allowed() ); + energy_term, theta, theta <= term_bounds( energy_term ).max ); } static void check_attraction( diff --git a/src/geode/stochastic/CMakeLists.txt b/src/geode/stochastic/CMakeLists.txt index 7a278be..954b50c 100644 --- a/src/geode/stochastic/CMakeLists.txt +++ b/src/geode/stochastic/CMakeLists.txt @@ -26,6 +26,7 @@ add_geode_library( "applications/observed_intensity.cpp" "applications/poisson_process.cpp" "applications/strauss_process.cpp" + "inference/abc_shadow.cpp" "spatial/object_set.cpp" "spatial/object_sets.cpp" "spatial/object_neighborhood.cpp" @@ -48,7 +49,7 @@ add_geode_library( "applications/observed_intensity.hpp" "applications/poisson_process.hpp" "applications/strauss_process.hpp" - #"inference/abc_shadow.hpp" + "inference/abc_shadow.hpp" "inference/statistics_tools.hpp" "inference/statistics_tracker.hpp" "inference/target_statistics.hpp" diff --git a/src/geode/stochastic/inference/abc_shadow.cpp b/src/geode/stochastic/inference/abc_shadow.cpp new file mode 100644 index 0000000..4524f6f --- /dev/null +++ b/src/geode/stochastic/inference/abc_shadow.cpp @@ -0,0 +1,319 @@ +/* + * 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 +#include + +#include +#include + +#include +#include +#include + +namespace +{ + double sample_step( double delta, geode::RandomEngine& engine ) + { + geode::UniformClosedOpen< double > uniform; + uniform.min_value = -0.5; + uniform.max_value = 0.5; + return delta * engine.sample_uniform( uniform ); + } + + bool is_in_box( double theta, const geode::ShadowParameter& parameter ) + { + return theta >= parameter.theta_min && theta <= parameter.theta_max; + } + + /// m_i: the proposals that move one coordinate during a shadow chain of + /// shadow_steps proposals, m / K (as a double) in one_coordinate mode + double proposals_per_coordinate( geode::index_t shadow_steps, + geode::ShadowProposal proposal, + geode::index_t nb_parameters ) + { + const auto proposals = static_cast< double >( shadow_steps ); + return proposal == geode::ShadowProposal::one_coordinate + ? proposals / static_cast< double >( nb_parameters ) + : proposals; + } + + /// One proposal on a coordinate drawn uniformly. + void propose_one_coordinate( absl::Span< double > thetas, + absl::Span< const double > statistic_differences, + absl::Span< const geode::ShadowParameter > parameters, + const geode::UniformClosedOpen< geode::index_t >& coordinate_law, + geode::RandomEngine& engine, + geode::ShadowStepResult& result ) + { + const auto coordinate = engine.sample_uniform( coordinate_law ); + const auto step = sample_step( parameters[coordinate].delta, engine ); + result.nb_proposals[coordinate]++; + const auto proposed = thetas[coordinate] + step; + if( !is_in_box( proposed, parameters[coordinate] ) ) + { + return; + } + const auto log_ratio = step * statistic_differences[coordinate]; + if( engine.sample_log() < log_ratio ) + { + thetas[coordinate] = proposed; + result.nb_accepted[coordinate]++; + } + } + + /// One proposal on all the coordinates at once, accepted or refused as a + /// whole. + void propose_all_coordinates( absl::Span< double > thetas, + absl::Span< const double > statistic_differences, + absl::Span< const geode::ShadowParameter > parameters, + std::vector< double >& steps, + geode::RandomEngine& engine, + geode::ShadowStepResult& result ) + { + bool in_box{ true }; + double log_ratio{ 0. }; + for( const auto coordinate : geode::Range{ thetas.size() } ) + { + steps[coordinate] = + sample_step( parameters[coordinate].delta, engine ); + result.nb_proposals[coordinate]++; + in_box = in_box + && is_in_box( thetas[coordinate] + steps[coordinate], + parameters[coordinate] ); + log_ratio += steps[coordinate] * statistic_differences[coordinate]; + } + if( !in_box || !( engine.sample_log() < log_ratio ) ) + { + return; + } + for( const auto coordinate : geode::Range{ thetas.size() } ) + { + thetas[coordinate] += steps[coordinate]; + result.nb_accepted[coordinate]++; + } + } +} // namespace + +namespace geode +{ + ShadowStepResult shadow_step( absl::Span< double > thetas, + absl::Span< const double > statistic_differences, + absl::Span< const ShadowParameter > parameters, + ShadowProposal proposal, + index_t nb_proposals, + RandomEngine& engine ) + { + const auto nb_parameters = thetas.size(); + OpenGeodeStochasticStochasticException::check_exception( + statistic_differences.size() == nb_parameters + && parameters.size() == nb_parameters && nb_parameters > 0, + nullptr, OpenGeodeException::TYPE::data, "[ABCShadow] ", + nb_parameters, " parameters, ", statistic_differences.size(), + " statistic differences and ", parameters.size(), + " boxes: the sizes should be equal and non zero." ); + ShadowStepResult result; + result.nb_proposals.assign( nb_parameters, 0 ); + result.nb_accepted.assign( nb_parameters, 0 ); + if( proposal == ShadowProposal::one_coordinate ) + { + UniformClosedOpen< index_t > coordinate_law; + coordinate_law.min_value = 0; + coordinate_law.max_value = static_cast< index_t >( nb_parameters ); + for( const auto step : Range{ nb_proposals } ) + { + geode_unused( step ); + propose_one_coordinate( thetas, statistic_differences, + parameters, coordinate_law, engine, result ); + } + return result; + } + std::vector< double > steps( nb_parameters, 0. ); + for( const auto step : Range{ nb_proposals } ) + { + geode_unused( step ); + propose_all_coordinates( thetas, statistic_differences, parameters, + steps, engine, result ); + } + return result; + } + + DeltaCalibrationResult calibrate_deltas( + absl::Span< const double > covariance, + index_t shadow_steps, + ShadowProposal proposal, + double step_scale ) + { + const auto nb_parameters = static_cast< index_t >( std::lround( + std::sqrt( static_cast< double >( covariance.size() ) ) ) ); + OpenGeodeStochasticStochasticException::check_exception( + nb_parameters > 0 + && nb_parameters * nb_parameters == covariance.size(), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] A covariance of ", covariance.size(), + " values is not a square matrix." ); + OpenGeodeStochasticStochasticException::check_exception( + shadow_steps > 0 && step_scale > 0. && std::isfinite( step_scale ), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] The number of shadow steps (", shadow_steps, + ") and the step scale (", step_scale, ") should be positive." ); + for( const auto row : Range{ nb_parameters } ) + { + const auto variance = covariance[row * nb_parameters + row]; + OpenGeodeStochasticStochasticException::check_exception( + variance > 0. && std::isfinite( variance ), nullptr, + OpenGeodeException::TYPE::data, "[ABCShadow] The statistic ", + row, " has the variance ", variance, + ": it does not vary, its step cannot be calibrated (give the " + "steps by hand)." ); + } + double largest_row_sum{ 0. }; + for( const auto row : Range{ nb_parameters } ) + { + // the correlation of a statistic with itself is exactly 1 + double row_sum{ 1. }; + for( const auto column : Range{ nb_parameters } ) + { + if( column == row ) + { + continue; + } + row_sum += + std::fabs( covariance[row * nb_parameters + column] ) + / ( std::sqrt( covariance[row * nb_parameters + row] ) + * std::sqrt( + covariance[column * nb_parameters + column] ) ); + } + largest_row_sum = std::max( largest_row_sum, row_sum ); + } + DeltaCalibrationResult result; + result.effective_step_scale = step_scale / largest_row_sum; + const auto proposals = + proposals_per_coordinate( shadow_steps, proposal, nb_parameters ); + result.deltas.reserve( nb_parameters ); + for( const auto row : Range{ nb_parameters } ) + { + // NOLINTNEXTLINE(*-magic-numbers) + result.deltas.push_back( std::sqrt( + 12. * result.effective_step_scale + / ( proposals * covariance[row * nb_parameters + row] ) ) ); + } + for( const auto parameter : Range{ nb_parameters } ) + { + OpenGeodeStochasticStochasticException::check_exception( + result.deltas[parameter] > 0. + && std::isfinite( result.deltas[parameter] ), + nullptr, OpenGeodeException::TYPE::data, + "[ABCShadow] The statistic ", parameter, + " has a variance too small or too large (", + covariance[parameter * nb_parameters + parameter], + ") for a finite non zero step: give the steps by hand." ); + } + return result; + } + + namespace detail + { + void calibration_moments( + const std::vector< std::vector< double > >& samples, + AbcTrace& trace ) + { + const auto moments = statistics::sample_moments( samples ); + const auto nb_statistics = moments.means.size(); + trace.statistic_covariance = moments.covariance; + trace.statistic_lag_correlations.assign( nb_statistics, 0. ); + for( const auto row : Range{ nb_statistics } ) + { + const auto mean = moments.means[row]; + double lag_sum{ 0. }; + for( const auto sample : Range{ samples.size() - 1 } ) + { + lag_sum += ( samples[sample][row] - mean ) + * ( samples[sample + 1][row] - mean ); + } + const auto squares = + moments.covariance[row * nb_statistics + row] + * static_cast< double >( samples.size() - 1 ); + auto& correlation = trace.statistic_lag_correlations[row]; + correlation = squares > 0. ? lag_sum / squares : 0.; + // NOLINTNEXTLINE(*-magic-numbers) + if( correlation > 0.5 ) + { + Logger::warning( "[ABCShadow] Statistic '", + trace.term_names[row], "': lag 1 correlation ", + correlation, + " between successive simulations: increase mh_steps " + "(the shadow chain assumes decorrelated t_y)." ); + } + } + } + + void estimate_step_scales( + index_t shadow_steps, ShadowProposal proposal, AbcTrace& trace ) + { + // NOLINTBEGIN(*-magic-numbers) + constexpr double TOO_LARGE{ 1. }; + constexpr double TOO_SMALL{ 0.02 }; + // NOLINTEND(*-magic-numbers) + const auto nb_parameters = trace.deltas.size(); + trace.estimated_step_scales.assign( nb_parameters, 0. ); + if( trace.statistics.size() < 2 ) + { + return; + } + const auto proposals = proposals_per_coordinate( + shadow_steps, proposal, nb_parameters ); + const auto moments = statistics::sample_moments( trace.statistics ); + for( const auto parameter : Range{ nb_parameters } ) + { + // P ~ Var( t_y ) / 2 over the trace (see AbcTrace) + const auto fisher = + moments.covariance[parameter * nb_parameters + parameter] + / 2.; + const auto delta = trace.deltas[parameter]; + // NOLINTNEXTLINE(*-magic-numbers) + const auto scale = proposals * delta * delta / 12. * fisher; + trace.estimated_step_scales[parameter] = scale; + if( scale > TOO_LARGE ) + { + Logger::warning( "[ABCShadow] Term '", + trace.term_names[parameter], + "': estimated h.P = ", scale, " > ", TOO_LARGE, + ": delta is too large, the posterior is inflated. " + "Rerun (the steps are recalibrated at the last theta) " + "or give smaller deltas." ); + } + else if( scale < TOO_SMALL ) + { + Logger::warning( "[ABCShadow] Term '", + trace.term_names[parameter], + "': estimated h.P = ", scale, " < ", TOO_SMALL, + ": delta is too small, the chain mixes slowly. Rerun " + "(the steps are recalibrated at the last theta) or " + "give larger deltas." ); + } + } + } + } // namespace detail +} // namespace geode diff --git a/tests/stochastic/inference/CMakeLists.txt b/tests/stochastic/inference/CMakeLists.txt index a811d4f..e78ca1c 100644 --- a/tests/stochastic/inference/CMakeLists.txt +++ b/tests/stochastic/inference/CMakeLists.txt @@ -25,3 +25,26 @@ add_geode_test( OpenGeode::geometry ${PROJECT_NAME}::stochastic ) + +add_geode_test( + SOURCE "test-abc-shadow-step.cpp" + DEPENDENCIES + OpenGeode::basic + ${PROJECT_NAME}::stochastic +) + +add_geode_test( + SOURCE "test-abc-shadow-poisson.cpp" + DEPENDENCIES + OpenGeode::basic + OpenGeode::geometry + ${PROJECT_NAME}::stochastic +) + +add_geode_test( + SOURCE "test-abc-shadow-strauss.cpp" + DEPENDENCIES + OpenGeode::basic + OpenGeode::geometry + ${PROJECT_NAME}::stochastic +) diff --git a/tests/stochastic/inference/test-abc-shadow-poisson.cpp b/tests/stochastic/inference/test-abc-shadow-poisson.cpp new file mode 100644 index 0000000..3ae39cb --- /dev/null +++ b/tests/stochastic/inference/test-abc-shadow-poisson.cpp @@ -0,0 +1,502 @@ +/* + * 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 +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include + +// ABC shadow on a simulation context: the posterior of a Poisson process is +// known, and every rule of the configuration is checked before any +// simulation. +namespace +{ + constexpr double AREA{ 100. }; + constexpr double OBSERVED_COUNT{ 50. }; + + geode::SpatialDomainConfig< 2 > domain_10x10() + { + geode::SpatialDomainConfig< 2 > domain; + // NOLINTBEGIN(*-magic-numbers) + domain.min_point = geode::Point2D{ { 0., 0. } }; + domain.max_point = geode::Point2D{ { 10., 10. } }; + domain.buffer_size = 1.; + // NOLINTEND(*-magic-numbers) + return domain; + } + + geode::SimulationContext< geode::Point2D > poisson_context( + double lambda, bool with_fixed_object = false ) + { + geode::PoissonProcessBuilder< geode::Point2D > poisson; + poisson.set_domain( domain_10x10() ); + auto& set = poisson.add_set( "A", lambda ); + if( with_fixed_object ) + { + // NOLINTNEXTLINE(*-magic-numbers) + set.fixed_objects = { geode::Point2D{ { 5., 5. } } }; + } + return poisson.build_simulation_context(); + } + + // Strauss: terms "A_density" then the interaction, a hard-core + // (gamma = 0) or a repulsion without hard-core (its attraction is not + // integrable) + geode::SimulationContext< geode::Point2D > strauss_context( double gamma ) + { + geode::StraussProcessBuilder< geode::Point2D > strauss; + strauss.set_domain( domain_10x10() ); + // NOLINTBEGIN(*-magic-numbers) + auto& set = strauss.add_set( "A", 0.5 ); + geode_unused( set ); + strauss.add_interaction( { "A" }, gamma, 0.5, std::nullopt ); + // NOLINTEND(*-magic-numbers) + return strauss.build_simulation_context(); + } + + geode::AbcShadowConfig density_config() + { + geode::AbcShadowConfig config; + geode::AbcParameterConfig density; + density.term_name = "A_density"; + density.observed_statistic = OBSERVED_COUNT; + config.parameters = { density }; + // NOLINTBEGIN(*-magic-numbers) + config.outer_iterations = 10; + config.shadow_steps = 100; + config.mh_steps = 200; + config.burn_in_steps = 2000; + config.calibration.iterations = 30; + // NOLINTEND(*-magic-numbers) + return config; + } + + // Digamma and trigamma of an integer n + double digamma( geode::index_t n ) + { + constexpr double EULER_GAMMA{ 0.57721566490153286 }; + double sum{ -EULER_GAMMA }; + for( const auto k : geode::Range{ 1, n } ) + { + sum += 1. / static_cast< double >( k ); + } + return sum; + } + + double trigamma( geode::index_t n ) + { + double sum{ M_PI * M_PI / 6. }; + for( const auto k : geode::Range{ 1, n } ) + { + sum -= + 1. + / ( static_cast< double >( k ) * static_cast< double >( k ) ); + } + return sum; + } + + // With a flat prior on theta = log lambda and n points in D, the + // posterior is proportional to exp( theta n - |D| e^theta ): lambda + // follows a Gamma( n, |D| ), so E[theta] = digamma( n ) - log |D| and + // Var[theta] = trigamma( n ). For a Poisson process the count in D is + // exactly the sufficient statistic of its restriction to D: the + // comparison of the statistics in D on both sides is exact here. + void test_poisson_posterior() + { + geode::Logger::info( "TEST - ABC SHADOW POISSON POSTERIOR" ); + auto context = poisson_context( 0.5 ); // NOLINT(*-magic-numbers) + auto config = density_config(); + // NOLINTBEGIN(*-magic-numbers) + config.outer_iterations = 4000; + config.mh_steps = 2000; + config.burn_in_steps = 20000; + config.calibration.iterations = 100; + // NOLINTEND(*-magic-numbers) + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-poisson@" ); + const auto trace = geode::run_abc_shadow( context, config, engine ); + const auto moments = geode::statistics::sample_moments( trace.thetas ); + const auto mean = moments.means[0]; + const auto deviation = std::sqrt( moments.covariance[0] ); + const auto n = static_cast< geode::index_t >( OBSERVED_COUNT ); + const auto expected_mean = digamma( n ) - std::log( AREA ); + const auto sigma = std::sqrt( trigamma( n ) ); + geode::Logger::info( "Poisson posterior: mean ", mean, " (expected ", + expected_mean, "), standard deviation ", deviation, " (expected ", + sigma, "), delta ", trace.deltas[0], ", variance of the count ", + trace.statistic_covariance[0], ", lag 1 correlation ", + trace.statistic_lag_correlations[0] ); + // The variance of the count at lambda ~ 0.5 is P ~ 50, as in the + // synthetic Gaussian test of test-abc-shadow-step: h.P ~ 0.2, + // autocorrelation ~ 0.9, effective sample size ~ 210, standard + // error of the mean ~ 0.07 sigma, standard deviation inflated by + // ~ 5 to 10 %. + // NOLINTBEGIN(*-magic-numbers) + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( mean - expected_mean ) < 0.25 * sigma + && std::fabs( deviation / sigma - 1. ) < 0.2, + "[ABCShadow] The Poisson posterior is not recovered." ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_trace_shape() + { + geode::Logger::info( "TEST - ABC SHADOW TRACE SHAPE" ); + auto context = poisson_context( 0.5 ); // NOLINT(*-magic-numbers) + const auto config = density_config(); + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-trace@" ); + const auto trace = geode::run_abc_shadow( context, config, engine ); + geode::OpenGeodeStochasticStochasticException::test( + trace.term_names == std::vector< std::string >{ "A_density" } + && trace.thetas.size() == config.outer_iterations + && trace.statistics.size() == config.outer_iterations + && trace.acceptance_rates.size() == config.outer_iterations + && trace.thetas[0].size() == 1 + && trace.statistics[0].size() == 1, + "[ABCShadow] Wrong sizes of the trace." ); + geode::OpenGeodeStochasticStochasticException::test( + trace.deltas.size() == 1 && trace.deltas[0] > 0. + && trace.statistic_covariance.size() == 1 + && trace.statistic_covariance[0] > 0. + && trace.effective_step_scale > 0. + && trace.effective_step_scale <= 0.2 // NOLINT + && trace.statistic_lag_correlations.size() == 1, + "[ABCShadow] Wrong calibration in the trace." ); + geode::OpenGeodeStochasticStochasticException::test( + context.model->thetas()[0] == trace.thetas.back()[0], + "[ABCShadow] The model should carry the last theta of the " + "trace." ); + // delta is frozen after the calibration + auto longer_context = poisson_context( 0.5 ); // NOLINT + auto longer = config; + longer.outer_iterations = 50; // NOLINT(*-magic-numbers) + geode::RandomEngine same_engine; + same_engine.set_seed( "@abc-shadow-trace@" ); + const auto longer_trace = + geode::run_abc_shadow( longer_context, longer, same_engine ); + geode::OpenGeodeStochasticStochasticException::test( + longer_trace.deltas == trace.deltas + && longer_trace.thetas[0] == trace.thetas[0], + "[ABCShadow] The calibrated delta should not depend on the " + "number of iterations." ); + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_given_deltas() + { + geode::Logger::info( "TEST - ABC SHADOW GIVEN DELTAS" ); + auto context = poisson_context( 0.5 ); // NOLINT(*-magic-numbers) + auto config = density_config(); + config.parameters[0].delta = 0.02; // NOLINT(*-magic-numbers) + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-given@" ); + const auto trace = geode::run_abc_shadow( context, config, engine ); + geode::OpenGeodeStochasticStochasticException::test( + trace.statistic_covariance.empty() + && trace.statistic_lag_correlations.empty() + && trace.effective_step_scale == 0. + && trace.deltas == std::vector< double >{ 0.02 }, + "[ABCShadow] Given deltas should be used without calibration." ); + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_continue_chain() + { + geode::Logger::info( "TEST - ABC SHADOW CONTINUE A CHAIN" ); + auto context = poisson_context( 0.5 ); // NOLINT(*-magic-numbers) + auto config = density_config(); + config.outer_iterations = 50; // NOLINT(*-magic-numbers) + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-continue@" ); + const auto first = geode::run_abc_shadow( context, config, engine ); + geode::OpenGeodeStochasticStochasticException::test( + context.model->thetas()[0] == first.thetas.back()[0], + "[ABCShadow] A second call should start from the last theta." ); + const auto second = geode::run_abc_shadow( context, config, engine ); + geode::OpenGeodeStochasticStochasticException::test( + second.thetas.size() == config.outer_iterations, + "[ABCShadow] Wrong size of the continued trace." ); + geode::Logger::info( "--> SUCCESS!" ); + } + + // The trace estimates h.P = m delta^2 / 12 . P, with P ~ Var( t_y ) / 2 + // over the trace, to detect a badly calibrated delta: close to 0.2 when + // calibrated, far above 1 with a much too large delta, far below 0.02 with + // a much too small one (a warning is logged in both cases). + void test_estimated_step_scales() + { + geode::Logger::info( "TEST - ABC SHADOW ESTIMATED STEP SCALES" ); + // NOLINTBEGIN(*-magic-numbers) + const auto scale = [&]( std::optional< double > delta ) { + auto context = poisson_context( 0.5 ); + auto config = density_config(); + config.outer_iterations = 400; + config.mh_steps = 1000; + config.parameters[0].delta = delta; + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-step-scales@" ); + const auto trace = geode::run_abc_shadow( context, config, engine ); + geode::Logger::info( "delta ", trace.deltas[0], ": estimated h.P ", + trace.estimated_step_scales[0] ); + return trace.estimated_step_scales[0]; + }; + const auto calibrated = scale( std::nullopt ); + geode::OpenGeodeStochasticStochasticException::test( + calibrated > 0.05 && calibrated < 0.5, + "[ABCShadow] The calibrated delta should give h.P ~ 0.2, not ", + calibrated ); + const auto large = scale( 0.5 ); + geode::OpenGeodeStochasticStochasticException::test( large > 1., + "[ABCShadow] A much too large delta should give h.P > 1, not ", + large ); + const auto small = scale( 0.001 ); + geode::OpenGeodeStochasticStochasticException::test( small < 0.02, + "[ABCShadow] A much too small delta should give h.P < 0.02, not ", + small ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + bool refused( geode::SimulationContext< geode::Point2D >& context, + const geode::AbcShadowConfig& config, + std::string_view expected_message ) + { + geode::RandomEngine engine; + try + { + const auto trace = geode::run_abc_shadow( context, config, engine ); + geode_unused( trace ); + } + catch( const geode::OpenGeodeException& exception ) + { + const std::string message{ exception.what() }; + if( message.find( expected_message ) == std::string::npos ) + { + geode::Logger::error( "Unexpected message: ", message ); + return false; + } + return true; + } + return false; + } + + void check_refused( geode::SimulationContext< geode::Point2D >& context, + const std::function< void( geode::AbcShadowConfig& ) >& change, + std::string_view expected_message, + std::string_view rule ) + { + auto config = density_config(); + change( config ); + geode::OpenGeodeStochasticStochasticException::test( + refused( context, config, expected_message ), + "[ABCShadow] Should be refused: ", rule ); + } + + void test_config_errors() + { + geode::Logger::info( "TEST - ABC SHADOW CONFIGURATION ERRORS" ); + constexpr auto infinity = std::numeric_limits< double >::infinity(); + auto context = poisson_context( 0.5 ); // NOLINT(*-magic-numbers) + // NOLINTBEGIN(*-magic-numbers) + check_refused( + context, + []( auto& config ) { + config.parameters.clear(); + }, + "no parameter", "no parameter" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].term_name = "nope"; + }, + "Unknown term", "unknown term" ); + check_refused( + context, + []( auto& config ) { + config.parameters.push_back( config.parameters[0] ); + }, + "twice", "term named twice" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].theta_min = 0.; + }, + "theta_min", "theta_min above the start" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].theta_min = 1.; + config.parameters[0].theta_max = 0.; + }, + "theta_min", "theta_min >= theta_max" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].theta_max = -infinity; + }, + "theta_max", "theta_max = -inf" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].theta_max = -1.; + }, + "outside", "start outside the box" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].observed_statistic = -1.; + }, + "negative", "negative observed statistic" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].observed_statistic = 0.; + }, + "hard-core", "observed statistic 0 without theta_min" ); + check_refused( + context, + []( auto& config ) { + config.parameters[0].delta = 0.; + }, + "delta", "zero delta" ); + check_refused( + context, + []( auto& config ) { + config.outer_iterations = 0; + }, + "iterations", "no outer iteration" ); + check_refused( + context, + []( auto& config ) { + config.shadow_steps = 0; + }, + "shadow steps", "no shadow step" ); + check_refused( + context, + []( auto& config ) { + config.mh_steps = 0; + }, + "Metropolis-Hastings steps", "no MH step" ); + check_refused( + context, + []( auto& config ) { + config.calibration.iterations = 29; + }, + "calibration", "too few calibration iterations" ); + check_refused( + context, + []( auto& config ) { + config.calibration.step_scale = 0.; + }, + "step scale", "zero step scale" ); + // an observed statistic of 0 is accepted with a finite lower bound + { + auto config = density_config(); + config.parameters[0].observed_statistic = 0.; + config.parameters[0].theta_min = -10.; + geode::RandomEngine engine; + const auto trace = geode::run_abc_shadow( context, config, engine ); + geode::OpenGeodeStochasticStochasticException::test( + trace.thetas.back()[0] >= -10., + "[ABCShadow] The lower bound should hold." ); + } + + // the integrability bound of a repulsion, and a hard-core + auto strauss = strauss_context( 0.5 ); + const auto repulsion = strauss.model->term_names()[1]; + check_refused( + strauss, + [&repulsion]( auto& config ) { + config.parameters[0].term_name = repulsion; + config.parameters[0].theta_max = 0.5; + }, + "integrable", "attraction on a repulsion" ); + auto hard_core_context = strauss_context( 0. ); + const auto hard_core = hard_core_context.model->term_names()[1]; + check_refused( + hard_core_context, + [&hard_core]( auto& config ) { + config.parameters[0].term_name = hard_core; + }, + "hard-core", "hard-core term" ); + // a part of the deltas only + check_refused( + strauss, + [&repulsion]( auto& config ) { + auto second = config.parameters[0]; + second.term_name = repulsion; + second.delta = 0.1; + config.parameters.push_back( second ); + }, + "all the parameters or none", "a part of the deltas" ); + + // fixed objects + auto fixed = poisson_context( 0.5, true ); + check_refused( + fixed, []( auto& ) {}, "fixed objects", "fixed objects" ); + + // a statistic that does not vary during the calibration: no point + auto empty = poisson_context( 1e-12 ); + check_refused( + empty, + []( auto& config ) { + config.parameters[0].observed_statistic = 5.; + config.parameters[0].theta_min = -40.; + }, + "does not vary", "constant statistic" ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } +} // namespace + +int main() +{ + try + { + geode::OpenGeodeStochasticStochasticLibrary::initialize(); + test_config_errors(); + test_given_deltas(); + test_trace_shape(); + test_continue_chain(); + test_estimated_step_scales(); + test_poisson_posterior(); + return 0; + } + catch( ... ) + { + return geode::geode_lippincott(); + } +} diff --git a/tests/stochastic/inference/test-abc-shadow-step.cpp b/tests/stochastic/inference/test-abc-shadow-step.cpp new file mode 100644 index 0000000..fce6729 --- /dev/null +++ b/tests/stochastic/inference/test-abc-shadow-step.cpp @@ -0,0 +1,447 @@ +/* + * 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 +#include + +#include +#include + +#include +#include +#include + +namespace +{ + // Mean and variance of the law proportional to exp( c theta ) on [a, b] + // (truncated exponential): the stationary law of the shadow chain with + // t_obs - t_y = c fixed. + struct Moments + { + double mean; + double variance; + }; + + Moments truncated_exponential( double c, double a, double b ) + { + const auto ea = std::exp( c * a ); + const auto eb = std::exp( c * b ); + const auto mean = ( b * eb - a * ea ) / ( eb - ea ) - 1. / c; + const auto second = + ( b * b * eb - a * a * ea ) / ( eb - ea ) - 2. * mean / c; + return { mean, second - mean * mean }; + } + + Moments sample_moments( const std::vector< double >& values ) + { + double sum{ 0. }; + for( const auto value : values ) + { + sum += value; + } + const auto mean = sum / static_cast< double >( values.size() ); + double squares{ 0. }; + for( const auto value : values ) + { + squares += ( value - mean ) * ( value - mean ); + } + return { mean, squares / static_cast< double >( values.size() - 1 ) }; + } + + // 1e6 states recorded after each proposal. Tolerances: 4 standard errors + // with an effective sample size 1e6 / tau, tau <= 50 (the step 0.5 crosses + // the box of width 2 in a few tens of proposals): 4 * 0.42 / sqrt( 2e4 ) + // ~ 0.012 on the mean; the variance has a smaller standard error. + constexpr geode::index_t NB_RECORDS{ 1'000'000 }; + constexpr double MEAN_TOLERANCE{ 0.012 }; + constexpr double VARIANCE_TOLERANCE{ 0.01 }; + + std::vector< std::vector< double > > record_chain( + std::vector< double > thetas, + const std::vector< double >& differences, + const std::vector< geode::ShadowParameter >& parameters, + geode::ShadowProposal proposal, + geode::RandomEngine& engine ) + { + std::vector< std::vector< double > > records( + thetas.size(), std::vector< double >( NB_RECORDS ) ); + for( const auto record : geode::Range{ NB_RECORDS } ) + { + const auto result = geode::shadow_step( absl::MakeSpan( thetas ), + differences, parameters, proposal, 1, engine ); + geode_unused( result ); + for( const auto coordinate : geode::Range{ thetas.size() } ) + { + records[coordinate][record] = thetas[coordinate]; + } + } + return records; + } + + void check_moments( const std::vector< double >& records, + const Moments& expected, + std::string_view name ) + { + const auto moments = sample_moments( records ); + geode::Logger::info( name, ": mean ", moments.mean, " (expected ", + expected.mean, "), variance ", moments.variance, " (expected ", + expected.variance, ")" ); + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( moments.mean - expected.mean ) < MEAN_TOLERANCE + && std::fabs( moments.variance - expected.variance ) + < VARIANCE_TOLERANCE, + "[ABCShadow] ", name, + ": the shadow chain does not sample the truncated exponential " + "law." ); + } + + void test_stationary_law_1d() + { + geode::Logger::info( "TEST - SHADOW STEP STATIONARY LAW 1D" ); + geode::RandomEngine engine; + engine.set_seed( 1 ); + // NOLINTBEGIN(*-magic-numbers) + const auto records = record_chain( { 0. }, { 2. }, { { -1., 1., 0.5 } }, + geode::ShadowProposal::one_coordinate, engine ); + check_moments( records[0], truncated_exponential( 2., -1., 1. ), "1D" ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_all_coordinates_2d() + { + geode::Logger::info( "TEST - SHADOW STEP ALL COORDINATES 2D" ); + geode::RandomEngine engine; + engine.set_seed( 2 ); + // NOLINTBEGIN(*-magic-numbers) + const auto records = record_chain( { 0., 0. }, { 1., -1. }, + { { -1., 1., 0.5 }, { -1., 1., 0.5 } }, + geode::ShadowProposal::all_coordinates, engine ); + check_moments( records[0], truncated_exponential( 1., -1., 1. ), + "2D first coordinate" ); + check_moments( records[1], truncated_exponential( -1., -1., 1. ), + "2D second coordinate" ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_counts() + { + geode::Logger::info( "TEST - SHADOW STEP COUNTS" ); + geode::RandomEngine engine; + engine.set_seed( 3 ); + // NOLINTBEGIN(*-magic-numbers) + const std::vector< geode::ShadowParameter > parameters{ + { -1., 1., 0.5 }, { -1., 1., 0.5 }, { -1., 1., 0.5 } + }; + std::vector< double > thetas{ 0., 0., 0. }; + const std::vector< double > differences{ 1., 0., -1. }; + const auto one = geode::shadow_step( absl::MakeSpan( thetas ), + differences, parameters, geode::ShadowProposal::one_coordinate, + 1000, engine ); + geode::index_t total{ 0 }; + for( const auto coordinate : geode::Range{ 3 } ) + { + total += one.nb_proposals[coordinate]; + geode::OpenGeodeStochasticStochasticException::test( + one.nb_accepted[coordinate] <= one.nb_proposals[coordinate] + && one.nb_proposals[coordinate] > 0, + "[ABCShadow] Wrong counts of a coordinate." ); + } + geode::OpenGeodeStochasticStochasticException::test( total == 1000, + "[ABCShadow] One coordinate mode: the proposals should sum to the " + "number of proposals, not ", + total ); + const auto all = geode::shadow_step( absl::MakeSpan( thetas ), + differences, parameters, geode::ShadowProposal::all_coordinates, + 1000, engine ); + for( const auto coordinate : geode::Range{ 3 } ) + { + geode::OpenGeodeStochasticStochasticException::test( + all.nb_proposals[coordinate] == 1000 + && all.nb_accepted[coordinate] == all.nb_accepted[0], + "[ABCShadow] All coordinates mode: each coordinate is " + "proposed, and accepted, with the others." ); + } + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_stays_in_box() + { + geode::Logger::info( "TEST - SHADOW STEP STAYS IN THE BOX" ); + geode::RandomEngine engine; + engine.set_seed( 4 ); + // NOLINTBEGIN(*-magic-numbers) + std::vector< double > thetas{ 0.5 }; + geode::index_t accepted{ 0 }; + for( const auto step : geode::Range{ 10'000 } ) + { + geode_unused( step ); + const auto result = geode::shadow_step( absl::MakeSpan( thetas ), + { 0. }, { { 0., 1., 10. } }, + geode::ShadowProposal::one_coordinate, 1, engine ); + accepted += result.nb_accepted[0]; + geode::OpenGeodeStochasticStochasticException::test( + thetas[0] >= 0. && thetas[0] <= 1., + "[ABCShadow] The chain left the box: ", thetas[0] ); + } + geode::OpenGeodeStochasticStochasticException::test( accepted < 2'000, + "[ABCShadow] Too many accepted proposals with " + "a step much larger than the box: ", + accepted ); + // an infinite box with a zero difference accepts every proposal + constexpr auto infinity = std::numeric_limits< double >::infinity(); + const auto result = geode::shadow_step( absl::MakeSpan( thetas ), + { 0. }, { { -infinity, infinity, 1. } }, + geode::ShadowProposal::one_coordinate, 1000, engine ); + geode::OpenGeodeStochasticStochasticException::test( + result.nb_accepted[0] == 1000 && std::isfinite( thetas[0] ), + "[ABCShadow] An infinite box should accept every proposal with a " + "zero difference." ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_replay() + { + geode::Logger::info( "TEST - SHADOW STEP REPLAY" ); + // NOLINTBEGIN(*-magic-numbers) + const std::vector< geode::ShadowParameter > parameters{ + { -2., 2., 0.3 }, { -2., 2., 0.7 } + }; + const std::vector< double > differences{ 0.5, -2. }; + std::vector< double > first{ 0.1, -0.1 }; + std::vector< double > second{ 0.1, -0.1 }; + geode::RandomEngine engine_a; + engine_a.set_seed( 5 ); + geode::RandomEngine engine_b; + engine_b.set_seed( 5 ); + geode::shadow_step( absl::MakeSpan( first ), differences, parameters, + geode::ShadowProposal::one_coordinate, 10'000, engine_a ); + geode::shadow_step( absl::MakeSpan( second ), differences, parameters, + geode::ShadowProposal::one_coordinate, 10'000, engine_b ); + // NOLINTEND(*-magic-numbers) + geode::OpenGeodeStochasticStochasticException::test( first == second, + "[ABCShadow] Two engines with the same seed should give the same " + "chain." ); + geode::Logger::info( "--> SUCCESS!" ); + } + + void test_size_mismatch() + { + geode::Logger::info( "TEST - SHADOW STEP SIZE MISMATCH" ); + geode::RandomEngine engine; + std::vector< double > thetas{ 0., 0. }; + bool refused{ false }; + try + { + // NOLINTNEXTLINE(*-magic-numbers) + geode::shadow_step( absl::MakeSpan( thetas ), { 1. }, + { { -1., 1., 0.5 } }, geode::ShadowProposal::one_coordinate, 10, + engine ); + } + catch( const geode::OpenGeodeException& ) + { + refused = true; + } + geode::OpenGeodeStochasticStochasticException::test( refused, + "[ABCShadow] Vectors of different sizes should be refused." ); + geode::Logger::info( "--> SUCCESS!" ); + } + + bool is_close( double value, double expected ) + { + constexpr double relative_tolerance{ 1e-12 }; + return std::fabs( value - expected ) + <= relative_tolerance * std::fabs( expected ); + } + + bool calibration_refused( const std::vector< double >& covariance, + geode::index_t shadow_steps, + double step_scale ) + { + try + { + const auto result = + geode::calibrate_deltas( covariance, shadow_steps, + geode::ShadowProposal::all_coordinates, step_scale ); + geode_unused( result ); + return false; + } + catch( const geode::OpenGeodeException& ) + { + return true; + } + } + + void test_calibrate_values() + { + geode::Logger::info( "TEST - CALIBRATE DELTAS VALUES" ); + // NOLINTBEGIN(*-magic-numbers) + const auto one = geode::calibrate_deltas( + { 50. }, 100, geode::ShadowProposal::all_coordinates, 0.2 ); + geode::OpenGeodeStochasticStochasticException::test( + one.deltas.size() == 1 + && is_close( one.deltas[0], std::sqrt( 2.4 / 5000. ) ) + && is_close( one.effective_step_scale, 0.2 ), + "[ABCShadow] Wrong calibrated delta: ", one.deltas[0] ); + const auto uncorrelated = geode::calibrate_deltas( { 50., 0., 0., 50. }, + 100, geode::ShadowProposal::one_coordinate, 0.2 ); + geode::OpenGeodeStochasticStochasticException::test( + is_close( uncorrelated.deltas[0], + std::sqrt( 2.4 / 5000. ) * std::sqrt( 2. ) ) + && is_close( uncorrelated.deltas[1], uncorrelated.deltas[0] ), + "[ABCShadow] One coordinate mode: each coordinate gets m / K " + "proposals." ); + // rho = 0.9: Gershgorin bound 1.9 on the largest eigenvalue + const auto correlated = geode::calibrate_deltas( { 50., 45., 45., 50. }, + 100, geode::ShadowProposal::all_coordinates, 0.2 ); + geode::OpenGeodeStochasticStochasticException::test( + is_close( correlated.effective_step_scale, 0.2 / 1.9 ) + && is_close( correlated.deltas[0], + std::sqrt( 12. * 0.2 / 1.9 / ( 100. * 50. ) ) ), + "[ABCShadow] Wrong effective step scale with correlated " + "statistics: ", + correlated.effective_step_scale ); + // m / K is not an integer division + const auto odd = geode::calibrate_deltas( { 50., 0., 0., 50. }, 3, + geode::ShadowProposal::one_coordinate, 0.2 ); + geode::OpenGeodeStochasticStochasticException::test( + is_close( odd.deltas[0], std::sqrt( 12. * 0.2 / ( 1.5 * 50. ) ) ), + "[ABCShadow] m / K should be computed in double." ); + geode::OpenGeodeStochasticStochasticException::test( + calibration_refused( { 0. }, 100, 0.2 ) + && calibration_refused( { 50. }, 100, 0. ) + && calibration_refused( { 50., 0., 0. }, 100, 0.2 ) + && calibration_refused( { 50. }, 0, 0.2 ) + // a tiny positive variance would give an infinite step + && calibration_refused( { 1e-320 }, 100, 0.2 ), + "[ABCShadow] A zero variance, a zero step scale, a covariance " + "that is not square or no proposal should be refused." ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } + + // Synthetic exponential family without simulation: t ~ N( P theta, P ), + // P the Fisher information. With a flat prior, the posterior given t_obs + // is N( t_obs / P, 1 / P ). + constexpr double FISHER{ 50. }; + constexpr double OBSERVED{ 25. }; + constexpr geode::index_t SHADOW_STEPS{ 100 }; + + Moments gaussian_chain( double delta, geode::index_t seed ) + { + geode::RandomEngine engine; + engine.set_seed( seed ); + // NOLINTBEGIN(*-magic-numbers) + const std::vector< geode::ShadowParameter > parameters{ { -5., 5., + delta } }; + std::vector< double > thetas{ OBSERVED / FISHER }; + std::vector< double > records; + constexpr geode::index_t burn_in{ 200 }; + constexpr geode::index_t iterations{ 4000 }; + for( const auto iteration : geode::Range{ burn_in + iterations } ) + { + geode::Gaussian statistic_law; + statistic_law.mean = FISHER * thetas[0]; + statistic_law.standard_deviation = std::sqrt( FISHER ); + const auto statistic = engine.sample_gaussian( statistic_law ); + const auto result = geode::shadow_step( absl::MakeSpan( thetas ), + { OBSERVED - statistic }, parameters, + geode::ShadowProposal::all_coordinates, SHADOW_STEPS, engine ); + geode_unused( result ); + if( iteration >= burn_in ) + { + records.push_back( thetas[0] ); + } + } + // NOLINTEND(*-magic-numbers) + return sample_moments( records ); + } + + void test_calibrated_gaussian_posterior() + { + geode::Logger::info( "TEST - CALIBRATED DELTA GAUSSIAN POSTERIOR" ); + // NOLINTBEGIN(*-magic-numbers) + const auto calibration = geode::calibrate_deltas( { FISHER }, + SHADOW_STEPS, geode::ShadowProposal::all_coordinates, 0.2 ); + const auto delta = calibration.deltas[0]; + const auto mean = OBSERVED / FISHER; + const auto sigma = 1. / std::sqrt( FISHER ); + // h.P = 0.2: autocorrelation 1 - hP / 2 = 0.9, effective sample size + // ~ 4000 * 0.1 / 1.9 ~ 210, standard error of the mean ~ 0.07 sigma; + // standard deviation inflated to first order by + // sqrt( ( 1 + hP / 4 ) / ( 1 - hP / 4 ) ) ~ 1.05 (1.07 measured on 30 + // seeds, from 1.02 to 1.16). + const auto calibrated = gaussian_chain( delta, 6 ); + const auto ratio = std::sqrt( calibrated.variance ) / sigma; + geode::Logger::info( "calibrated delta ", delta, ": mean ", + calibrated.mean, " (posterior ", mean, "), sd / sigma ", ratio ); + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( calibrated.mean - mean ) < 0.25 * sigma + && std::fabs( ratio - 1. ) < 0.2, + "[ABCShadow] The calibrated delta should sample the posterior." ); + // h.P = 2: the inflation of the standard deviation shows (1.57 + // measured, 1.73 to first order) + const auto inflated = gaussian_chain( delta * std::sqrt( 10. ), 7 ); + const auto inflated_ratio = std::sqrt( inflated.variance ) / sigma; + geode::Logger::info( + "delta x sqrt( 10 ): sd / sigma ", inflated_ratio ); + geode::OpenGeodeStochasticStochasticException::test( + inflated_ratio > 1.3, "[ABCShadow] With h.P = 2, the standard " + "deviation should be inflated." ); + // delta x 25: the drift saturates at m delta / 8 and the chain + // bounces on the box + const auto saturated = gaussian_chain( delta * 25., 8 ); + const auto saturated_ratio = std::sqrt( saturated.variance ) / sigma; + geode::Logger::info( "delta x 25: sd / sigma ", saturated_ratio ); + geode::OpenGeodeStochasticStochasticException::test( + saturated_ratio > 3., "[ABCShadow] With a much too large delta, " + "the chain should not sample the " + "posterior." ); + // NOLINTEND(*-magic-numbers) + geode::Logger::info( "--> SUCCESS!" ); + } +} // namespace + +int main() +{ + try + { + geode::OpenGeodeStochasticStochasticLibrary::initialize(); + test_stationary_law_1d(); + test_all_coordinates_2d(); + test_counts(); + test_stays_in_box(); + test_replay(); + test_size_mismatch(); + test_calibrate_values(); + test_calibrated_gaussian_posterior(); + return 0; + } + catch( ... ) + { + return geode::geode_lippincott(); + } +} diff --git a/tests/stochastic/inference/test-abc-shadow-strauss.cpp b/tests/stochastic/inference/test-abc-shadow-strauss.cpp new file mode 100644 index 0000000..ed90731 --- /dev/null +++ b/tests/stochastic/inference/test-abc-shadow-strauss.cpp @@ -0,0 +1,294 @@ +/* + * 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 +#include + +#include +#include + +#include + +#include +#include +#include +#include + +// Validation of the inference on a Strauss process (the model is +// simulated on the extended domain, and the statistics are compared in the +// domain on both sides). A pattern simulated with known parameters gives +// t_obs; the ABC shadow, started elsewhere, must find the parameters back, +// with a posterior spread consistent with the Fisher information. +namespace +{ + constexpr double TRUE_LAMBDA{ 0.5 }; + constexpr double TRUE_GAMMA{ 0.3 }; + constexpr double DISTANCE{ 1. }; + + geode::SimulationContext< geode::Point2D > strauss_context( + double lambda, double gamma ) + { + geode::SpatialDomainConfig< 2 > domain; + // NOLINTBEGIN(*-magic-numbers) + domain.min_point = geode::Point2D{ { 0., 0. } }; + domain.max_point = geode::Point2D{ { 20., 20. } }; + domain.buffer_size = 1.; + // NOLINTEND(*-magic-numbers) + geode::StraussProcessBuilder< geode::Point2D > strauss; + strauss.set_domain( domain ); + auto& set = strauss.add_set( "A", lambda ); + geode_unused( set ); + strauss.add_interaction( { "A" }, gamma, DISTANCE, std::nullopt ); + return strauss.build_simulation_context(); + } + + struct Reference + { + std::vector< double > observed; + // sqrt( diag( Cov( t )^-1 ) ): the posterior standard deviations of + // an exponential family with a flat prior, to first order + std::vector< double > sigmas; + double correlation; + }; + + Reference reference_statistics() + { + auto context = strauss_context( TRUE_LAMBDA, TRUE_GAMMA ); + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-strauss-data@" ); + // NOLINTBEGIN(*-magic-numbers) + context.mh_sampler->walk( *context.object_sets, engine, 200'000 ); + Reference reference; + reference.observed = + context.model->observed_statistics( *context.object_sets ); + constexpr geode::index_t nb_realizations{ 200 }; + std::vector< std::vector< double > > samples; + for( const auto realization : geode::Range{ nb_realizations } ) + { + geode_unused( realization ); + context.mh_sampler->walk( *context.object_sets, engine, 3000 ); + samples.push_back( + context.model->observed_statistics( *context.object_sets ) ); + } + // NOLINTEND(*-magic-numbers) + const auto covariance = + geode::statistics::sample_moments( samples ).covariance; + const auto c00 = covariance[0]; + const auto c01 = covariance[1]; + const auto c11 = covariance[3]; + // diagonal of the inverse of the 2 x 2 covariance + const auto determinant = c00 * c11 - c01 * c01; + reference.sigmas = { std::sqrt( c11 / determinant ), + std::sqrt( c00 / determinant ) }; + reference.correlation = c01 / std::sqrt( c00 * c11 ); + return reference; + } + + // Integrated autocorrelation time, summed while the autocorrelation stays + // above 0.05. + double effective_sample_size( const std::vector< double >& values ) + { + const auto nb = values.size(); + double mean{ 0. }; + for( const auto value : values ) + { + mean += value; + } + mean /= static_cast< double >( nb ); + double variance{ 0. }; + for( const auto value : values ) + { + variance += ( value - mean ) * ( value - mean ); + } + double time{ 1. }; + for( const auto lag : geode::Range{ 1, nb / 2 } ) + { + double covariance{ 0. }; + for( const auto index : geode::Range{ nb - lag } ) + { + covariance += + ( values[index] - mean ) * ( values[index + lag] - mean ); + } + const auto correlation = covariance / variance; + // NOLINTNEXTLINE(*-magic-numbers) + if( correlation < 0.05 ) + { + break; + } + time += 2. * correlation; + } + return static_cast< double >( nb ) / time; + } + + void check_mode( + const Reference& reference, geode::ShadowProposal proposal ) + { + const auto mode_name = proposal == geode::ShadowProposal::one_coordinate + ? "one_coordinate" + : "all_coordinates"; + geode::Logger::info( "Mode ", mode_name ); + const auto start = std::chrono::steady_clock::now(); + // started away from the truth: lambda 1, gamma 0.6 + auto context = strauss_context( 1., 0.6 ); // NOLINT(*-magic-numbers) + const auto names = context.model->term_names(); + geode::AbcShadowConfig config; + for( const auto term : geode::Range{ 2 } ) + { + geode::AbcParameterConfig parameter; + parameter.term_name = names[term]; + parameter.observed_statistic = reference.observed[term]; + config.parameters.push_back( parameter ); + } + // NOLINTBEGIN(*-magic-numbers) + config.shadow_steps = 100; + config.mh_steps = 3000; + config.burn_in_steps = 200'000; + config.proposal = proposal; + geode::RandomEngine engine; + engine.set_seed( "@abc-shadow-strauss-inference@" ); + // first call: outer burn-in, discarded; the second one continues the + // chain and recalibrates the steps near the posterior + config.outer_iterations = 500; + const auto burn_in = geode::run_abc_shadow( context, config, engine ); + geode_unused( burn_in ); + config.burn_in_steps = 0; + config.outer_iterations = 2000; + const auto trace = geode::run_abc_shadow( context, config, engine ); + // NOLINTEND(*-magic-numbers) + const std::vector< double > truth{ std::log( TRUE_LAMBDA ), + std::log( TRUE_GAMMA ) }; + double acceptance{ 0. }; + for( const auto rate : trace.acceptance_rates ) + { + acceptance += rate; + } + acceptance /= static_cast< double >( trace.acceptance_rates.size() ); + const auto covariance = trace.statistic_covariance; + const auto correlation = + covariance[1] / std::sqrt( covariance[0] * covariance[3] ); + const auto posterior = + geode::statistics::sample_moments( trace.thetas ); + const auto& posterior_means = posterior.means; + for( const auto term : geode::Range{ 2 } ) + { + std::vector< double > values; + values.reserve( trace.thetas.size() ); + for( const auto& thetas : trace.thetas ) + { + values.push_back( thetas[term] ); + } + const auto mean = posterior_means[term]; + const auto deviation = + std::sqrt( posterior.covariance[term * 2 + term] ); + geode::Logger::info( " ", names[term], ": theta true ", + truth[term], ", mean ", mean, ", standard deviation ", + deviation, ", sigma_ref ", reference.sigmas[term], ", delta ", + trace.deltas[term], ", ESS ", effective_sample_size( values ) ); + // NOLINTBEGIN(*-magic-numbers) + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( mean - truth[term] ) < 3. * deviation, + "[ABCShadow] Strauss, ", mode_name, ": theta of ", names[term], + " not recovered." ); + geode::OpenGeodeStochasticStochasticException::test( + deviation > reference.sigmas[term] / 2. + && deviation < 2. * reference.sigmas[term], + "[ABCShadow] Strauss, ", mode_name, + ": the posterior spread of ", names[term], + " is not consistent with the Fisher information." ); + // NOLINTEND(*-magic-numbers) + } + // The goal of the inference: at the posterior mean, the model gives on + // average the observed statistics (for an exponential family with a + // flat prior, the posterior concentrates where E_theta[ t ] = t_obs). + // This does not depend on the noise of the data. A shift of theta by + // one posterior standard deviation moves E[ t ] by about one standard + // deviation of t; the posterior mean is known to sigma / sqrt( ESS ~ + // 50 ) ~ 0.14 sd( t ) and the mean over 200 realizations to ~ 0.1 + // sd( t ): tolerance 0.5 sd( t ). + for( const auto term : geode::Range{ 2 } ) + { + context.model->set_theta( term, posterior_means[term] ); + } + // NOLINTBEGIN(*-magic-numbers) + context.mh_sampler->walk( *context.object_sets, engine, 50'000 ); + constexpr geode::index_t nb_realizations{ 200 }; + std::vector< std::vector< double > > samples; + samples.reserve( nb_realizations ); + for( const auto realization : geode::Range{ nb_realizations } ) + { + geode_unused( realization ); + context.mh_sampler->walk( *context.object_sets, engine, 3000 ); + samples.push_back( + context.model->observed_statistics( *context.object_sets ) ); + } + const auto at_posterior = geode::statistics::sample_moments( samples ); + for( const auto term : geode::Range{ 2 } ) + { + const auto mean = at_posterior.means[term]; + const auto deviation = + std::sqrt( at_posterior.covariance[term * 2 + term] ); + geode::Logger::info( " ", names[term], + ": mean statistic at the posterior mean ", mean, ", observed ", + reference.observed[term], ", standard deviation ", deviation ); + geode::OpenGeodeStochasticStochasticException::test( + std::fabs( mean - reference.observed[term] ) < 0.5 * deviation, + "[ABCShadow] Strauss, ", mode_name, + ": at the posterior mean, " + "the model does not give the observed statistic of ", + names[term], " on average." ); + } + // NOLINTEND(*-magic-numbers) + const auto seconds = std::chrono::duration< double >( + std::chrono::steady_clock::now() - start ) + .count(); + geode::Logger::info( " correlation of the statistics ", correlation, + " (reference ", reference.correlation, "), s_eff ", + trace.effective_step_scale, ", shadow acceptance ", acceptance, + ", ", seconds, " s" ); + } + + void test_strauss_recovery() + { + geode::Logger::info( "TEST - ABC SHADOW STRAUSS RECOVERY" ); + const auto reference = reference_statistics(); + geode::Logger::info( "Observed statistics ", reference.observed[0], " ", + reference.observed[1] ); + check_mode( reference, geode::ShadowProposal::all_coordinates ); + check_mode( reference, geode::ShadowProposal::one_coordinate ); + geode::Logger::info( "--> SUCCESS!" ); + } +} // namespace + +int main() +{ + try + { + geode::OpenGeodeStochasticStochasticLibrary::initialize(); + test_strauss_recovery(); + return 0; + } + catch( ... ) + { + return geode::geode_lippincott(); + } +} diff --git a/tests/stochastic/inference/test-statistics-tracker.cpp b/tests/stochastic/inference/test-statistics-tracker.cpp index e5a56bb..894594e 100644 --- a/tests/stochastic/inference/test-statistics-tracker.cpp +++ b/tests/stochastic/inference/test-statistics-tracker.cpp @@ -26,6 +26,7 @@ #include #include +#include #include namespace @@ -164,6 +165,43 @@ namespace geode::Logger::info( "--> SUCCESS!" ); } + + // Samples already in memory: means and unbiased covariance, computed by + // hand. Deviations from the means ( 3, 2 ): ( -2, 0 ), ( 0, -2 ), ( 2, 2 ). + void test_sample_moments() + { + geode::Logger::info( "TEST - SAMPLE MOMENTS" ); + // NOLINTBEGIN(*-magic-numbers) + const std::vector< std::vector< double > > samples{ { 1., 2. }, + { 3., 0. }, { 5., 4. } }; + const auto moments = geode::statistics::sample_moments( samples ); + geode::OpenGeodeStochasticStochasticException::test( + moments.means.size() == 2 && is_close( moments.means[0], 3. ) + && is_close( moments.means[1], 2. ), + "[SampleMoments] Wrong means" ); + geode::OpenGeodeStochasticStochasticException::test( + moments.covariance.size() == 4 + && is_close( moments.covariance[0], 4. ) + && is_close( moments.covariance[1], 2. ) + && is_close( moments.covariance[2], 2. ) + && is_close( moments.covariance[3], 4. ), + "[SampleMoments] Wrong covariance" ); + // NOLINTEND(*-magic-numbers) + bool refused{ false }; + try + { + const std::vector< std::vector< double > > one_sample{ { 1., 2. } }; + const auto single = geode::statistics::sample_moments( one_sample ); + geode_unused( single ); + } + catch( const geode::OpenGeodeException& ) + { + refused = true; + } + geode::OpenGeodeStochasticStochasticException::test( + refused, "[SampleMoments] A single sample should be refused" ); + geode::Logger::info( "--> SUCCESS!" ); + } } // namespace int main() @@ -174,6 +212,7 @@ int main() test_means_and_variances(); test_large_mean_variance(); test_wrong_number_of_values(); + test_sample_moments(); return 0; } catch( ... ) diff --git a/tests/stochastic/models/test-model-parameters.cpp b/tests/stochastic/models/test-model-parameters.cpp index e965c26..cba9876 100644 --- a/tests/stochastic/models/test-model-parameters.cpp +++ b/tests/stochastic/models/test-model-parameters.cpp @@ -336,6 +336,46 @@ namespace geode::Logger::info( "--> SUCCESS!" ); } + // Bounds of the parameters, the single source of the rules of set_thetas + // and of the prior box of the inference. + void test_theta_bounds() + { + geode::Logger::info( "TEST - THETA BOUNDS" ); + auto context = + geode::build_simulation_context( point_config( point_gammas() ) ); + auto& model = *context.model; + auto bounds = model.theta_bounds(); + constexpr geode::index_t HARD_CORE_A{ 1 }; + geode::OpenGeodeStochasticStochasticException::test( + bounds.size() == model.nb_terms(), + "[ModelParameters] One bound per term" ); + for( const auto term : geode::Range{ model.nb_terms() } ) + { + geode::OpenGeodeStochasticStochasticException::test( + bounds[term].min == -INF, + "[ModelParameters] Wrong lower bound of term ", term ); + } + geode::OpenGeodeStochasticStochasticException::test( + bounds[DENSITY_A].max == INF && bounds[ATTRACTION_A].max == INF + && bounds[DENSITY_B].max == INF, + "[ModelParameters] A single object term, or an attraction on sets " + "with hard-cores, has no upper bound" ); + geode::OpenGeodeStochasticStochasticException::test( + bounds[REPULSION_AB].max == 0., + "[ModelParameters] A pairwise term on a set without hard-core is " + "bounded by 0" ); + geode::OpenGeodeStochasticStochasticException::test( + bounds[HARD_CORE_A].max == -INF, + "[ModelParameters] A hard-core is fixed at -inf" ); + model.forbid_attraction( DENSITY_B ); + bounds = model.theta_bounds(); + geode::OpenGeodeStochasticStochasticException::test( + bounds[DENSITY_B].max == 0., + "[ModelParameters] A term whose attraction is forbidden is bounded " + "by 0" ); + geode::Logger::info( "--> SUCCESS!" ); + } + void test_accepted() { geode::Logger::info( "TEST - VALID PARAMETERS ACCEPTED" ); @@ -663,6 +703,7 @@ int main() test_mh_sees_new_parameters(); test_rejections(); test_accepted(); + test_theta_bounds(); test_tiny_gamma_is_not_hard_core(); test_stability_with_tiny_gammas(); test_fixed_objects_violating_hard_core();