deal.II version GIT relicensing-1936-ge55124254b 2024-10-04 21:10:00+00:00
|
#include <deal.II/base/parameter_handler.h>
Public Types | |
enum | OutputStyle { DefaultStyle = 0x0000 , Short = 0x0001 , KeepDeclarationOrder = 0x0002 , PRM = 0x0010 , LaTeX = 0x0020 , Description = 0x0040 , XML = 0x0080 , JSON = 0x0100 , ShortPRM = PRM | Short , ShortXML = XML | Short , ShortJSON = JSON | Short , ShortLaTeX = LaTeX | Short , KeepOnlyChanged = 0x0200 } |
Public Member Functions | |
ParameterHandler () | |
virtual | ~ParameterHandler () override=default |
ParameterHandler (const ParameterHandler &)=delete | |
ParameterHandler & | operator= (const ParameterHandler &)=delete |
virtual void | parse_input (std::istream &input, const std::string &filename="input file", const std::string &last_line="", const bool skip_undefined=false) |
virtual void | parse_input (const std::string &filename, const std::string &last_line="", const bool skip_undefined=false, const bool assert_mandatory_entries_are_found=false) |
virtual void | parse_input_from_string (const std::string &s, const std::string &last_line="", const bool skip_undefined=false) |
virtual void | parse_input_from_xml (std::istream &input, const bool skip_undefined=false) |
virtual void | parse_input_from_json (std::istream &input, const bool skip_undefined=false) |
void | clear () |
void | declare_entry (const std::string &entry, const std::string &default_value, const Patterns::PatternBase &pattern=Patterns::Anything(), const std::string &documentation="", const bool has_to_be_set=false) |
void | mark_as_deprecated (const std::string &entry, const bool is_deprecated=true) |
void | add_action (const std::string &entry, const std::function< void(const std::string &value)> &action, const bool execute_action=true) |
template<typename ParameterType > | |
void | add_parameter (const std::string &entry, ParameterType ¶meter, const std::string &documentation="", const Patterns::PatternBase &pattern= *Patterns::Tools::Convert< ParameterType >::to_pattern(), const bool has_to_be_set=false) |
void | declare_alias (const std::string &existing_entry_name, const std::string &alias_name, const bool alias_is_deprecated=false) |
void | enter_subsection (const std::string &subsection, const bool create_path_if_needed=true) |
void | leave_subsection () |
bool | subsection_path_exists (const std::vector< std::string > &sub_path) const |
std::string | get_current_path () const |
std::string | get_current_full_path (const std::string &name) const |
std::string | get_current_full_path (const std::vector< std::string > &sub_path, const std::string &name) const |
std::string | get (const std::string &entry_string) const |
std::string | get (const std::vector< std::string > &entry_subsection_path, const std::string &entry_string) const |
long int | get_integer (const std::string &entry_string) const |
long int | get_integer (const std::vector< std::string > &entry_subsection_path, const std::string &entry_string) const |
double | get_double (const std::string &entry_name) const |
double | get_double (const std::vector< std::string > &entry_subsection_path, const std::string &entry_string) const |
bool | get_bool (const std::string &entry_name) const |
bool | get_bool (const std::vector< std::string > &entry_subsection_path, const std::string &entry_string) const |
void | set (const std::string &entry_name, const std::string &new_value) |
void | set (const std::string &entry_name, const char *new_value) |
void | set (const std::string &entry_name, const long int new_value) |
void | set (const std::string &entry_name, const double new_value) |
void | set (const std::string &entry_name, const bool new_value) |
std::ostream & | print_parameters (std::ostream &out, const OutputStyle style) const |
void | print_parameters (const std::string &filename, const OutputStyle style=DefaultStyle) const |
void | log_parameters (LogStream &out, const OutputStyle style=DefaultStyle) |
void | log_parameters_section (LogStream &out, const OutputStyle style=DefaultStyle) |
std::size_t | memory_consumption () const |
template<class Archive > | |
void | save (Archive &ar, const unsigned int version) const |
template<class Archive > | |
void | load (Archive &ar, const unsigned int version) |
template<class Archive > | |
void | serialize (Archive &archive, const unsigned int version) |
bool | operator== (const ParameterHandler &prm2) const |
std::set< std::string > | get_entries_wrongly_not_set () const |
void | assert_that_entries_have_been_set () const |
Subscriptor functionality | |
Classes derived from Subscriptor provide a facility to subscribe to this object. This is mostly used by the ObserverPointer class. | |
void | subscribe (std::atomic< bool > *const validity, const std::string &identifier="") const |
void | unsubscribe (std::atomic< bool > *const validity, const std::string &identifier="") const |
unsigned int | n_subscriptions () const |
template<typename StreamType > | |
void | list_subscribers (StreamType &stream) const |
void | list_subscribers () const |
Static Public Member Functions | |
static ::ExceptionBase & | ExcEntryAlreadyExists (std::string arg1) |
static ::ExceptionBase & | ExcEntryIsDeprecated (int arg1, std::string arg2, std::string arg3) |
static ::ExceptionBase & | ExcEncounteredDeprecatedEntries (std::string arg1) |
static ::ExceptionBase & | ExcValueDoesNotMatchPattern (std::string arg1, std::string arg2) |
static ::ExceptionBase & | ExcAlreadyAtTopLevel () |
static ::ExceptionBase & | ExcEntryUndeclared (std::string arg1) |
static ::ExceptionBase & | ExcUnbalancedSubsections (std::string arg1, std::string arg2) |
static ::ExceptionBase & | ExcNoSubsection (int arg1, std::string arg2, std::string arg3) |
static ::ExceptionBase & | ExcCannotParseLine (int arg1, std::string arg2, std::string arg3) |
static ::ExceptionBase & | ExcInvalidEntryForPattern (int arg1, std::string arg2, std::string arg3, std::string arg4, std::string arg5) |
static ::ExceptionBase & | ExcInvalidXMLParameterFile () |
static ::ExceptionBase & | ExcCannotOpenIncludeStatementFile (int arg1, std::string arg2, std::string arg3) |
static ::ExceptionBase & | ExcInUse (int arg1, std::string arg2, std::string arg3) |
static ::ExceptionBase & | ExcNoSubscriber (std::string arg1, std::string arg2) |
Private Types | |
using | map_value_type = decltype(counter_map)::value_type |
using | map_iterator = decltype(counter_map)::iterator |
Private Member Functions | |
void | scan_line (std::string line, const std::string &input_filename, const unsigned int current_line_n, const bool skip_undefined) |
void | recursively_print_parameters (const boost::property_tree::ptree &tree, const std::vector< std::string > &target_subsection_path, const ParameterHandler::OutputStyle style, const unsigned int indent_level, std::ostream &out) const |
void | check_no_subscribers () const noexcept |
Private Attributes | |
std::vector< std::string > | subsection_path |
std::unique_ptr< boost::property_tree::ptree > | entries |
std::map< std::string, std::pair< bool, bool > > | entries_set_status |
std::vector< std::unique_ptr< const Patterns::PatternBase > > | patterns |
std::vector< std::function< void(const std::string &)> > | actions |
std::atomic< unsigned int > | counter |
std::map< std::string, unsigned int > | counter_map |
std::vector< std::atomic< bool > * > | validity_pointers |
const std::type_info * | object_info |
Static Private Attributes | |
static const char | path_separator = '.' |
static std::mutex | mutex |
Friends | |
class | MultipleParameterLoop |
The ParameterHandler class provides a standard interface to an input file which provides at run-time for program parameters such as time step sizes, geometries, right hand sides etc. The input for the program is given in files, streams or strings in memory using text like
Input may be sorted into subsection trees in order to give the input a logical structure, and input files may include other files.
The ParameterHandler class is discussed in step-29, step-33, and step-34.
In order to use the facilities of a ParameterHandler object, one first has to make known the different entries the input file may or may not contain. This is done in the following way:
Each entry is declared using the function declare_entry(). The first parameter is the name of the entry (in short: the entry). The second is the default answer to be taken in case the entry is not specified in the input file. The third parameter is a regular expression which the input (and the default answer) has to match. Several such regular expressions are defined in Patterns. This parameter can be omitted, in which case it will default to Patterns::Anything, i.e. a pattern that matches every input string. The fourth parameter can be used to document the intent or expected format of an entry; its value is printed as a comment when writing all entries of a ParameterHandler object using the print_parameters() function to allow for easier understanding of a parameter file. It can be omitted as well, in which case no such documentation will be printed.
Entries may be located in subsections which form a kind of input tree. For example input parameters for linear solver routines should be classified in a subsection named Linear solver
or any other suitable name. This is accomplished in the following way:
Subsections may be nested. For example a nonlinear solver may have a linear solver as member object. Then the function call tree would be something like (if the class NonLinEq
has a member variables eq
of type LinEq
):
For class member functions which declare the different entries we propose to use the common name declare_parameters
. In normal cases this method can be static
since the entries will not depend on any previous knowledge. Classes for which entries should logically be grouped into subsections should declare these subsections themselves. If a class has two or more member variables of the same type both of which should have their own parameters, this parent class' method declare_parameters
is responsible to group them into different subsections:
For the first example above the input file would look like the following:
The words subsection
, set
and end
may be either written in lowercase or uppercase letters. Leading and trailing whitespace is removed, multiple whitespace is condensed into only one. Since the latter applies also to the name of an entry, an entry name will not be recognized if in the declaration multiple whitespace is used.
In entry names and values the following characters are not allowed: #
, {
, }
, |
. Their use is reserved for the MultipleParameterLoop class.
Comments starting with # are skipped.
Continuation lines are allowed by means of the character \
, which must be the last character (aside from whitespace, which is ignored) of the line. When a line is a continuation (i.e., the previous line ended in a \
), then, unlike the default behavior of the C
preprocessor, all whitespace at the beginning of the line is ignored.
We propose to use the following scheme to name entries: start the first word with a capital letter and use lowercase letters further on. The same applies to the possible entry values to the right of the =
sign.
The class can also handle json-files and XML-files. The json input file might look like the following for the previous example:
The advantage of using json-files is that this format is natively supported by Python, simplifying the running of parameter studies tremendously.
An input file can include other include files using the syntax
The file so referenced is searched for relative to the current directory (not relative to the directory in which the including parameter file is located, since this is not known to all three versions of the parse_input() function).
In order to read input there are three possibilities: reading from an std::istream
object, reading from a file of which the name is given and reading from a string in memory in which the lines are separated by \n
characters. These possibilities are used as follows:
You can use several sources of input successively. Entries which are changed more than once will be overwritten every time they are used.
You should not try to declare entries using declare_entry() and enter_subsection() with as yet unknown subsection names after using parse_input(). The results in this case are unspecified.
If an error occurs upon reading the input, error messages are written to std::cerr
and the reader function returns with a return value of false
. This is opposed to almost all other functions in deal.II, which would normally throw an exception if an error occurs; this difference in behavior is a relic of the fact that this class predates deal.II and had previously been written for a different project.
An alternative to using the hand-written input files shown above is to use the graphical user interface (GUI) that accompanies this class.
See the parameter_gui github repository for further details.
Each class gets its data out of a ParameterHandler object by calling the get() member functions like this:
get() returns the value of the given entry. If the entry was not specified in the input source(s), the default value is returned. You have to enter and leave subsections exactly as you did when declaring subsections. You may choose the order in which to traverse the subsection tree.
It is possible to avoid calls to enter_subsection() and leave_subsection() by supplying get() with a vector of strings representing the path from which to get a value. For example, the following two versions of get_parameters() will produce the same result:
The latter method allows the ParameterHandler reference to be const
.
It is guaranteed that only entries matching the given regular expression are returned, i.e. an input entry value which does not match the regular expression is not stored.
You can use get() to retrieve the parameter in text form, get_integer() to get an integer or get_double() to get a double. You can also use get_bool(). It will cause an internal error if the string could not be converted to an integer, double or a bool. This should, though, not happen if you correctly specified the regular expression for this entry; you should not try to get out an integer or a double from an entry for which no according regular expression was set. The internal error is raised through the Assert() macro family which only works in debug mode.
If you want to print out all user selectable features, use the print_parameters() function. It is generally a good idea to print all parameters at the beginning of a log file, since this way input and output are together in one file which makes matching at a later time easier. Additionally, the function also print those entries which have not been modified in the input file and are thus set to default values; since default values may change in the process of program development, you cannot know the values of parameters not specified in the input file.
It is often convenient to have something happen as soon as a parameter value is read. This could be a check that it is valid – say, that a file that is listed in the parameter file exists – or to initiate something else in response, such as setting a variable outside the ParameterHandler (as in the example shown below). In almost all cases, this "action" could also be initiated once all parameters are read via parse_input(), but it is sometimes convenient to do it right away.
This is facilitated by the add_action() function that can be called after declaring a parameter via declare_entry(). "Actions" are in essence pointers to functions that will be called for parameters that have associated actions. These functions take the value of a parameter as argument, and can then do whatever they want with it – e.g., save it somewhere outside the ParameterHandler object. (Exactly when the action is called is described in the documentation of the add_action() function.) Of course, in C++ one doesn't usually pass around the address of a function, but an action can be a function-like object (taking a string as argument) that results from calling such as a lambda function that has the form
and that is attached to a specific parameter.
A typical example of such an action would be as follows: let's assume that you have a program that declares a parameter for the number of iterations it is going to run, say
then one could obtain this parameter from a parameter file using a code snippet in run()
as follows:
This two-step process – first declaring the parameter, and later reading it – is a bit cumbersome because one has to first declare all parameters and at a later time retrieve them from the ParameterHandler object. In large programs, these two things also often happen in different functions.
To avoid this, it would be nice if we could put both the declaration and the retrieval into the same place. This can be done via actions, and the function would then look like this:
Here, the action consists of a lambda function that takes the value for this parameter as a string, and then converts it to an integer to store in the variable where it belongs. This action is executed inside the call to prm.parse_input()
, and so there is now no longer a need to extract the parameter's value at a later time. Furthermore, the code that sets the member variable is located right next to the place where the parameter is actually declared, so we no longer need to have two separate parts of the code base that deal with input parameters.
Of course, it is possible to execute far more involved actions than just setting a member variable as shown above, even though that is a typical case.
We propose that every class which gets data out of a ParameterHandler object provides a function named get_parameters
. This should be declared virtual
. get_parameters
functions in derived classes should call the BaseClass::get_parameters
function.
Experience has shown that in programs defining larger numbers of parameters (more than, say, fifty) it is advantageous to define an additional class holding these parameters. This class is more like a C-style structure, having a large number of variables, usually public. It then has at least two functions, which declare and parse the parameters. In the main program, the main class has an object of this parameter class and delegates declaration and parsing of parameters to this object.
The advantage of this approach is that you can keep out the technical details (declaration and parsing) out of the main class and additionally don't clutter up your main class with dozens or more variables denoting the parameters.
This is the code:
This is the input file (named "prmtest.prm"):
And here is the output of the program:
Here is some more internal information about the representation of parameters:
Logically, parameters and the nested sections they are arranged in can be thought of as a hierarchical directory structure, or a tree. Take, for example, the following code declaring a set of parameters and sections they live in:
We can think of the parameters so arranged as a file system in which every parameter is a directory. The name of this directory is the name of the parameter, and in this directory lie files that describe the parameter. These files are at the time of writing this documentation (other fields, such as those indicating "actions" may also exist in each directory):
value
: The content of this file is the current value of this parameter; initially, the content of the file equals the default value of the parameter.default_value
: The content of this file is the default value of the parameter.pattern
: A textual representation of the pattern that describes the parameter's possible values.pattern_index
: A number that indexes the Patterns::PatternBase object that is used to describe the parameter.documentation
: The content of this file is the documentation given for a parameter as the last argument of the ParameterHandler::declare_entry call. With the exception of the value
file, the contents of files are never changed after declaration of a parameter.Alternatively, a directory in this file system may not have a file called value
in it. In that case, the directory represents a subsection as declared above, and the directory's name will correspond to the name of the subsection. It will then have no files in it at all, but it may have further directories in it: some of these directories will be parameters (indicates by the presence of files) or further nested subsections.
Given this explanation, the code above will lead to a hierarchical representation of data that looks like this (the content of files is indicated at the right in a different font):
Once parameters have been read in, the contents of the value
"files" may be different while the other files remain untouched.
Using the ParameterHandler::print_parameters() function with ParameterHandler::XML as second argument, we can get a complete representation of this data structure in XML. It will look like this:
This representation closely resembles the directory/file structure discussed above. The only difference is that directory and file names are mangled: since they should only contain letters and numbers, every character in their names that is not a letter or number is replaced by an underscore followed by its two-digit hexadecimal representation. In addition, the special name "value" is mangled when used as the name of a parameter, given that this name is also used to name special files in the hierarchy structure. Finally, the entire tree is wrapped into a tag ParameterHandler
to satisfy the XML requirement that there be only a single top-level construct in each file.
The tree structure (and its XML representation) is what the graphical user interface (see above) uses to represent parameters like a directory/file collection.
Definition at line 854 of file parameter_handler.h.
|
privateinherited |
The data type used in counter_map.
Definition at line 230 of file subscriptor.h.
|
privateinherited |
The iterator type used in counter_map.
Definition at line 235 of file subscriptor.h.
List of possible output formats used for functions like ParameterHandler::print_parameters(). The options can be categorized into two groups:
Only one format option may be specified at the time. Any function that accepts an OutputStyle as an option will throw if you specify more than one.
A number of shortcuts of commonly used option combinations are provided. E.g., ShortPRM prints the parameters in the PRM format, while skipping the documentation.
Enumerator | |
---|---|
DefaultStyle | Default stylistic style: print documentation and sort all parameters alphabetically. |
Short | Write input for ParameterHandler without comments or changed default values. |
KeepDeclarationOrder | Keep the order of the parameters as they have been declared. |
PRM | Write human readable output suitable to be read by ParameterHandler::parse_input() again. |
LaTeX | Write parameters as a LaTeX table. |
Description | Write out declared parameters with description and possible values.
|
XML | Write out everything as an XML file suitable to be read by ParameterHandler::parse_input_from_xml() again. See the general documentation of this class for an example of output. |
JSON | Write out everything as a JSON file suitable to be read by ParameterHandler::parse_input_from_json() again. |
ShortPRM | Write the content of ParameterHandler without comments or changed default values. |
ShortXML | Write the content of ParameterHandler without comments or changed default values as a XML file. |
ShortJSON | Write the content of ParameterHandler without comments or changed default values as a JSON file. |
ShortLaTeX | Write the content of ParameterHandler without comments or changed default values as a LaTeX file. |
KeepOnlyChanged | Write out only parameters with changed values. |
Definition at line 872 of file parameter_handler.h.
ParameterHandler::ParameterHandler | ( | ) |
Constructor.
Definition at line 44 of file parameter_handler.cc.
|
overridevirtualdefault |
Destructor. Declare this only to have a virtual destructor, which is safer as we have virtual functions. It actually does nothing spectacular.
|
delete |
Inhibit automatic CopyConstructor.
|
delete |
Inhibit automatic assignment operator.
|
virtual |
Parse each line from a stream until the stream returns the eof
condition or error to provide values for known parameter fields. The second argument can be used to denote the name of the file (if that's what the input stream represents) we are reading from; this is only used when creating output for exceptions.
If non-empty last_line
is provided, the ParameterHandler object will stop parsing lines after encountering last_line
. This is handy when adding extra data that shall be parsed manually.
If skip_undefined
is true
, the parameter handler will skip undefined sections and entries. This is useful for partially parsing a parameter file, for example to obtain only the spatial dimension of the problem. By default all entries and subsections are expected to be declared.
The function sets the value of all parameters it encounters in the input file to the provided value. Parameters not explicitly listed in the input file are left at the value they previously held, which will be the default value provided to declare_entry() unless one has previously read a different input file.
Each parameter value is matched against the pattern for this parameter that was provided to declare_entry(), and for each parameter all associated actions that may previously have been set by add_action() are executed. If a parameter does not satisfy its pattern, or if an associated action throws an exception, then the value provided for the parameter is not set and the current object reverts to the subsection it was in before the current function was called. No further processing of the input stream occurs, that is everything that comes after the parameter whose value does not satisfy its pattern is ignored.
Reimplemented in MultipleParameterLoop, and MultipleParameterLoop.
Definition at line 433 of file parameter_handler.cc.
|
virtual |
Parse input from a specified parameter file filename
independently of the type of input file (prm, xml, json) being used. The code path selected by this function is extracted from the ending of the filename, so the user has to make sure that the content of the input file is consistent with its name.
The parameter last_line
will only be used for parameter files of .prm type. See the other parse_input function for documentation.
The user can specify whether parameters in the input file not added to the parameter handler will be skipped by skip_undefined
(enables partial parsing), and whether the code will assert that all parameters of the parameter handler declared with flag has_to_be_set=true
are indeed found in the input file.
If the function is called with skip_undefined=true
, it is recommended to also set assert_mandatory_entries_are_found=true
. For example, this ensures that parameters with typos in the input file will not be skipped, while such mistakes would otherwise remain unrecognized.
Reimplemented in MultipleParameterLoop.
Definition at line 581 of file parameter_handler.cc.
|
virtual |
Parse input from a string to populate known parameter fields. The lines in the string must be separated by \n
characters.
The function in essence reads the entire file into a stream and then calls the other parse_input() function with that stream. See there for more information.
Definition at line 611 of file parameter_handler.cc.
|
virtual |
Parse input from an XML stream to populate known parameter fields. This could be from a file originally written by the print_parameters() function using the XML output style and then modified by hand as necessary, or from a file written using this method and then modified by the graphical parameter GUI (see the general documentation of this class).
Definition at line 792 of file parameter_handler.cc.
|
virtual |
Parse input from a JSON stream to populate known parameter fields. This could be from a file originally written by the print_parameters() function using the JSON output style and then modified by hand as necessary, or from a separate program that knows how to write JSON format for ParameterHandler input.
Definition at line 848 of file parameter_handler.cc.
void ParameterHandler::clear | ( | ) |
Clear all contents.
Definition at line 884 of file parameter_handler.cc.
void ParameterHandler::declare_entry | ( | const std::string & | entry, |
const std::string & | default_value, | ||
const Patterns::PatternBase & | pattern = Patterns::Anything() , |
||
const std::string & | documentation = "" , |
||
const bool | has_to_be_set = false |
||
) |
Declare a new entry with name entry
, default and for which any input has to match the pattern
(default: any pattern).
The function generates an exception of type ExcValueDoesNotMatchPattern if the default value doesn't match the given pattern, using the C++ throw mechanism. However, this exception is only generated after the entry has been created; if you have code where no sensible default value for a parameter is possible, you can then catch and ignore this exception.
The parameter documentation
defaulting to an empty string is used to add a documenting text to each entry which will be printed as a comment when this class is asked to write out all declarations to a stream using the print_parameters() function.
The parameter has_to_be_set
can be used in order to declare this parameter as a parameter whose default value has to be overwritten by one of the methods provided by this class. Whether a parameter has been set successfully can be queried by the functions get_entries_wrongly_not_set() and assert_that_entries_have_been_set().
Definition at line 893 of file parameter_handler.cc.
void ParameterHandler::mark_as_deprecated | ( | const std::string & | entry, |
const bool | is_deprecated = true |
||
) |
Mark a previously declared parameter as deprecated. This will cause an exception of type ExcEncounteredDeprecatedEntries to be thrown if the parameter is used in an input file that is parsed by the parse_input() function.
The exception message will list the name of the parameter(s) that were encountered in the input file.
entry | The name of the parameter to be marked as deprecated. |
is_deprecated | An optional parameter that can be used to set the deprecation status of the parameter. If set to true, the parameter will be marked as deprecated. This is the default behavior. If set to false, the parameter will be marked as not deprecated. This is useful if a parameter is marked as deprecated by one function, but another function wants to keep using it. |
Definition at line 1040 of file parameter_handler.cc.
void ParameterHandler::add_action | ( | const std::string & | entry, |
const std::function< void(const std::string &value)> & | action, | ||
const bool | execute_action = true |
||
) |
Attach an action to the parameter with name entry
in the current section. The action needs to be a function-like object that takes the value of the parameter as a (string) argument. See the general documentation of this class for a longer description of actions, as well as examples.
The action is executed in three different circumstances:
name
, at the end of the current function if execute_action
is set to true. This is useful because it allows for the action to execute whatever it needs to do at least once for each parameter, even those that are not actually specified in the input file (and thus remain at their default values). Note that if the action is executed, it converts the default value to a string and back afterwards. This can lead to round-off errors so that the default values might change in the case of floating-point numbers.It is valid to add multiple actions to the same parameter. They will in that case be executed in the same order in which they were added.
Definition at line 939 of file parameter_handler.cc.
void ParameterHandler::add_parameter | ( | const std::string & | entry, |
ParameterType & | parameter, | ||
const std::string & | documentation = "" , |
||
const Patterns::PatternBase & | pattern = *Patterns::Tools::Convert<ParameterType>::to_pattern() , |
||
const bool | has_to_be_set = false |
||
) |
Declare a new entry name entry
, set its default value to the content of the variable parameter
, and create an action that will fill parameter
with updated values when a file is parsed, or the entry is set to a new value.
By default, the pattern to use is obtained by calling the function Patterns::Tools::Convert<T>::to_pattern(), but a custom one can be used.
The parameter has_to_be_set
can be used in order to declare this parameter as a parameter whose default value has to be overwritten by one of the methods provided by this class. Whether a parameter has been set successfully can be queried by the functions get_entries_wrongly_not_set() and assert_that_entries_have_been_set().
Definition at line 2368 of file parameter_handler.h.
void ParameterHandler::declare_alias | ( | const std::string & | existing_entry_name, |
const std::string & | alias_name, | ||
const bool | alias_is_deprecated = false |
||
) |
Create an alias for an existing entry. This provides a way to refer to a parameter in the input file using an alternate name. The alias will be in the current section, and the referenced entry needs to be an existing entry in the current section.
The primary purpose of this function is to allow for a backward compatible way of changing names in input files of applications for which backward compatibility is important. This can be achieved by changing the name of the parameter in the call to declare_entry(), and then creating an alias that maps the old name to the new name. This way, old input files can continue to refer to parameters under the old name, and they will automatically be mapped to the new parameter name.
It is valid to set the same parameter multiple times in an input file. The value that will ultimately be chosen in such cases is simply the last value set. This rule also applies to aliases, where the final value of a parameter is the last value set either through the current name of the parameter or through any of its possible multiple aliases. For example, if you have an input file that looks like
where parm1_alias
is an alias declared via
then the final value for the parameter called parm1
will be 2, not 1.
existing_entry_name | The name of an existing parameter in the current section that the alias should refer to. |
alias_name | An alternate name for the parameter referenced by the first argument. |
alias_is_deprecated | If true, mark the alias as deprecated. This will then be listed in the description of the alias if you call print_parameters(), and you will get a warning on the screen when reading an input file that contains this deprecated alias. The purpose of this argument is to be able to allow the use of an old name for a parameter (see above) but make it clear that this old name will eventually be removed. |
Definition at line 977 of file parameter_handler.cc.
void ParameterHandler::enter_subsection | ( | const std::string & | subsection, |
const bool | create_path_if_needed = true |
||
) |
Enter a subsection. If it does not yet exist, create it if requested.
Definition at line 1068 of file parameter_handler.cc.
void ParameterHandler::leave_subsection | ( | ) |
Leave present subsection.
Definition at line 1092 of file parameter_handler.cc.
bool ParameterHandler::subsection_path_exists | ( | const std::vector< std::string > & | sub_path | ) | const |
Check whether a subsection or a subsection path exists in current tree. The input parameter sub_path
is assumed to be relative to the currently selected path.
Definition at line 1105 of file parameter_handler.cc.
std::string ParameterHandler::get_current_path | ( | ) | const |
Return the string that identifies the current path into the property tree. The path elements are separated by the path_separator, which is a '.'. This is only a path, i.e., it is not terminated by the path_separator character.
This function simply calls collate_path_string() with subsection_path
as argument.
Definition at line 392 of file parameter_handler.cc.
std::string ParameterHandler::get_current_full_path | ( | const std::string & | name | ) | const |
Given the name of an entry as argument, the function computes a full path into the parameter tree using the current subsection. The path elements are separated by the path_separator, which is a '.'.
Definition at line 400 of file parameter_handler.cc.
std::string ParameterHandler::get_current_full_path | ( | const std::vector< std::string > & | sub_path, |
const std::string & | name | ||
) | const |
This function computes a full path into the parameter tree given a path from the current subsection and the name of an entry. The path elements are separated by the path_separator, which is a '.'.
Definition at line 414 of file parameter_handler.cc.
std::string ParameterHandler::get | ( | const std::string & | entry_string | ) | const |
Return value of entry entry_string
. If the entry was changed, then the changed value is returned, otherwise the default value. If the value of an undeclared entry is required, an Assert
will fail.
Definition at line 1126 of file parameter_handler.cc.
std::string ParameterHandler::get | ( | const std::vector< std::string > & | entry_subsection_path, |
const std::string & | entry_string | ||
) | const |
Return value of entry entry_string
. If the entry was changed, then the changed value is returned, otherwise the default value. If the value of an undeclared entry is required, an Assert
will fail. If entry_subsection_path
is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection. The first string in entry_subsection_path
must be the name of a subsection of the current section, and each next string must be the name of a subsection of the one before it.
Definition at line 1143 of file parameter_handler.cc.
long int ParameterHandler::get_integer | ( | const std::string & | entry_string | ) | const |
Return value of entry entry_string
as long int
. (A long int is chosen so that even very large unsigned values can be returned by this function).
Definition at line 1164 of file parameter_handler.cc.
long int ParameterHandler::get_integer | ( | const std::vector< std::string > & | entry_subsection_path, |
const std::string & | entry_string | ||
) | const |
Return value of entry entry_string
as long int
. (A long int is chosen so that even very large unsigned values can be returned by this function). If entry_subsection_path
is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 1183 of file parameter_handler.cc.
double ParameterHandler::get_double | ( | const std::string & | entry_name | ) | const |
Return value of entry entry_name
as double
.
Definition at line 1207 of file parameter_handler.cc.
double ParameterHandler::get_double | ( | const std::vector< std::string > & | entry_subsection_path, |
const std::string & | entry_string | ||
) | const |
Return value of entry entry_name
as double
. If entry_subsection_path
is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 1227 of file parameter_handler.cc.
bool ParameterHandler::get_bool | ( | const std::string & | entry_name | ) | const |
Return value of entry entry_name
as bool
. The entry may be "true" or "yes" for true
, "false" or "no" for false
respectively.
Definition at line 1252 of file parameter_handler.cc.
bool ParameterHandler::get_bool | ( | const std::vector< std::string > & | entry_subsection_path, |
const std::string & | entry_string | ||
) | const |
Return value of entry entry_name
as bool
. The entry may be "true" or "yes" for true
, "false" or "no" for false
respectively. If entry_subsection_path
is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 1269 of file parameter_handler.cc.
void ParameterHandler::set | ( | const std::string & | entry_name, |
const std::string & | new_value | ||
) |
Change the value presently stored for entry_name
to the one given in the second argument.
The parameter must already exist in the present subsection.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 1291 of file parameter_handler.cc.
void ParameterHandler::set | ( | const std::string & | entry_name, |
const char * | new_value | ||
) |
Same as above, but an overload where the second argument is a character pointer. This is necessary, since otherwise the call to set("abc","def")
will be mapped to the function taking one string and a bool as arguments, which is certainly not what is most often intended.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 1344 of file parameter_handler.cc.
void ParameterHandler::set | ( | const std::string & | entry_name, |
const long int | new_value | ||
) |
Change the value presently stored for entry_name
to the one given in the second argument.
The parameter must already exist in the present subsection.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 1366 of file parameter_handler.cc.
void ParameterHandler::set | ( | const std::string & | entry_name, |
const double | new_value | ||
) |
Change the value presently stored for entry_name
to the one given in the second argument.
The parameter must already exist in the present subsection.
For internal purposes, the new value needs to be converted to a string. This is done using 16 digits of accuracy, so the set value and the one you can get back out using get_double() may differ in the 16th digit.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 1352 of file parameter_handler.cc.
void ParameterHandler::set | ( | const std::string & | entry_name, |
const bool | new_value | ||
) |
Change the value presently stored for entry_name
to the one given in the second argument.
The parameter must already exist in the present subsection.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 1379 of file parameter_handler.cc.
std::ostream & ParameterHandler::print_parameters | ( | std::ostream & | out, |
const OutputStyle | style | ||
) | const |
Print all parameters with the given style
to out
.
Before printing, all current parameters and subsections are sorted alphabetically by default. This behavior can be disabled setting the optional parameter style
to KeepDeclarationOrder
: in this case entries are printed in the same order as they have been declared.
In PRM
, XML
, and JSON
format, the output is formatted in such a way that it is possible to use it for later input again. This is most useful to record the parameters for a specific run, since if you output the parameters using this function into a log file, you can always recover the results by simply copying the output to your input file.
Besides the name and value of each entry, the output also contains the default value of entries if it is different from the actual value, as well as the documenting string given to the declare_entry() function if available.
By using the flag Short
in combination with PRM
, XML
, JSON
, or LaTeX
(or by using the shortcuts ShortPRM
, ShortXML
, ShortJSON
, or ShortLaTeX
), a reduced output can be generated, only containing the values and skipping the documentation.
In XML
format, the output starts with one root element ParameterHandler
in order to get a valid XML document and all subsections under it.
In LaTeX
format, the output contains the same information but in a format so that the resulting file can be input into a latex document such as a manual for the code for which this object handles run-time parameters. The various sections of parameters are then represented by latex section and subsection commands as well as by nested enumerations.
You can reference specific parameter sections and individual parameters by the labels that are generated automatically for each entry. The labels have the format parameters:section1/subsection1
and parameters:section1/subsection1/someentry
. Because special characters can appear in the section and entry names, these will be "mangled". Here, all characters except [a-zA-Z0-9]
are replaced by _XX
, where XX
is the two-digit ascii code of the character in hexadecimal encoding (so a space becomes _20
for example).
While this function escapes special LaTeX-specific characters (backslash, underscore, etc.) in most of the output (names, default values, etc.), the documentation string is passed as-is. This means you can use math environments and other formatting in the description, but you need to escape quotes, backslashes, underscores, etc. yourself.
In addition, all parameter names are listed with \index
statements in two indices called prmindex
(where the name of each parameter is listed in the index) and prmindexfull
where parameter names are listed sorted by the section in which they exist. By default, the LaTeX program ignores these \index
commands, but they can be used to generate an index by using the following commands in the preamble of the latex file :
and at the end of the file this:
Definition at line 1389 of file parameter_handler.cc.
void ParameterHandler::print_parameters | ( | const std::string & | filename, |
const OutputStyle | style = DefaultStyle |
||
) | const |
Print all parameters to the file given by filename
with the given output style style
.
This function deduces the output format from the extension of the specified filename. Supported extensions are prm
, xml
, tex
, and json
. Hence, it is not necessary to specify an output format via the style
argument as long as one of these extensions is added to the filename. If an output format is specified in the style
parameter nevertheless, the output format has to be consistent with the filename extension.
If no extension is specified or the extension is not supported, the output format is deduced from the style
argument.
If neither the extension is supported, nor does the style
parameter contain a format specification, an assertion is thrown.
filename | The output file name. |
style | The style with which output is produced. |
Definition at line 1505 of file parameter_handler.cc.
void ParameterHandler::log_parameters | ( | LogStream & | out, |
const OutputStyle | style = DefaultStyle |
||
) |
Print parameters to a logstream. This function allows to print all parameters into a log-file. Sections will be indented in the usual log-file style.
All current parameters and subsections are sorted alphabetically by default. This behavior can be disabled setting the optional parameter style
to KeepDeclarationOrder
: in this case entries are printed in the same order as they have been declared.
style
not related to the ordering are ignored. Definition at line 1919 of file parameter_handler.cc.
void ParameterHandler::log_parameters_section | ( | LogStream & | out, |
const OutputStyle | style = DefaultStyle |
||
) |
Log parameters in the present subsection. The subsection is determined by the subsection_path
member variable. This variable is controlled by entering and leaving subsections through the enter_subsection() and leave_subsection() functions.
All current parameters and subsections are sorted alphabetically by default. This behavior can be disabled setting the optional parameter style
to KeepDeclarationOrder
: in this case entries are printed in the same order as they have been declared.
style
not related to the ordering are ignored.In most cases, you will not want to use this function directly, but have it called recursively by the previous function.
Definition at line 1930 of file parameter_handler.cc.
std::size_t ParameterHandler::memory_consumption | ( | ) | const |
Determine an estimate for the memory consumption (in bytes) of this object.
Definition at line 2194 of file parameter_handler.cc.
|
inline |
Write the data of this object to a stream for the purpose of serialization using the BOOST serialization library.
Definition at line 2329 of file parameter_handler.h.
|
inline |
Read the data of this object from a stream for the purpose of serialization using the BOOST serialization library.
Definition at line 2349 of file parameter_handler.h.
void ParameterHandler::serialize | ( | Archive & | archive, |
const unsigned int | version | ||
) |
Write and read the data of this object from a stream for the purpose of serialization using the BOOST serialization library.
bool ParameterHandler::operator== | ( | const ParameterHandler & | prm2 | ) | const |
Test for equality.
Definition at line 2203 of file parameter_handler.cc.
std::set< std::string > ParameterHandler::get_entries_wrongly_not_set | ( | ) | const |
Return a set of parameter names (including subsection names) corresponding to those entries of the parameter handler that have not been set by one of the functions parsing parameters from an input file or by an explicit call to one of the set() functions, but that have been declared as mandatory parameters that must be set (through the last argument of the declare_entry() function or add_parameter() function).
Definition at line 2228 of file parameter_handler.cc.
void ParameterHandler::assert_that_entries_have_been_set | ( | ) | const |
Asserts that those entries of the parameter handler with flag has_to_be_set = true
have been set. An exception is invoked if at least one of these parameters has not been set.
Definition at line 2242 of file parameter_handler.cc.
|
private |
Scan one line of input. input_filename
and current_line_n
are the name of the input file and the number of the line presently scanned (these are used in exception messages to show where parse errors occurred). This function will raise an exception if the line contains an undeclared subsection or entry, if the line's entry does not match its given pattern, or if the line could not be understood as a valid parameter file expression.
The function modifies its argument, but also takes it by value, so the caller's variable is not changed.
If skip_undefined
is true
, the parser will skip undefined sections and entries. This is useful for partially parsing a parameter file, for example to obtain only the spatial dimension of the problem. By default all entries and subsections are expected to be declared.
Definition at line 1976 of file parameter_handler.cc.
|
private |
Print out the parameters of the subsection given by the target_subsection_path
argument, as well as all subsections within it recursively. This function is called from the print_parameters() function, and is implemented for all style
arguments other than XML and JSON (where we can output the entire set of parameters via BOOST functions). The indent_level
argument indicates how many spaces the output should be indented, so that subsections properly nest inside the output of higher sections.
Definition at line 1530 of file parameter_handler.cc.
|
inherited |
Subscribes a user of the object by storing the pointer validity
. The subscriber may be identified by text supplied as identifier
.
Definition at line 130 of file subscriptor.cc.
|
inherited |
Unsubscribes a user from the object.
identifier
and the validity
pointer must be the same as the one supplied to subscribe(). Definition at line 150 of file subscriptor.cc.
|
inlineinherited |
Return the present number of subscriptions to this object. This allows to use this class for reference counted lifetime determination where the last one to unsubscribe also deletes the object.
Definition at line 301 of file subscriptor.h.
|
inlineinherited |
List the subscribers to the input stream
.
Definition at line 318 of file subscriptor.h.
|
inherited |
List the subscribers to deallog
.
Definition at line 198 of file subscriptor.cc.
|
privatenoexceptinherited |
Check that there are no objects subscribing to this object. If this check passes then it is safe to destroy the current object. It this check fails then this function will either abort or print an error message to deallog (by using the AssertNothrow mechanism), but will not throw an exception.
Definition at line 52 of file subscriptor.cc.
|
friend |
Definition at line 1889 of file parameter_handler.h.
|
staticprivate |
The separator used when accessing elements of a path into the parameter tree.
Definition at line 1804 of file parameter_handler.h.
|
private |
Path of presently selected subsections; empty list means top level
Definition at line 1809 of file parameter_handler.h.
|
private |
The complete tree of sections and entries. See the general documentation of this class for a description how data is stored in this variable.
The variable is a pointer so that we can use an incomplete type, rather than having to include all of the property_tree stuff from boost. This works around a problem with gcc 4.5.
Definition at line 1819 of file parameter_handler.h.
A map that stores a pair of boolean variables for each entry added to the parameter handler. The first bool describes whether the parameter has to be set according to the last argument of the functions declare_entry() or add_parameter(), and the second bool contains the information whether the parameter has been set by any of the functions parsing input parameters or by a set function of this class.
Definition at line 1829 of file parameter_handler.h.
|
private |
A list of patterns that are used to describe the parameters of this object. Every nodes in the property tree corresponding to a parameter stores an index into this array.
Definition at line 1836 of file parameter_handler.h.
|
private |
A list of actions that are associated with parameters. These are added by the add_action() function. Nodes in the property tree corresponding to individual parameters store indices into this array in order to reference specific actions.
Definition at line 1844 of file parameter_handler.h.
|
mutableprivateinherited |
Store the number of objects which subscribed to this object. Initially, this number is zero, and upon destruction it shall be zero again (i.e. all objects which subscribed should have unsubscribed again).
The creator (and owner) of an object is counted in the map below if HE manages to supply identification.
We use the mutable
keyword in order to allow subscription to constant objects also.
This counter may be read from and written to concurrently in multithreaded code: hence we use the std::atomic
class template.
Definition at line 219 of file subscriptor.h.
|
mutableprivateinherited |
In this map, we count subscriptions for each different identification string supplied to subscribe().
Definition at line 225 of file subscriptor.h.
|
mutableprivateinherited |
In this vector, we store pointers to the validity bool in the ObserverPointer objects that subscribe to this class.
Definition at line 241 of file subscriptor.h.
|
mutableprivateinherited |
Pointer to the typeinfo object of this object, from which we can later deduce the class name. Since this information on the derived class is neither available in the destructor, nor in the constructor, we obtain it in between and store it here.
Definition at line 249 of file subscriptor.h.
|
staticprivateinherited |
A mutex used to ensure data consistency when accessing the mutable
members of this class. This lock is used in the subscribe() and unsubscribe() functions, as well as in list_subscribers()
.
Definition at line 272 of file subscriptor.h.