Hyperiso 1.0.3
Modular flavour-physics calculations, Wilson coefficients and statistical inference
Loading...
Searching...
No Matches
MemoryManager.cpp
Go to the documentation of this file.
1#include "MemoryManager.h"
2#include "Parameters.h"
3
4#include <system_error>
5
6MemoryManager* MemoryManager::instance = nullptr;
7
8MemoryManager::MemoryManager() : memento(DBMemento()) {
9 this->cache.is_ready = false;
10}
11
12void MemoryManager::check_if_ready() {
13 if (!cache.is_ready) {
14 LOG_ERROR("MemoryManager", "Please init the memory manager before using it.");
15 }
16}
17
18std::shared_ptr<BlockAccessor> MemoryManager::extract_blocks(std::unordered_set<BlockName> block_names) {
19 return (*input_cache)[block_names];
20}
21
22std::shared_ptr<BlockAccessor> MemoryManager::extract_block_accessor() {
23 auto global_ba = std::make_shared<BlockAccessor>();
24
25 for (auto type : cache.parameter_types)
26 {
27 auto params = Parameters::GetInstance(type);
28 if (!params)
29 continue;
30
31 auto ba = params->get_block_accessor();
32 if (!ba)
33 continue;
34
35 for (const auto& [block_name, block_ptr] : *ba)
36 {
37 global_ba->emplace(block_name, block_ptr);
38 }
39 }
40
41 if (input_cache)
42 {
43 for (const auto& [block_name, block_ptr] : *input_cache)
44 {
45 if (!global_ba->contains(block_name))
46 {
47 global_ba->emplace(block_name, block_ptr);
48 }
49 }
50 }
51 return global_ba;
52}
53
54std::shared_ptr<BlockAccessor> MemoryManager::clone_input_cache_deep() const {
55 if (!input_cache) {
56 return std::make_shared<BlockAccessor>();
57 }
58 return input_cache->deep_clone_plain();
59}
60
62 check_if_ready();
63 return correlation_repository;
64}
65
66void MemoryManager::save_input_cache() {
67 memento.takeSnapshot(input_cache);
68}
69
70void MemoryManager::read_default_input() {
71 dl_ba->load(input_cache, paths_provider->default_param_values());
72 auto obs_blocks = std::make_shared<BlockAccessor>();
73 dl_ba->load(obs_blocks, paths_provider->default_obs_values(), true);
74 input_cache = input_cache >> obs_blocks;
75 save_input_cache();
76 LOG_VERBOSE("Default cache stored");
77
78 auto default_param_corr = std::make_shared<CorrelationMatrixPair<ParamId>>();
79 dl_cmp_p->load(default_param_corr, paths_provider->default_param_corr().string());
80 LOG_VERBOSE("Default param correlations loaded");
81 auto default_obs_corr = std::make_shared<CorrelationMatrixPair<ExperimentObs>>();
82 dl_cmp_o->load(default_obs_corr, paths_provider->default_obs_corr().string());
83 LOG_VERBOSE("Default observable correlations loaded");
84 correlation_repository.set_correlation_matrix(default_param_corr);
85 correlation_repository.set_correlation_matrix(default_obs_corr);
86
87 LOG_VERBOSE("Default files loaded");
88}
89
90void MemoryManager::read_user_input() {
91 // ParamBlockLoader p_loader;
92 fs::path ui_paths[3] = {
93 paths_provider->user_sm_params(), paths_provider->user_flavor_params(),
94 paths_provider->user_decay_params()
95 };
96 for (auto& path : ui_paths) {
97 auto ui_ba = std::make_shared<BlockAccessor>();
98 dl_ba->load(ui_ba, path);
99 input_cache = ui_ba >> input_cache;
100 }
101
102 auto ui_ba_obs = std::make_shared<BlockAccessor>();
103 dl_ba->load(ui_ba_obs, paths_provider->user_obs_values(), true);
104 input_cache = ui_ba_obs >> input_cache;
105
106 save_input_cache();
107
108 auto user_param_corr = std::make_shared<CorrelationMatrixPair<ParamId>>();
109 dl_cmp_p->load(user_param_corr, paths_provider->user_param_corr().string());
110 auto user_obs_corr = std::make_shared<CorrelationMatrixPair<ExperimentObs>>();
111 dl_cmp_o->load(user_obs_corr, paths_provider->user_obs_corr().string());
112 correlation_repository.merge_correlation_matrix(user_param_corr);
113 correlation_repository.merge_correlation_matrix(user_obs_corr);
114
115 LOG_VERBOSE("User input files loaded");
116}
117
118void MemoryManager::read_lha_input(const std::string& lhaFile, const HyperisoConfig& config) {
119 fs::path lha_path = this->format_lha_path(lhaFile);
120 fs::path spectrum_path = calculate_spectrum(lha_path, config);
121
122 auto lha_ba = std::make_shared<BlockAccessor>();
123 dl_ba->load(lha_ba, spectrum_path);
124 input_cache = lha_ba >> input_cache;
125 save_input_cache();
126
127 LOG_VERBOSE("LHA file loaded");
128}
129
130fs::path MemoryManager::calculate_spectrum(fs::path input_lha_path, const HyperisoConfig &config) {
131 if (!(config.model == Model::THDM || config.model == Model::SUSY)) {
132 return input_lha_path;
133 }
134
135 if(config.flags.at(ExternalFlag::IS_LHA_SPECTRUM)) {
136 return input_lha_path;
137 }
138
139 if (!sc) {
140 LOG_WARN("MemoryManager", "No ISpectrumCalculator provided, skipping spectrum calculation.");
141 return input_lha_path;
142 }
143
144 fs::path spectrum_dir = paths_provider->spectrum_dir();
145 std::error_code ec;
146 fs::create_directories(spectrum_dir, ec);
147 if (ec) {
148 LOG_ERROR("MemoryManager", "Cannot create spectrum cache directory:", spectrum_dir.string(), ec.message());
149 return input_lha_path;
150 }
151
152 fs::path spectrum_path = spectrum_dir / input_lha_path.filename();
153 sc->calculate_spectrum(input_lha_path, spectrum_path, config.model);
154 return spectrum_path;
155}
156
158 if (!MemoryManager::instance) {
159 MemoryManager::instance = new MemoryManager();
160 }
161 return MemoryManager::instance;
162}
163
164MemoryManager::MemoryManager(std::shared_ptr<IDataLoader<BlockAccessor>> loader, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ParamId>>> param_corr, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ExperimentObs>>> obs_corr, std::shared_ptr<ISpectrumCalculator> spectrum_c, std::shared_ptr<IPathsProvider> paths_provider_, std::shared_ptr<ILhaPrototypeRegistry> lha_prototype_registry_) : memento(DBMemento()) {
165 this->sc = spectrum_c;
166
167 this->dl_ba = loader;
168 this->dl_cmp_p = param_corr;
169 this->dl_cmp_o = obs_corr;
170
171 this->paths_provider = paths_provider_;
172 this->lha_prototype_registry = lha_prototype_registry_;
173 this->cache.is_ready = false;
174}
175
176// MemoryManager* MemoryManager::Create(std::shared_ptr<IDataLoader<BlockAccessor>> loader, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ParamId>>> param_corr, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ExperimentObs>>> obs_corr, std::shared_ptr<ISpectrumCalculator> spectrum_c, std::shared_ptr<IPathsProvider> paths_provider) {
177// if (!MemoryManager::instance) {
178// MemoryManager::instance = new MemoryManager(loader, param_corr, obs_corr, spectrum_c, paths_provider);
179// }
180// return MemoryManager::instance;
181// }
182
183MemoryManager* MemoryManager::Create(std::shared_ptr<IDataLoader<BlockAccessor>> loader, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ParamId>>> param_corr, std::shared_ptr<IDataLoader<CorrelationMatrixPair<ExperimentObs>>> obs_corr, std::shared_ptr<ISpectrumCalculator> spectrum_c, std::shared_ptr<IPathsProvider> paths_provider, std::shared_ptr<ILhaPrototypeRegistry> lha_prototype_registry) {
184 if (!MemoryManager::instance) {
185 MemoryManager::instance = new MemoryManager(loader, param_corr, obs_corr, spectrum_c, paths_provider, lha_prototype_registry);
186 } else if (!MemoryManager::instance->dl_ba && !MemoryManager::instance->cache.is_ready) {
187 // Allows a default-created singleton to be wired later through ports.
188 MemoryManager::instance->dl_ba = loader;
189 MemoryManager::instance->dl_cmp_p = param_corr;
190 MemoryManager::instance->dl_cmp_o = obs_corr;
191 MemoryManager::instance->sc = spectrum_c;
192 MemoryManager::instance->paths_provider = paths_provider;
193 MemoryManager::instance->lha_prototype_registry = lha_prototype_registry;
194 }
195 return MemoryManager::instance;
196}
197
198void MemoryManager::set_paths_provider(std::shared_ptr<IPathsProvider> paths_provider_) {
199 if (!paths_provider_) {
200 LOG_ERROR("MemoryManager", "Cannot install a null IPathsProvider.");
201 return;
202 }
203
204 if (cache.is_ready) {
205 LOG_WARN("MemoryManager", "set_paths_provider called after init; it will only affect future reload or switch operations.");
206 }
207
208 this->paths_provider = std::move(paths_provider_);
209}
210
211fs::path MemoryManager::get_path(APIPath path_name) {
212 if (path_name == APIPath::LHA_PATH) {
213 check_if_ready();
214 return cache.lha_path;
215 }
216
217 if (!paths_provider) {
218 LOG_ERROR("MemoryManager", "No IPathsProvider was provided.");
219 return {};
220 }
221
222 switch (path_name) {
224 return paths_provider->assets_root();
226 return paths_provider->default_param_values();
228 return paths_provider->default_obs_values();
230 return paths_provider->default_param_corr();
232 return paths_provider->default_obs_corr();
234 return paths_provider->default_nuisances();
236 return paths_provider->user_sm_params();
238 return paths_provider->user_flavor_params();
240 return paths_provider->user_decay_params();
242 return paths_provider->user_obs_values();
244 return paths_provider->user_param_corr();
246 return paths_provider->user_obs_corr();
248 return paths_provider->user_nuisances();
250 return paths_provider->param_mapping_dir_path();
252 return paths_provider->template_dir_path();
254 return paths_provider->spectrum_dir();
256 return paths_provider->marty_temp_dir();
258 break;
259 }
260
261 LOG_ERROR("MemoryManager", "Unknown path for APIAdapter.");
262 return {};
263}
264
266 size_t itemCount,
267 size_t valueIdx,
268 int scaleIdx,
269 int rgIdx,
270 int binIdx,
271 bool globalScale)
272{
273 if (cache.is_ready) {
274 LOG_WARN("MemoryManager", "add_lha_prototype called after init; it will only affect future LHA reloads.");
275 }
276
277 if (!lha_prototype_registry) {
278 LOG_ERROR("MemoryManager", "No ILhaPrototypeRegistry port was provided.");
279 return;
280 }
281
282 lha_prototype_registry->add_lha_prototype(blockName,
283 itemCount,
284 valueIdx,
285 scaleIdx,
286 rgIdx,
287 binIdx,
288 globalScale);
289
291}
292
293void MemoryManager::add_lha_prototypes(const std::vector<LhaPrototypeSpec>& prototypes)
294{
295 for (const auto& prototype : prototypes) {
296 add_lha_prototype(prototype.blockName,
297 prototype.itemCount,
298 prototype.valueIdx,
299 prototype.scaleIdx,
300 prototype.rgIdx,
301 prototype.binIdx,
302 prototype.globalScale);
303 }
304}
305
306void MemoryManager::init(const std::string& lhaFile, HyperisoConfig config) {
307 if (cache.is_ready) {
308 LOG_WARN("MemoryManager has already been initialized.");
309 return;
310 }
311
312 input_cache = std::make_shared<BlockAccessor>();
313 this->read_default_input();
314 this->read_user_input();
315 this->read_lha_input(lhaFile, config);
316 cache.lha_path = lhaFile;
317 cache.config = config;
318 cache.thread_id = std::this_thread::get_id();
319 this->deduce_parameter_types(config);
320 cache.is_ready = true;
321
322 LOG_DEBUG("Hyperiso successfully initialized !");
323}
324
325void MemoryManager::deduce_parameter_types(const HyperisoConfig &config) {
332 const bool has_custom_bsm_blocks = !ParameterBlockRepartition::custom_bsm_blocks().empty();
333
334 if (config.model != Model::SM || has_custom_bsm_blocks) {
335 cache.parameter_types.push_back(ParameterType::BSM);
336 }
337}
338
339void MemoryManager::switch_lha(const std::string& lhaFile, HyperisoConfig config) {
340 ReadyGuard guard(cache.is_ready);
341 memento.restore();
342 this->read_lha_input(lhaFile, config);
343 cache.lha_path = lhaFile;
344 cache.config = std::move(config);
345 this->deduce_parameter_types(cache.config);
346
348
349 this->cache.flags[InternalFlag::PARAMS_CHANGED] = true;
350}
351
355
356void MemoryManager::reload_user_input(const std::string &lhaFile, HyperisoConfig config) {
357 ReadyGuard guard(cache.is_ready);
358 memento.restore(2);
359 this->read_user_input();
360 this->read_lha_input(lhaFile, config);
361
362 cache.lha_path = lhaFile;
363 cache.config = std::move(config);
364 this->deduce_parameter_types(cache.config);
365 this->cache.flags[InternalFlag::PARAMS_CHANGED] = true;
366
367}
368
369fs::path MemoryManager::format_lha_path(const std::string &path) {
370 const fs::path input_path(path);
371 const fs::path assets_dir = paths_provider->assets_root();
372 fs::path full_path;
373 if (input_path.is_relative()) { // Path is specified relative to Assets/
374 full_path = assets_dir/path;
375 } else if (input_path.is_absolute()) {
376 full_path = path;
377 } else {
378 LOG_ERROR("MemoryManager", "LHA File path is undefined:", path);
379 }
380
381 if (!std::filesystem::exists(full_path)) {
382 LOG_ERROR("MemoryManager", "Cannot find LHA File:", full_path.string());
383 }
384
385 LOG_DEBUG("LHA File path:", full_path);
386 return full_path;
387}
388
390 this->cache.config.model = model;
391 this->deduce_parameter_types(this->cache.config);
392 this->cache.flags[InternalFlag::PARAMS_CHANGED] = true;
393}
394
395std::unordered_set<ParamId>
396MemoryManager::get_all_source_parameters(const std::unordered_set<ParamId>& param_ids) const
397{
398
399 auto global_ba = std::make_shared<BlockAccessor>();
400
401 for (auto type : cache.parameter_types)
402 {
403 auto params = Parameters::GetInstance(type);
404 if (!params)
405 continue;
406
407 auto ba = params->get_block_accessor();
408 if (!ba)
409 continue;
410
411 for (const auto& [block_name, block_ptr] : *ba)
412 {
413 global_ba->emplace(block_name, block_ptr);
414 }
415 }
416
417 if (input_cache)
418 {
419 for (const auto& [block_name, block_ptr] : *input_cache)
420 {
421 if (!global_ba->contains(block_name))
422 {
423 global_ba->emplace(block_name, block_ptr);
424 }
425 }
426 }
427
428 return global_ba->get_all_source_parameters(param_ids);
429}
@ IS_LHA_SPECTRUM
Input LHA file already contains a spectrum.
Model
APIPath
Enumerates the filesystem paths exposed through the public API.
@ USER_OBS_VALUES
YAML/YML file containing user observable overrides.
@ DEFAULT_NUISANCES
JSON file containing default nuisance definitions.
@ USER_OBS_CORR
YAML/YML file containing user observable correlation overrides.
@ USER_NUISANCES
YAML/YML file containing user nuisance overrides.
@ TEMPLATE_DIR
Read-only directory containing generated-code templates.
@ DEFAULT_OBS_CORR
JSON file containing default observable correlations.
@ USER_PARAM_CORR
YAML/YML file containing user parameter correlation overrides.
@ DEFAULT_PARAM_VALUES
JSON file containing default parameter values.
@ USER_SM_PARAMS
YAML/YML file containing user SM parameter overrides.
@ DEFAULT_OBS_VALUES
JSON file containing default observable values.
@ MARTY_TEMP_DIR
Writable cache directory used for generated MARTY files.
@ LHA_PATH
Path to the active LHA file.
@ PARAM_MAPPING_DIR
Read-only directory containing MARTY/Hyperiso parameter mappings.
@ SPECTRUM_DIR
Writable cache directory used for generated spectrum files.
@ USER_FLAVOR_PARAMS
YAML/YML file containing user flavor parameter overrides.
@ ASSETS_ROOT
Root directory for HyperISO read-only assets.
@ DEFAULT_PARAM_CORR
JSON file containing default parameter correlations.
@ USER_DECAY_PARAMS
YAML/YML file containing user decay parameter overrides.
#define LOG_ERROR(type,...)
Macro for logging error messages and terminating the application.
Definition Logger.h:41
#define LOG_DEBUG(...)
Macro for logging debug messages.
Definition Logger.h:45
#define LOG_VERBOSE(...)
Macro for logging verbose messages.
Definition Logger.h:47
#define LOG_WARN(...)
Macro for logging warning messages.
Definition Logger.h:40
Manages memory caching, parameter blocks, and LHA reader instances.
Model-dependent parameter repository and initialization strategies.
Block identifier with alias support.
Definition BlockName.h:59
Manages correlations between parameters and experiment-scoped observables.
void set_correlation_matrix(std::shared_ptr< CorrelationMatrixPair< ParamId > > correlation_matrices)
Sets (replaces) the correlation matrix for parameters.
void merge_correlation_matrix(std::shared_ptr< CorrelationMatrixPair< ParamId > > correlation_matrix)
Merges a new correlation matrix into the existing parameter correlations.
Stack-based implementation of IDBMemento for BlockAccessor.
Definition DBMemento.h:39
void takeSnapshot(std::shared_ptr< BlockAccessor > blocks)
Takes a snapshot of the given BlockAccessor.
Definition DBMemento.cpp:3
void restore(size_t n_steps=1)
Restores the state n_steps snapshots back.
Definition DBMemento.cpp:7
Abstract interface for loading data into an object.
Definition IDataLoader.h:60
Singleton class responsible for initializing and managing memory, input files, and parameter blocks.
std::shared_ptr< BlockAccessor > extract_block_accessor()
Extracts all blocks from the cached input.
std::shared_ptr< BlockAccessor > clone_input_cache_deep() const
Deep-clones the raw input cache as independent plain blocks.
void reload_user_input(HyperisoConfig config)
Reloads user-specific input files.
void set_paths_provider(std::shared_ptr< IPathsProvider > paths_provider_)
Replaces the filesystem path provider used by the manager.
void switch_lha(const std::string &lhaFile, HyperisoConfig config)
Registers several additional LHA block prototypes.
std::unordered_set< ParamId > get_all_source_parameters(const std::unordered_set< ParamId > &param_ids) const
Computes all ultimate "source" parameters for a given set of parameter IDs.
void init(const std::string &lhaFile, HyperisoConfig config)
Initializes the memory manager with the provided LHA file and configuration.
static MemoryManager * GetInstance()
Retrieves the singleton instance of MemoryManager.
static MemoryManager * Create(std::shared_ptr< IDataLoader< BlockAccessor > > loader, std::shared_ptr< IDataLoader< CorrelationMatrixPair< ParamId > > > param_corr, std::shared_ptr< IDataLoader< CorrelationMatrixPair< ExperimentObs > > > obs_corr, std::shared_ptr< ISpectrumCalculator > spectrum_c, std::shared_ptr< IPathsProvider > paths_provider, std::shared_ptr< ILhaPrototypeRegistry > lha_prototype_registry=nullptr)
Retrieves/creates the singleton instance of MemoryManager with injected dependencies.
const CorrelationRepository & get_correlation_repository()
Retrieves the current correlation repository.
void switch_model(Model model=Model::SM)
Switches the model used for spectrum and parameters.
fs::path get_path(APIPath path_name)
Retrieves a public API path from the runtime cache or path provider.
std::shared_ptr< BlockAccessor > extract_blocks(std::unordered_set< BlockName > block_names)
Extracts specific blocks from the cached input.
void add_lha_prototypes(const std::vector< LhaPrototypeSpec > &prototypes)
Registers several additional LHA block prototypes through the injected port.
void add_lha_prototype(BlockName blockName, size_t itemCount=2, size_t valueIdx=1, int scaleIdx=-1, int rgIdx=-1, int binIdx=-1, bool globalScale=false)
Registers an additional LHA block prototype before LHA parsing.
static void clear()
static std::shared_ptr< Parameters > GetInstance(ParameterType id=ParameterType::SM)
Returns the singleton-like repository for a given parameter type.
Stores a pair of correlation matrices (statistical and systematic) for a given key type.
Configuration object controlling model, input flags and optional MARTY resources.
Definition Config.h:24
std::map< ExternalFlag, bool > flags
External flags describing the nature of the inputs.
Definition Config.h:26
Model model
Current model.
Definition Config.h:33
std::vector< ParameterType > parameter_types
List of parameter types currently managed.
bool is_ready
Indicates if the memory manager is initialized and ready.
std::thread::id thread_id
Thread ID associated with the current cache usage.
std::map< InternalFlag, bool > flags
Internal status flags.
HyperisoConfig config
Config struct for various flags and runtime information.
fs::path lha_path
Path to the currently loaded LHA file.
static const std::unordered_set< BlockName > & custom_bsm_blocks()
Returns the registered runtime BSM blocks.
static void register_custom_bsm_block(BlockName blockName)
Registers one runtime block as BSM-owned.
RAII guard to toggle the "ready" flag while performing unsafe operations.