3.4
DUNE for Multi-{Phase, Component, Scale, Physics, ...} flow and transport in porous media
parameters.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 * See the file COPYING for full copying permissions. *
5 * *
6 * This program is free software: you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation, either version 3 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program. If not, see <http://www.gnu.org/licenses/>. *
18 *****************************************************************************/
24#ifndef DUMUX_PARAMETERS_HH
25#define DUMUX_PARAMETERS_HH
26
27#include <iostream>
28#include <list>
29#include <sstream>
30#include <unordered_map>
31#include <fstream>
32#include <functional>
33
34#include <dune/common/parametertree.hh>
35#include <dune/common/parametertreeparser.hh>
36#include <dune/common/parallel/mpihelper.hh>
37
41
42namespace Dumux {
43
50
51 using DefaultParams = std::function<void (Dune::ParameterTree&)>;
52 using Usage = std::function<void (const char *, const std::string &)>;
53
54public:
55
57 static void init(int argc, char **argv, const Usage& usage)
58 {
59 init(argc, argv, [] (Dune::ParameterTree&) {}, "", usage);
60 }
61
63 static void init(int argc, char **argv,
64 std::string parameterFileName,
65 const Usage& usage = [](const char *, const std::string &){})
66 {
67 init(argc, argv, [] (Dune::ParameterTree&) {}, parameterFileName, usage);
68 }
69
71 static void init(int argc, char **argv,
72 const DefaultParams& defaultParams,
73 const Usage& usage)
74 {
75 init(argc, argv, defaultParams, "", usage);
76 }
77
94 static void init(int argc, char **argv,
95 const DefaultParams& defaultParams = [] (Dune::ParameterTree&) {},
96 std::string parameterFileName = "",
97 const Usage& usage = [](const char *, const std::string &){})
98 {
99 const auto& mpiHelper = Dune::MPIHelper::instance(argc, argv);
100
101 // check whether the user wanted to see the help message
102 for (int i = 1; i < argc; ++i)
103 {
104 if (std::string("--help") == argv[i] || std::string("-h") == argv[i])
105 {
106 // return usage message and return;
107 if (mpiHelper.rank() == 0)
108 usage(argv[0], defaultUsageMessage(argv[0]));
109
110 exit(0);
111 }
112 }
113
114 // apply the default parameters
115 defaultParams(defaultParamTree_());
116 applyGlobalDefaults_(defaultParamTree_());
117
118 // parse paramters from the command line
119 const auto commandLineArgs = parseCommandLine(argc, argv);
120 mergeTree_(paramTree_(), commandLineArgs);
121
122 // overwrite parameter file if one was specified on the command line
123 parameterFileName = commandLineArgs.get<std::string>("ParameterFile", parameterFileName);
124
125 // otherwise use the default name (executable name + .input)
126 if (parameterFileName.empty())
127 {
128 parameterFileName = [&](){
129 std::string defaultName = std::string(argv[0]) + ".input";
130 std::ifstream pFile(defaultName.c_str());
131 if (pFile.is_open())
132 return defaultName;
133
134 defaultName = "params.input";
135 pFile = std::ifstream(defaultName.c_str());
136 if (pFile.is_open())
137 return defaultName;
138 else
139 return std::string("");
140 }();
141
142 // if no parameter file was given and also no default names where found, continue without
143 if (parameterFileName.empty())
144 {
145 if (mpiHelper.size() > 1)
146 std::cout << "Rank " << mpiHelper.rank() << ": ";
147 std::cout << "No parameter file found. Continuing without parameter file.\n";
148
149 return;
150 }
151 else
152 {
153 if (mpiHelper.size() > 1)
154 std::cout << "Rank " << mpiHelper.rank() << ": ";
155 std::cout << "No parameter file given. "
156 << "Defaulting to '"
157 << parameterFileName
158 << "' for input file.\n";
159 }
160 }
161
162 if (mpiHelper.size() > 1)
163 std::cout << "Rank " << mpiHelper.rank() << ": ";
164 std::cout << "Reading parameters from file " << parameterFileName << ".\n";
165
166 // read parameters from the file without overwriting the command line params
167 // because the command line arguments have precedence
168 // let Dune do the error checking if the file exists
169 Dune::ParameterTreeParser::readINITree(parameterFileName,
170 paramTree_(),
171 /*overwrite=*/false);
172 }
173
181 static void init(const DefaultParams& params = [] (Dune::ParameterTree&) {},
182 const DefaultParams& defaultParams = [] (Dune::ParameterTree&) {})
183 {
184 // apply the parameters
185 params(paramTree_());
186 // apply the default parameters
187 defaultParams(defaultParamTree_());
188 applyGlobalDefaults_(defaultParamTree_());
189 }
190
202 static void init(const std::string& parameterFileName,
203 const DefaultParams& params = [] (Dune::ParameterTree&) {},
204 bool inputFileOverwritesParams = true,
205 const DefaultParams& defaultParams = [] (Dune::ParameterTree&) {})
206 {
207 // apply the parameters
208 params(paramTree_());
209
210 // read parameters from the input file
211 Dune::ParameterTreeParser::readINITree(parameterFileName, paramTree_(), inputFileOverwritesParams);
212
213 // apply the default parameters
214 defaultParams(defaultParamTree_());
215 applyGlobalDefaults_(defaultParamTree_());
216 }
217
219 static void print()
220 {
221 getTree().reportAll();
222 }
223
225 static Dune::ParameterTree parseCommandLine(int argc, char **argv)
226 {
227 Dune::ParameterTree commandLineArgs;
228 for (int i = 1; i < argc; ++i)
229 {
230 if (argv[i][0] != '-' && i == 1)
231 {
232 // try to pass first argument as parameter file
233 commandLineArgs["ParameterFile"] = argv[1];
234 continue;
235 }
236
237 if (argv[i][0] != '-')
238 DUNE_THROW(ParameterException, "-> Command line argument " << i << " (='" << argv[i] << "') is invalid. <-");
239
240 if (i+1 == argc)
241 DUNE_THROW(ParameterException, "-> No argument given for parameter '" << argv[i] << "'! <-");
242
243 // check for the ParameterFile argument
244 if (argv[i]+1 == std::string("ParameterFile")) // +1 removes the '-'
245 {
246 commandLineArgs["ParameterFile"] = argv[i+1];
247 ++i;
248 }
249
250 // add all other options as key value pairs
251 else
252 {
253 // read a -MyOpt VALUE option
254 std::string paramName = argv[i]+1; // +1 removes the '-'
255 std::string paramValue = argv[i+1];
256 ++i; // In the case of '-MyOpt VALUE' each pair counts as two arguments
257
258 // Put the key=value pair into the parameter tree
259 commandLineArgs[paramName] = paramValue;
260 }
261 }
262 return commandLineArgs;
263 }
264
271 {
272 static LoggingParameterTree tree(paramTree_(), defaultParamTree_());
273 return tree;
274 }
275
276private:
278 static Dune::ParameterTree& paramTree_()
279 {
280 static Dune::ParameterTree tree;
281 return tree;
282 }
283
285 static Dune::ParameterTree& defaultParamTree_()
286 {
287 static Dune::ParameterTree tree;
288 return tree;
289 }
290
293 static void applyGlobalDefaults_(Dune::ParameterTree& params)
294 {
295 // global defaults
296 Dune::ParameterTree defaultParams;
297
298 // parameters in the implicit group
299 defaultParams["Flux.UpwindWeight"] = "1.0";
300 defaultParams["Implicit.EnableJacobianRecycling"] = "false";
301
302 // parameters in the assembly group
303 defaultParams["Assembly.NumericDifferenceMethod"] = "1";
304
305 // parameters in the problem group
306 defaultParams["Problem.EnableGravity"] = "true";
307 defaultParams["Problem.EnableInertiaTerms"] = "true";
308
309 // parameters in the time loop group
310 defaultParams["TimeLoop.MaxTimeStepSize"] = "1e300";
311 defaultParams["TimeLoop.MaxTimeStepDivisions"] = "10";
312
313 // parameters in the vtk group
314 defaultParams["Vtk.AddVelocity"] = "false";
315 defaultParams["Vtk.AddProcessRank"] = "true";
316
317 // parameters in the mpfa group
318 defaultParams["MPFA.Q"] = "0.0";
319
320 // merge the global default tree but do not overwrite if the parameter already exists
321 mergeTree_(params, defaultParams, false);
322 }
323
325 static void mergeTree_(Dune::ParameterTree& target, const Dune::ParameterTree& source, bool overwrite = true)
326 { mergeTreeImpl_(target, source, overwrite, ""); }
327
329 static void mergeTreeImpl_(Dune::ParameterTree& target, const Dune::ParameterTree& source, bool overwrite, const std::string& group)
330 {
331 const auto prefix = group.empty() ? "" : group + ".";
332 for (const auto& key : source.getValueKeys())
333 if (overwrite || !target.hasKey(key))
334 target[prefix + key] = source[key];
335
336 for (const auto& subKey : source.getSubKeys())
337 mergeTreeImpl_(target, source.sub(subKey), overwrite, prefix + subKey);
338 }
339};
340
347template<typename T, typename... Args>
348T getParam(Args&&... args)
349{ return Parameters::getTree().template get<T>(std::forward<Args>(args)... ); }
350
357template<typename T, typename... Args>
358T getParamFromGroup(Args&&... args)
359{ return Parameters::getTree().template getFromGroup<T>(std::forward<Args>(args)... ); }
360
366inline bool hasParam(const std::string& param)
367{ return Parameters::getTree().hasKey(param); }
368
374inline bool hasParamInGroup(const std::string& paramGroup, const std::string& param)
375{ return Parameters::getTree().hasKeyInGroup(param, paramGroup); }
376
382inline std::vector<std::string> getParamSubGroups(const std::string& subGroupName, const std::string& paramGroup)
383{ return Parameters::getTree().getSubGroups(subGroupName, paramGroup); }
384
385} // end namespace Dumux
386
387#endif
Function printing a default usage message.
Some exceptions thrown in DuMux
A parameter tree that logs which parameters have been used.
std::vector< std::string > getParamSubGroups(const std::string &subGroupName, const std::string &paramGroup)
Get a list of sub groups from the parameter tree sorted by relevance.
Definition: parameters.hh:382
T getParamFromGroup(Args &&... args)
A free function to get a parameter from the parameter tree singleton with a model group.
Definition: parameters.hh:358
bool hasParamInGroup(const std::string &paramGroup, const std::string &param)
Check whether a key exists in the parameter tree with a model group prefix.
Definition: parameters.hh:374
bool hasParam(const std::string &param)
Check whether a key exists in the parameter tree.
Definition: parameters.hh:366
std::string defaultUsageMessage(const std::string &programName)
Provides a general text block, that is part of error/ help messages.
Definition: defaultusagemessage.hh:37
T getParam(Args &&... args)
A free function to get a parameter from the parameter tree singleton.
Definition: parameters.hh:348
Definition: adapt.hh:29
Exception thrown if a run-time parameter is not specified correctly.
Definition: exceptions.hh:60
A parameter tree that logs which parameters have been used.
Definition: loggingparametertree.hh:41
void reportAll(std::ostream &stream=std::cout) const
print distinct substructure to stream
Definition: loggingparametertree.hh:164
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:127
bool hasKeyInGroup(const std::string &key, const std::string &groupPrefix) const
test for key in group
Definition: loggingparametertree.hh:84
bool hasKey(const std::string &key) const
test for key
Definition: loggingparametertree.hh:66
Parameter class managing runtime input parameters.
Definition: parameters.hh:49
static void init(int argc, char **argv, const DefaultParams &defaultParams=[](Dune::ParameterTree &) {}, std::string parameterFileName="", const Usage &usage=[](const char *, const std::string &){})
Initialize the parameter tree.
Definition: parameters.hh:94
static void init(const std::string &parameterFileName, const DefaultParams &params=[](Dune::ParameterTree &) {}, bool inputFileOverwritesParams=true, const DefaultParams &defaultParams=[](Dune::ParameterTree &) {})
Initialize the parameter tree.
Definition: parameters.hh:202
static void init(int argc, char **argv, const DefaultParams &defaultParams, const Usage &usage)
Initialize the parameter tree singletons.
Definition: parameters.hh:71
static void init(const DefaultParams &params=[](Dune::ParameterTree &) {}, const DefaultParams &defaultParams=[](Dune::ParameterTree &) {})
Initialize the parameter tree.
Definition: parameters.hh:181
static const LoggingParameterTree & getTree()
Get the parameter tree.
Definition: parameters.hh:270
static void init(int argc, char **argv, std::string parameterFileName, const Usage &usage=[](const char *, const std::string &){})
Initialize the parameter tree singletons.
Definition: parameters.hh:63
static void init(int argc, char **argv, const Usage &usage)
Initialize the parameter tree singletons.
Definition: parameters.hh:57
static void print()
prints all used and unused parameters
Definition: parameters.hh:219
static Dune::ParameterTree parseCommandLine(int argc, char **argv)
Parse command line arguments into a parameter tree.
Definition: parameters.hh:225