Hyperiso 1.0.3
Modular flavour-physics calculations, Wilson coefficients and statistical inference
Loading...
Searching...
No Matches
StatisticManager.h
Go to the documentation of this file.
1#ifndef STATISTIC_MANAGER_H
2#define STATISTIC_MANAGER_H
3
4#include <vector>
5#include <iomanip>
6#include <iostream>
7#include <filesystem>
8#include <optional>
9#include <limits>
10#include <numeric>
11#include <set>
12#include <random>
13#include <map>
14
15#include "Include.h"
16#include "IModel.h"
18#include "IStatParameterProxy.h"
19#include "IStatSourcesProxy.h"
22#include "JointDistribution.h"
23#include "RvgNuisanceSampler.h"
24#include "MCEngine.h"
25#include "MarginalFactory.h"
26#include "CopulaFactory.h"
27#include "Fit.h"
30#include "INuisanceReader.h"
31#include "NuisanceSpec.h"
34
59
69 std::map<ParamId, MarginalType> override_nuisance_marginals {};
70 std::map<ExperimentObs, MarginalType> override_exp_data_marginals {};
73
74 std::size_t MLE_max_iter = 500;
75 double MLE_tol = 1e-8;
76 unsigned MLE_strategy = 2;
77 bool MLE_run_hesse = true;
78 bool MLE_request_minos = false;
79 bool MLE_verbose = false;
80
89 unsigned nuisance_sensitivity_seed = 12345;
91
97
98 bool MLE_trace_first_evals = false;
99 std::size_t MLE_trace_max_evals = 25;
103
107
109 std::size_t MC_forced_decay_threads = 1;
110};
111
122 std::size_t MC_draws = 100;
123 std::size_t MC_threads = 1;
124 unsigned int MC_seed = 123456u;
125 double skew_abs_threshold = 0.2;
126
127 bool print_mc_progress = true;
129 bool print_mc_config = false;
130 bool print_fit_summary = false;
131 bool print_scan_summary = false;
132 bool print_cache_summary = false;
133 bool print_debug = false;
134
135 bool write_mc_samples_csv = false;
136 std::string mc_samples_csv_path = "obs_samples.csv";
137 std::size_t mc_progress_probe_draws = 5;
138 std::size_t mc_progress_update_every = 1;
139
140 std::shared_ptr<StatisticProgressMonitor> progress_monitor {};
141
142 std::map<ParamId, std::pair<double, double>> fit_parameter_bounds {};
143 std::map<ParamId, double> fit_parameter_offsets {};
144
146};
147
153 double x = 0.0;
154 double y = 0.0;
155 double nll = 0.0;
156 double delta_nll = 0.0;
157};
158
166 double x_center = 0.0;
167 double y_center = 0.0;
168 std::size_t nx = 0;
169 std::size_t ny = 0;
170 std::vector<LikelihoodScanPoint> points;
171};
172
178 bool fit_ok {false};
179 std::map<ParamId, double> p_hat;
180 std::map<ParamId, double> eta_hat;
181 std::map<ParamId, double> p_hat_std;
182 std::map<ParamId, std::map<ParamId, double>> p_correlations;
183 double ell_hat {0.0};
184};
185
190struct StatCache {
191 std::map<ExperimentObs, double> exp_obs;
192 std::map<ParamId, double> eta_specs_real;
193 std::map<ParamId, double> p_specs;
194 std::map<ParamId, std::map<ParamId, double>> SigmaEta;
195 std::map<ExperimentObs, std::map<ExperimentObs, double>> SigmaObs;
196
198};
199
211public:
230 std::shared_ptr<IModel> obs_int,
231 std::shared_ptr<IStatCorrelationProxy> pscp,
232 std::shared_ptr<IStatParameterProxy> pspp,
233 std::shared_ptr<IStatSourcesProxy> sp,
234 std::shared_ptr<IStatDependencyPruner> dp,
235 std::shared_ptr<INuisanceReader> nuisance_reader,
236 std::shared_ptr<IStatParamOptimizerProxy> spop);
237
242 std::vector<std::unique_ptr<IMarginalDistribution>> build_nuisance_marginal_distributions();
243
248 std::unique_ptr<JointDistribution> build_nuisance_distribution();
249
254 std::unique_ptr<JointDistribution> build_exp_data_distribution();
255
260
265 void set_nuisance_user_file(const fs::path& user_yaml_path);
266
271
273 const NuisanceRegistry& default_nuisance_specs() const { return default_nuisance_specs_; }
274
276 const NuisanceRegistry& user_nuisance_specs() const { return user_nuisance_specs_; }
277
279 const NuisanceRegistry& merged_nuisance_specs() const { return merged_nuisance_specs_; }
280
285 std::map<BinnedObservableId, GaussianSummary> compute_uncertainties();
286
292
304 FitResultWithMaps compute_MLE(const std::vector<ParamId>& p_specs);
305
318 Contour confidence_contour(ParamId p1, ParamId p2, double z, std::array<double, 4> bounds, ContourOptions options);
319
329 void prepare_likelihood_for_scan(const std::vector<ParamId>& p_specs);
330
339 void set_manual_scan_point(const std::map<ParamId, double>& p_hat,
340 const std::map<ParamId, double>& eta_hat);
341
353 ParamId p1,
354 ParamId p2,
355 double x_half_width,
356 double y_half_width,
357 std::size_t nx,
358 std::size_t ny
359 ) const;
360
366 void save_likelihood_scan_csv(const std::string& path,
367 const LikelihoodScanGrid& grid) const;
368
373 void update_cache(const std::vector<ParamId>& p_specs = std::vector<ParamId>());
374
376 void select_experiment(const std::string& experiment);
377
379 void select_experiments(const std::set<std::string>& experiments);
380
382 void select_experiments(const std::vector<std::string>& experiments);
383
386
388 bool has_experiment_selection() const noexcept;
389
391 std::set<std::string> selected_experiments() const;
392
401 void select_experiment_observables(const std::set<ExperimentObs>& observables);
402
404 void select_experiment_observables(const std::vector<ExperimentObs>& observables);
405
408
410 bool has_experiment_observable_selection() const noexcept;
411
414
419 std::map<ParamId, double> get_all_obss_deps();
420
426 std::map<ParamId, double> get_p_specs(const std::vector<ParamId>& p_specs);
427
429 std::map<ParamId, std::map<ParamId, double>> get_all_correlations();
430
433
435 std::map<ExperimentObs, double> get_obs_exp();
436
440 void print_cache();
441
442private:
444 void rebuild_merged_nuisance_specs();
445
447 void invalidate_fit_state();
448
454 const NuisanceSpec* find_nuisance_spec(const ParamId& pid) const;
455
461 MarginalType resolve_nuisance_marginal_type(const ParamId& pid) const;
462
470 fit_app::ParameterDefinition make_nuisance_parameter_definition(const ParamId& pid,
471 double value,
472 double sigma_hint) const;
473
480 MarginalConfig make_nuisance_marginal_config(const ParamId& pid,
481 MarginalType mt) const;
482
491 void validate_fit_parameter_sensitivity();
492
494 bool accepts_experiment_observable(const ExperimentObs& exp_obs) const;
495
496 std::shared_ptr<IModel> obs_int;
497 std::shared_ptr<IStatCorrelationProxy> pscp;
498 std::shared_ptr<IStatParameterProxy> pspp;
499 MarginalConfigFactory marginal_config_factory_;
500 std::shared_ptr<IStatSourcesProxy> sp;
501 std::shared_ptr<IStatDependencyPruner> dp;
502 std::shared_ptr<INuisanceReader> nuisance_reader_;
503 std::shared_ptr<IStatParamOptimizerProxy> spop;
504
505 StatisticConfig config;
506 StatCache cache;
507
508 NuisanceRegistry default_nuisance_specs_;
509 NuisanceRegistry user_nuisance_specs_;
510 NuisanceRegistry merged_nuisance_specs_;
511 std::optional<fs::path> current_user_nuisance_file_;
512
513 std::shared_ptr<LikelihoodContext> last_ctx_;
514 std::shared_ptr<BaseLikelihood> last_like_;
515 std::shared_ptr<MLFitter> last_fitter_;
516 FitResult last_fit_raw_;
517
518 std::vector<ParamId> last_fit_param_ids_;
519 std::vector<ParamId> last_nuisance_ids_;
520 std::map<ParamId, std::size_t> last_fit_param_index_;
521
522 std::vector<double> last_scan_p_;
523 std::vector<double> last_scan_eta_;
524 bool has_manual_scan_point_ = false;
525
526 std::vector<ParamId> last_detached_fit_params_;
527 std::vector<std::pair<ParameterType, std::string>> last_detached_fit_blocks_;
528
529 std::optional<std::set<std::string>> selected_experiments_;
530 std::optional<std::set<ExperimentObs>> selected_experiment_observables_;
531};
532
533#endif
Chi-square likelihood implementation for models without explicit nuisance parameters.
Factory utilities for constructing copula objects from typed configurations.
CopulaType
Identifies the copula family used to model dependence.
Definition CopulaType.h:32
@ GAUSSIAN
Gaussian copula, defined by a correlation matrix.
Helper used to transform collections of identifiers into correlation matrices/maps.
High-level maximum-likelihood fitting and confidence-contour API.
ParameterType
Abstract model interface used by the statistical layer.
Interface for loading nuisance-parameter specifications.
Statistical-layer port for read-only access to correlation coefficients.
Statistical-layer port for pruning and restoring parameter dependencies.
Statistical-layer port for batched parameter edits and optimized commits.
Statistical-layer port for read-only access to parameters and observable entries.
Statistical-layer port for retrieving leaf parameter sources.
Joint probability distribution built from marginals and a copula.
Monte Carlo propagation of nuisance-parameter uncertainties.
Factory for building marginal-distribution configuration objects.
Factory for instantiating concrete marginal distributions.
MarginalType
Supported marginal-distribution families.
Data structures for nuisance-parameter specifications.
std::unordered_map< ParamId, NuisanceSpec > NuisanceRegistry
Registry of nuisance specifications indexed by parameter id.
Nuisance sampler backed by a joint random-vector generator.
StatisticLikelihoodMode
Selects the likelihood backend used by StatisticManager::compute_MLE().
@ PROFILED_NUISANCE
Full likelihood with explicit nuisance parameters profiled during the fit.
@ CHI2_MC_COVARIANCE
Fast chi-square likelihood using MC theory covariance plus experimental covariance.
Default implementation of a profileable negative log-likelihood.
Interface for a model capable of producing observable predictions.
Definition IModel.h:42
Abstract interface for nuisance specification loaders.
Abstract port used by the statistics module to prune dependency links.
Abstract interface for batched parameter mutation in the statistics layer.
Abstract read-only interface to parameters and observables for the statistics layer.
Abstract statistics-layer interface for dependency source resolution.
High-level driver for likelihood minimization and 2D contour extraction.
Definition Fit.h:129
Builds distribution-configuration objects from parameters or observables.
Coordinates statistical inputs, nuisance distributions, MLE fits and contour/scan computations.
void select_experiments(const std::set< std::string > &experiments)
Restricts subsequent statistics to the provided set of experiment names.
void set_manual_scan_point(const std::map< ParamId, double > &p_hat, const std::map< ParamId, double > &eta_hat)
Sets the reference point used by subsequent likelihood scans.
void print_cache()
Prints the current internal cache to standard output for debugging.
std::set< ExperimentObs > selected_experiment_observables() const
LikelihoodScanGrid scan_likelihood_around_current_point(ParamId p1, ParamId p2, double x_half_width, double y_half_width, std::size_t nx, std::size_t ny) const
Evaluates the current likelihood on a regular 2D grid around the active reference point.
std::map< ExperimentObs, std::map< ExperimentObs, double > > get_all_obs_correlations()
void reload_nuisance_specs()
Reloads default and user nuisance specifications and invalidates fit state.
std::vector< std::unique_ptr< IMarginalDistribution > > build_nuisance_marginal_distributions()
Builds marginal distributions for all currently cached nuisances.
void set_nuisance_user_file(const fs::path &user_yaml_path)
Selects a custom user nuisance-definition file and reloads nuisance specifications.
std::unique_ptr< JointDistribution > build_nuisance_distribution()
Builds the joint nuisance distribution from cached nuisance marginals and correlations.
const NuisanceRegistry & default_nuisance_specs() const
bool has_experiment_observable_selection() const noexcept
void select_experiment_observables_all()
Clears the explicit experimental-observable selection.
void select_experiment_observables(const std::set< ExperimentObs > &observables)
Restricts subsequent statistics to an explicit list of experimental measurements.
void select_experiment(const std::string &experiment)
Restricts subsequent statistics to a single experiment name.
std::set< std::string > selected_experiments() const
std::map< ParamId, std::map< ParamId, double > > get_all_correlations()
void prepare_likelihood_for_scan(const std::vector< ParamId > &p_specs)
Prepares a likelihood object for manual scans without running a full MLE.
std::map< BinnedObservableId, GaussianSummary > compute_uncertainties()
Computes Gaussian summaries for MC-propagated observable uncertainties.
const NuisanceRegistry & merged_nuisance_specs() const
Contour confidence_contour(ParamId p1, ParamId p2, double z, std::array< double, 4 > bounds, ContourOptions options)
Computes a two-dimensional confidence contour for the last successful MLE.
std::map< ExperimentObs, double > get_obs_exp()
bool has_experiment_selection() const noexcept
FitResultWithMaps compute_MLE(const std::vector< ParamId > &p_specs)
Computes the maximum-likelihood fit for a selected set of fit parameters.
std::map< ParamId, double > get_p_specs(const std::vector< ParamId > &p_specs)
Resolves initial fit-parameter values from the parameter proxy.
void save_likelihood_scan_csv(const std::string &path, const LikelihoodScanGrid &grid) const
Writes a likelihood scan grid to a CSV file.
void update_cache(const std::vector< ParamId > &p_specs=std::vector< ParamId >())
Updates the full statistical cache for the selected fit parameters.
void select_experiments_all()
Clears any experiment selection and uses all available experiments.
const NuisanceRegistry & user_nuisance_specs() const
std::unique_ptr< JointDistribution > build_exp_data_distribution()
Builds the joint experimental-data distribution from cached observables and correlations.
std::map< ParamId, double > get_all_obss_deps()
Selects all nuisance dependencies relevant to the current observable set.
void clear_nuisance_user_file()
Clears the custom user nuisance file and reloads the default configured user file.
MCResult compute_uncertainties_and_sampling()
Runs MC uncertainty propagation and returns both samples and summaries.
Hash specialization for SymbolId<Tag>.
Definition BlockName.h:353
std::map< ExperimentObs, MarginalType > override_exp_data_marginals
Per-observable overrides for experimental-data marginals.
double chi2_covariance_ridge_abs
Absolute diagonal ridge used before inverting chi-square covariance matrices.
double nuisance_relevance_cutoff
Relative-uncertainty cutoff for the first nuisance preselection pass.
bool MLE_allow_profile_hessian_fallback
Allows numerical profile-Hessian covariance fallback if backend covariance fails.
bool MLE_trace_first_evals
Enables debug tracing of the first likelihood evaluations.
bool fit_parameter_sensitivity_keep_on_failure
Keeps a fit parameter when its sensitivity probe cannot be evaluated safely.
bool MLE_run_hesse
Whether to request HESSE/covariance estimation after the fit.
unsigned MLE_strategy
Backend minimization strategy; zero means backend default where supported.
double nuisance_sensitivity_probe_sigmas
Size of the +/- finite-difference probe in units of nuisance sigma.
double MLE_tol
Minimizer tolerance passed to the backend.
double fit_parameter_sensitivity_rel_cutoff
Relative observable shift required to regard a fit parameter as active.
double fit_parameter_sensitivity_probe_fraction
Minimum probe size as a fraction of explicit/default fit bounds.
bool MLE_verbose
Enables verbose output from the fit backend.
double nuisance_sensitivity_context_sigma
Randomized-context spread in nuisance sigma units.
int nuisance_sensitivity_contexts
Number of contexts tested by sensitivity pruning; negative disables the check.
double MLE_profile_hessian_step_scale
Step scaling used by the numerical profile-Hessian fallback.
double chi2_covariance_ridge_rel
Relative diagonal ridge used before inverting chi-square covariance matrices.
double nuisance_sensitivity_rel_cutoff
Relative observable shift required to keep a nuisance.
bool MLE_request_minos
Whether to request MINOS errors when supported by the backend build.
unsigned nuisance_sensitivity_seed
RNG seed used to build sensitivity-pruning contexts.
bool nuisance_sensitivity_keep_on_failure
Keeps a nuisance if its sensitivity probe fails.
std::map< ParamId, MarginalType > override_nuisance_marginals
Per-parameter overrides for nuisance marginal laws.
double fit_parameter_sensitivity_abs_cutoff
Absolute observable shift required to regard a fit parameter as active.
std::size_t MLE_max_iter
Maximum number of minimizer function calls/iterations.
double nuisance_sensitivity_scale_floor
Lower scale used when normalizing relative observable shifts.
double nuisance_sensitivity_abs_cutoff
Absolute observable shift required to keep a nuisance.
bool MC_force_decay_threads_to_one
Give MC priority over internal decay parallelism.
CopulaType nuisance_copula_type
Copula used to correlate nuisance parameters.
bool fit_parameter_sensitivity_check
Reject fit parameters that do not measurably change any selected observable.
std::size_t MLE_trace_max_evals
Maximum number of likelihood evaluations printed when tracing is enabled.
double MLE_profile_hessian_eig_floor_rel
Relative eigenvalue floor used to regularize the fallback Hessian.
StatisticLikelihoodMode likelihood_mode
Likelihood mode used by compute_MLE().
std::size_t MC_forced_decay_threads
Decay thread count while MC workers are running.
bool nuisance_sensitivity_pruning
Enables local model-sensitivity pruning of nuisance candidates.
CopulaType exp_data_copula_type
Copula used to correlate experimental observables.
Runtime options controlling 2D contour computation.
Definition Fit.h:93
Output of a contour extraction algorithm.
User-facing MLE result keyed by physics parameter identifiers.
std::map< ParamId, double > p_hat_std
Profiled standard deviations of fitted parameters.
std::map< ParamId, double > eta_hat
Best-fit/profiler values of nuisance parameters.
std::map< ParamId, std::map< ParamId, double > > p_correlations
Correlation matrix of fitted parameters.
std::map< ParamId, double > p_hat
Best-fit values of fitted parameters.
double ell_hat
Minimum negative log-likelihood value.
bool fit_ok
True when the fit returned a usable parameter estimate.
Summary of a global likelihood fit.
Abstract read-only interface for correlation queries in the statistics module.
Shared immutable-like data required to evaluate a likelihood.
Regular two-dimensional grid of likelihood-scan evaluations.
double y_center
Reference value used as the scan center on y.
double x_center
Reference value used as the scan center on x.
ParamId y_param
Identifier of the second scanned parameter.
std::vector< LikelihoodScanPoint > points
Flattened grid points in x-major order.
ParamId x_param
Identifier of the first scanned parameter.
std::size_t nx
Number of grid points along x.
std::size_t ny
Number of grid points along y.
Single point of a two-dimensional likelihood scan.
double delta_nll
Difference between nll and the minimum NLL found on the scan grid.
double x
Coordinate along the first scanned fit parameter.
double nll
Negative log-likelihood value at this point.
double y
Coordinate along the second scanned fit parameter.
Specification of one nuisance parameter.
Composite identifier for a single parameter.
Definition ParamID.h:57
Internal cache of currently selected observables, nuisances, correlations and fit state.
std::map< ParamId, double > p_specs
Selected fit parameters and their initial values.
FitResultWithMaps mle_result
Last MLE result expressed with map-based identifiers.
std::map< ExperimentObs, double > exp_obs
Experimental central values used by the current fit.
std::map< ParamId, double > eta_specs_real
Selected nuisance parameters and their central values.
std::map< ExperimentObs, std::map< ExperimentObs, double > > SigmaObs
Correlation matrix of selected experimental observables.
std::map< ParamId, std::map< ParamId, double > > SigmaEta
Correlation matrix of selected nuisances.
std::shared_ptr< StatisticProgressMonitor > progress_monitor
Optional thread-safe progress sink for GUI/notebook frontends.
std::string mc_samples_csv_path
Output CSV path used when write_mc_samples_csv is true.
bool print_scan_summary
Print likelihood-scan summaries.
bool print_fit_summary
Print high-level fit backend summaries.
unsigned int MC_seed
RNG seed used for reproducible MC nuisance and experimental-data sampling.
std::size_t mc_progress_probe_draws
Number of first accepted draws used to stabilize the first ETA.
std::map< ParamId, std::pair< double, double > > fit_parameter_bounds
Optional explicit minimizer bounds keyed by fit ParamId.
bool write_mc_samples_csv
Write accepted MC observable samples to CSV.
bool print_mc_config
Print nuisance candidates and retained MC marginal configuration.
AdvancedStatisticConfig advanced
Advanced fit/pruning/covariance configuration.
bool print_chi2_pipeline_progress
Print chi-square workflow stages after/beside the MC progress bar.
bool print_mc_progress
Print MC progress with ETA based on measured draw time.
std::size_t MC_draws
Number of accepted MC draws used for uncertainty propagation.
bool print_debug
Master debug flag for low-level diagnostic output.
std::size_t MC_threads
Number of worker threads used by MC propagation.
std::size_t mc_progress_update_every
Accepted-draw stride between progress updates.
std::map< ParamId, double > fit_parameter_offsets
Optional affine display offsets: model value = fitted value - offset.
double skew_abs_threshold
Absolute skewness threshold below which a summary is treated as symmetric.
bool print_cache_summary
Print internal cache diagnostics.