3.2-git
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 Newton group
310 // MinSteps = 2 makes Newton more robust if converge criterion is not perfect
311 defaultParams["Newton.MinSteps"] = "2";
312 defaultParams["Newton.MaxSteps"] = "18";
313 defaultParams["Newton.TargetSteps"] = "10";
314 defaultParams["Newton.UseLineSearch"] = "false";
315 defaultParams["Newton.EnableChop"] = "false";
316 defaultParams["Newton.EnableShiftCriterion"] = "true";
317 defaultParams["Newton.MaxRelativeShift"] = "1e-8";
318 defaultParams["Newton.EnableResidualCriterion"] = "false";
319 defaultParams["Newton.ResidualReduction"] = "1e-5";
320 defaultParams["Newton.EnableAbsoluteResidualCriterion"] = "false";
321 defaultParams["Newton.MaxAbsoluteResidual"] = "1e-5";
322 defaultParams["Newton.SatisfyResidualAndShiftCriterion"] = "false";
323 defaultParams["Newton.EnablePartialReassembly"] = "false";
324
325 // parameters in the time loop group
326 defaultParams["TimeLoop.MaxTimeStepSize"] = "1e300";
327 defaultParams["TimeLoop.MaxTimeStepDivisions"] = "10";
328
329 // parameters in the vtk group
330 defaultParams["Vtk.AddVelocity"] = "false";
331 defaultParams["Vtk.AddProcessRank"] = "true";
332
333 // parameters in the mpfa group
334 defaultParams["Mpfa.Q"] = "0.0"; // DEPRECATED, REMOVE AFTER 3.2
335 defaultParams["MPFA.Q"] = "0.0";
336
337 // merge the global default tree but do not overwrite if the parameter already exists
338 mergeTree_(params, defaultParams, false);
339 }
340
342 static void mergeTree_(Dune::ParameterTree& target, const Dune::ParameterTree& source, bool overwrite = true)
343 { mergeTreeImpl_(target, source, overwrite, ""); }
344
346 static void mergeTreeImpl_(Dune::ParameterTree& target, const Dune::ParameterTree& source, bool overwrite, const std::string& group)
347 {
348 const auto prefix = group.empty() ? "" : group + ".";
349 for (const auto& key : source.getValueKeys())
350 if (overwrite || !target.hasKey(key))
351 target[prefix + key] = source[key];
352
353 for (const auto& subKey : source.getSubKeys())
354 mergeTreeImpl_(target, source.sub(subKey), overwrite, prefix + subKey);
355 }
356};
357
364template<typename T, typename... Args>
365T getParam(Args&&... args)
366{ return Parameters::getTree().template get<T>(std::forward<Args>(args)... ); }
367
374template<typename T, typename... Args>
375T getParamFromGroup(Args&&... args)
376{ return Parameters::getTree().template getFromGroup<T>(std::forward<Args>(args)... ); }
377
383inline bool hasParam(const std::string& param)
384{ return Parameters::getTree().hasKey(param); }
385
391inline bool hasParamInGroup(const std::string& paramGroup, const std::string& param)
392{ return Parameters::getTree().hasKeyInGroup(param, paramGroup); }
393
399inline std::vector<std::string> getParamSubGroups(const std::string& subGroupName, const std::string& paramGroup)
400{ return Parameters::getTree().getSubGroups(subGroupName, paramGroup); }
401
402} // end namespace Dumux
403
404#endif
Some exceptions thrown in DuMux
Function printing a default usage message.
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:399
T getParamFromGroup(Args &&... args)
A free function to get a parameter from the parameter tree singleton with a model group.
Definition: parameters.hh:375
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:391
bool hasParam(const std::string &param)
Check whether a key exists in the parameter tree.
Definition: parameters.hh:383
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:365
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