version 3.11-dev
Loading...
Searching...
No Matches
loggingparametertree.hh
Go to the documentation of this file.
1// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2// vi: set et ts=4 sw=4 sts=4:
3//
4// SPDX-FileCopyrightText: Copyright © DuMux Project contributors, see AUTHORS.md in root folder
5// SPDX-License-Identifier: GPL-3.0-or-later
6//
12#ifndef DUMUX_LOGGING_PARAMETER_TREE_HH
13#define DUMUX_LOGGING_PARAMETER_TREE_HH
14
15#include <algorithm>
16#include <array>
17#include <charconv>
18#include <iomanip>
19#include <iostream>
20#include <map>
21#include <optional>
22#include <sstream>
23#include <string>
24#include <memory>
25#include <mutex>
26#include <type_traits>
27#include <vector>
28
29#include <dune/common/parametertree.hh>
31
32namespace Dumux {
33
39{
40
41public:
42 /*
43 * \brief A logging parameter tree is always attached to an existingparameter tree
44 */
46
47 /*
48 * \brief Create LoggingParameterTree from ParameterTree
49 */
50 LoggingParameterTree(const Dune::ParameterTree& params, const Dune::ParameterTree& defaultParams)
51 : params_(params)
52 , defaultParams_(defaultParams)
53 , usedRuntimeParams_(std::make_unique<Dune::ParameterTree>())
54 , usedDefaultParams_(std::make_unique<Dune::ParameterTree>())
55 , usedFallbackDefaultParams_(std::make_unique<Dune::ParameterTree>())
56 , distinctDefaultValues_(std::make_unique<std::map<std::string, std::vector<std::string>>>())
57 {}
58
70 bool hasKey(const std::string& key) const
71 { return params_.hasKey(key); }
72
88 bool hasKeyInGroup(const std::string& key,
89 const std::string& groupPrefix) const
90 {
91 if (groupPrefix.empty())
92 return hasKey(key);
93
94 if (hasKey(key))
95 return true;
96
97 auto compoundKey = groupPrefix + "." + key;
98 if (params_.hasKey(compoundKey))
99 return true;
100
101 compoundKey = findKeyInGroup(params_, key, groupPrefix);
102 if (compoundKey != "")
103 return true;
104
105 return false;
106 }
107
131 std::vector<std::string> getSubGroups(const std::string& subGroupName,
132 std::string groupPrefix) const
133 {
134 std::vector<std::string> groupNames;
135
136 if (!groupPrefix.empty())
137 {
138 auto compoundGroup = groupPrefix + "." + subGroupName;
139 for (std::string::size_type dotPos = 0; dotPos != std::string::npos; dotPos = groupPrefix.rfind("."))
140 {
141 if (params_.hasSub(compoundGroup) || defaultParams_.hasSub(compoundGroup))
142 groupNames.push_back(compoundGroup);
143
144 groupPrefix.resize(dotPos);
145 compoundGroup = groupPrefix + "." + subGroupName;
146 }
147 }
148
149 if (params_.hasSub(subGroupName) || defaultParams_.hasSub(subGroupName))
150 groupNames.push_back(subGroupName);
151
152 return groupNames;
153 }
154
159 void report(std::ostream& stream = std::cout) const
160 { params_.report(stream); }
161
168 void reportAll(std::ostream& stream = std::cout) const
169 {
170 stream << "\n# Runtime-specified parameters used:" << std::endl;
171 usedRuntimeParams_->report(stream);
172
173 stream << "\n# Global default parameters used:" << std::endl;
174 usedDefaultParams_->report(stream);
175
176 if (logFallbackDefaults_)
177 {
178 stream << "\n# Fallback default parameters used (hardcoded at the call site in the source code):" << std::endl;
179 usedFallbackDefaultParams_->report(stream);
180
181 const auto& distinctDefaultValues = *distinctDefaultValues_;
182 if (std::ranges::any_of(distinctDefaultValues, [](const auto& entry){ return entry.second.size() > 1; }))
183 {
184 stream << "\n# Parameters used with different default values (at call sites or as global default):" << std::endl;
185 for (const auto& [key, values] : distinctDefaultValues)
186 {
187 if (values.size() > 1)
188 {
189 stream << key << " =";
190 for (const auto& value : values)
191 stream << " \"" << value << "\"";
192 stream << std::endl;
193 }
194 }
195 }
196 }
197
198 const auto unusedParams = getUnusedKeys();
199 if (!unusedParams.empty())
200 {
201 stream << "\n# Unused parameters:" << std::endl;
202 for (const auto& key : unusedParams)
203 stream << key << " = \"" << params_[key] << "\"" << std::endl;
204 }
205 }
206
218 std::string findKeyInGroup(const Dune::ParameterTree& tree,
219 const std::string& key,
220 const std::string& groupPrefix) const
221 {
222 // search backwards until key is found
223 std::string prefix = groupPrefix;
224 auto dot = prefix.rfind(".");
225 while (dot != std::string::npos)
226 {
227 prefix.resize(dot);
228 std::string compoundKey = prefix + "." + key;
229
230 if (tree.hasKey(compoundKey))
231 return compoundKey;
232
233 // look for the next dot in the current prefix
234 dot = prefix.rfind(".");
235
236 }
237
238 // the key was not found
239 return "";
240 }
241
252 std::string get(const std::string& key, const std::string& defaultValue) const
253 {
254 if (params_.hasKey(key))
255 {
256 // log that we used this parameter
257 const auto returnValue = params_[key];
258 logUsedRuntimeParam_(key, returnValue);
259 return returnValue;
260 }
261
262 if (logFallbackDefaults_)
263 logUsedFallbackDefaultParam_(key, defaultValue);
264
265 return defaultValue;
266 }
267
281 std::string getFromGroup(const std::string& groupPrefix,
282 const std::string& key,
283 const std::string& defaultValue) const
284 {
285 if (groupPrefix.empty())
286 return get(key, defaultValue);
287
288 // first, look for the compound key
289 std::string compoundKey = groupPrefix + "." + key;
290 if (params_.hasKey(compoundKey))
291 {
292 // log that we used this parameter
293 const auto returnValue = params_[compoundKey];
294 logUsedRuntimeParam_(compoundKey, returnValue);
295 return returnValue;
296 }
297
298 // search backwards until key is found
299 compoundKey = findKeyInGroup(params_, key, groupPrefix);
300 if (compoundKey != "")
301 {
302 // log that we used this parameter
303 const auto returnValue = params_[compoundKey];
304 logUsedRuntimeParam_(compoundKey, returnValue);
305 return returnValue;
306 }
307
308 // finally, look for the key without prefix
309 return get(key, defaultValue);
310 }
311
324 std::string get(const std::string& key, const char* defaultValue) const
325 {
326 const std::string dv = defaultValue;
327 return get(key, dv);
328 }
329
343 std::string getFromGroup(const std::string& groupPrefix,
344 const std::string& key,
345 const char* defaultValue) const
346 {
347 const std::string dv = defaultValue;
348 return getFromGroup(groupPrefix, key, dv);
349 }
350
351
363 template<typename T>
364 T get(const std::string& key, const T& defaultValue) const
365 {
366 if (params_.hasKey(key))
367 {
368 // log that we used this parameter
369 logUsedRuntimeParam_(key, params_[key]);
370 return params_.template get<T>(key);
371 }
372
373 if (logFallbackDefaults_)
374 logUsedFallbackDefaultParam_(key, defaultValue);
375
376 return defaultValue;
377 }
378
392 template<typename T>
393 T getFromGroup(const std::string& groupPrefix,
394 const std::string& key,
395 const T& defaultValue) const
396 {
397 if (groupPrefix.empty())
398 return get<T>(key, defaultValue);
399
400 // first, look for the compound key
401 std::string compoundKey = groupPrefix + "." + key;
402 if (params_.hasKey(compoundKey))
403 {
404 // log that we used this parameter
405 logUsedRuntimeParam_(compoundKey, params_[compoundKey]);
406 return params_.template get<T>(compoundKey);
407 }
408
409 // search backwards until key is found
410 compoundKey = findKeyInGroup(params_, key, groupPrefix);
411 if (compoundKey != "")
412 {
413 // log that we used this parameter
414 logUsedRuntimeParam_(compoundKey, params_[compoundKey]);
415 return params_.template get<T>(compoundKey);
416 }
417
418 // finally, look for the key without prefix
419 return get<T>(key, defaultValue);
420 }
421
432 template <class T>
433 T get(const std::string& key) const
434 {
435 if (params_.hasKey(key))
436 {
437 // log that we used this parameter
438 logUsedRuntimeParam_(key, params_[key]);
439 return params_.template get<T>(key);
440 }
441
442 else if(defaultParams_.hasKey(key))
443 {
444 // use the default
445 logUsedDefaultParam_(key, defaultParams_[key]);
446 return defaultParams_.template get<T>(key);
447 }
448
449 DUNE_THROW(Dumux::ParameterException, "Key " << key << " not found in the parameter tree");
450 }
451
464 template<typename T>
465 T getFromGroup(const std::string& groupPrefix,
466 const std::string& key) const
467 {
468 if (groupPrefix.empty())
469 return get<T>(key);
470
471 // first, look for the compound key
472 std::string compoundKey = groupPrefix + "." + key;
473 if (params_.hasKey(compoundKey))
474 {
475 // log that we used this parameter
476 logUsedRuntimeParam_(compoundKey, params_[compoundKey]);
477 return params_.template get<T>(compoundKey);
478 }
479
480 // search backwards until key is found
481 compoundKey = findKeyInGroup(params_, key, groupPrefix);
482 if (compoundKey != "")
483 {
484 // log that we used this parameter
485 logUsedRuntimeParam_(compoundKey, params_[compoundKey]);
486 return params_.template get<T>(compoundKey);
487 }
488
489 // reset the compoundKey
490 compoundKey = groupPrefix + "." + key;
491
492 // if the backward search did not succeed, try the bare key without any prefix
493 if (params_.hasKey(key))
494 {
495 // log that we used this parameter
496 logUsedRuntimeParam_(key, params_[key]);
497 return params_.template get<T>(key);
498 }
499
500 // if this did not work, repeat the procedure using the default parameters
501 else if(defaultParams_.hasKey(compoundKey))
502 {
503 // use the default
504 logUsedDefaultParam_(compoundKey, defaultParams_[compoundKey]);
505 return defaultParams_.template get<T>(compoundKey);
506 }
507
508 else
509 {
510 // search backwards until key is found
511 compoundKey = findKeyInGroup(defaultParams_, key, groupPrefix);
512 if (compoundKey != "")
513 {
514 // log that we used this parameter
515 logUsedDefaultParam_(compoundKey, defaultParams_[compoundKey]);
516 return defaultParams_.template get<T>(compoundKey);
517 }
518
519 if(defaultParams_.hasKey(key))
520 {
521 // use the default
522 logUsedDefaultParam_(key, defaultParams_[key]);
523 return defaultParams_.template get<T>(key);
524 }
525
526 DUNE_THROW(Dumux::ParameterException, "Key " << key << " not found in the parameter tree with group prefix " << groupPrefix);
527 }
528 }
529
535 std::vector<std::string> getUnusedKeys() const
536 {
537 std::vector<std::string> unusedParams;
538 findUnusedKeys_(params_, unusedParams);
539 return unusedParams;
540 }
541
545 {
546 std::scoped_lock lock{ usedRuntimeMutex_, usedDefaultMutex_, usedFallbackDefaultMutex_ };
547 *usedRuntimeParams_ = Dune::ParameterTree{};
548 *usedDefaultParams_ = Dune::ParameterTree{};
549 *usedFallbackDefaultParams_ = Dune::ParameterTree{};
550 distinctDefaultValues_->clear();
551 }
552
558 void setLogFallbackDefaults(bool enable)
559 { logFallbackDefaults_ = enable; }
560
561private:
568 void findUnusedKeys_(const Dune::ParameterTree& tree,
569 std::vector<std::string>& unusedParams,
570 const std::string& prefix = "") const
571 {
572 // loop over all keys of the current tree
573 // store keys which were not accessed
574 const auto& keys = tree.getValueKeys();
575 for (const auto& key : keys)
576 if (key != "ParameterFile" && !usedRuntimeParams_->hasKey(prefix + key))
577 unusedParams.push_back(prefix + key);
578
579 // recursively loop over all subtrees
580 const auto& subTreeKeys = tree.getSubKeys();
581 for (const auto& key : subTreeKeys)
582 findUnusedKeys_(tree.sub(key), unusedParams, prefix + key + ".");
583 }
584
587 void logUsedRuntimeParam_(const std::string& key, const std::string& value) const
588 {
589 std::scoped_lock lock{ usedRuntimeMutex_ };
590 usedRuntimeParams_->operator[](key) = value;
591 }
592
595 void logUsedDefaultParam_(const std::string& key, const std::string& value) const
596 {
597 std::scoped_lock lock{ usedDefaultMutex_ };
598 usedDefaultParams_->operator[](key) = value;
599 }
600
604 template<class T>
605 void logUsedFallbackDefaultParam_(const std::string& key, const T& defaultValue) const
606 {
607 const auto value = toParameterString_(defaultValue);
608 if (!value)
609 return;
610
611 std::optional<std::string> globalDefault;
612 if (defaultParams_.hasKey(key))
613 {
614 // compare in the representation of the call-site default, e.g. "1e300" and 1e300 are the same value
615 try { globalDefault = toParameterString_(defaultParams_.template get<T>(key)); }
616 catch (const Dune::RangeError&) { globalDefault = defaultParams_[key]; }
617 }
618
619 std::scoped_lock lock{ usedFallbackDefaultMutex_ };
620 usedFallbackDefaultParams_->operator[](key) = *value;
621
622 auto& values = (*distinctDefaultValues_)[key];
623 const auto addIfNew = [&](const std::string& v){
624 if (std::ranges::find(values, v) == values.end())
625 values.push_back(v);
626 };
627 addIfNew(*value);
628 if (globalDefault)
629 addIfNew(*globalDefault);
630 }
631
634 template<class T>
635 static std::optional<std::string> toParameterString_(const T& value)
636 {
637 if constexpr (std::is_same_v<T, std::string>)
638 return value;
639 else if constexpr (std::is_same_v<T, bool>)
640 return value ? "true" : "false";
641 else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double>)
642 {
643 // the shortest representation that is read back as the same value
644 std::array<char, 32> buffer;
645 const auto end = std::to_chars(buffer.data(), buffer.data() + buffer.size(), value).ptr;
646 return std::string(buffer.data(), end);
647 }
648 // ranges, but not ranges of their own type such as std::filesystem::path
649 else if constexpr (requires { std::end(value); requires !std::is_same_v<std::decay_t<decltype(*std::begin(value))>, T>; })
650 {
651 std::string result;
652 for (bool first = true; const auto& entry : value)
653 {
654 const auto entryString = toParameterString_(entry);
655 if (!entryString)
656 return std::nullopt;
657
658 result += (first ? "" : " ") + *entryString;
659 first = false;
660 }
661 return result;
662 }
663 else if constexpr (requires (std::ostream& stream) { stream << value; })
664 {
665 std::ostringstream stream;
666 stream << value;
667 return stream.str();
668 }
669 else
670 return std::nullopt;
671 }
672
673 const Dune::ParameterTree& params_;
674 const Dune::ParameterTree& defaultParams_;
675
676 // logging caches (externally stored)
677 std::unique_ptr<Dune::ParameterTree> usedRuntimeParams_;
678 std::unique_ptr<Dune::ParameterTree> usedDefaultParams_;
679 std::unique_ptr<Dune::ParameterTree> usedFallbackDefaultParams_;
680 std::unique_ptr<std::map<std::string, std::vector<std::string>>> distinctDefaultValues_;
681
682 // access to the caches have to be protected for thread-safety
683 mutable std::mutex usedRuntimeMutex_;
684 mutable std::mutex usedDefaultMutex_;
685 mutable std::mutex usedFallbackDefaultMutex_;
686
687 bool logFallbackDefaults_ = false;
688};
689
690} // end namespace Dumux
691
692#endif
std::string getFromGroup(const std::string &groupPrefix, const std::string &key, const std::string &defaultValue) const
get value as string, preferably from the sub-tree corresponding to a given prefix....
Definition loggingparametertree.hh:281
T getFromGroup(const std::string &groupPrefix, const std::string &key, const T &defaultValue) const
get value as string, preferably from the sub-tree corresponding to a given prefix....
Definition loggingparametertree.hh:393
void report(std::ostream &stream=std::cout) const
print the hierarchical parameter tree to stream
Definition loggingparametertree.hh:159
std::string get(const std::string &key, const std::string &defaultValue) const
get value as string
Definition loggingparametertree.hh:252
void reportAll(std::ostream &stream=std::cout) const
print distinct substructure to stream
Definition loggingparametertree.hh:168
std::string findKeyInGroup(const Dune::ParameterTree &tree, const std::string &key, const std::string &groupPrefix) const
Do a backwards hierarchical search for a key in a group.
Definition loggingparametertree.hh:218
std::string getFromGroup(const std::string &groupPrefix, const std::string &key, const char *defaultValue) const
get value as string, preferably from the sub-tree corresponding to a given prefix....
Definition loggingparametertree.hh:343
std::vector< std::string > getSubGroups(const std::string &subGroupName, std::string groupPrefix) const
obtain a vector of all full group names for a specified subgroup name
Definition loggingparametertree.hh:131
bool hasKeyInGroup(const std::string &key, const std::string &groupPrefix) const
test for key in group
Definition loggingparametertree.hh:88
std::string get(const std::string &key, const char *defaultValue) const
get value as string
Definition loggingparametertree.hh:324
T get(const std::string &key) const
Get value.
Definition loggingparametertree.hh:433
LoggingParameterTree(const Dune::ParameterTree &params, const Dune::ParameterTree &defaultParams)
Definition loggingparametertree.hh:50
void clearUsageLog()
Forget which parameters have been used.
Definition loggingparametertree.hh:544
std::vector< std::string > getUnusedKeys() const
Find the keys that haven't been used yet.
Definition loggingparametertree.hh:535
T get(const std::string &key, const T &defaultValue) const
get value converted to a certain type
Definition loggingparametertree.hh:364
T getFromGroup(const std::string &groupPrefix, const std::string &key) const
get value as string, preferably from the sub-tree corresponding to a given prefix....
Definition loggingparametertree.hh:465
void setLogFallbackDefaults(bool enable)
Also log parameters that fall back to the default value given at the call site.
Definition loggingparametertree.hh:558
bool hasKey(const std::string &key) const
test for key
Definition loggingparametertree.hh:70
Exception thrown if a run-time parameter is not specified correctly.
Definition exceptions.hh:48
Some exceptions thrown in DuMux.
Definition adapt.hh:17
Definition common/pdesolver.hh:24