File options.hxx#

Defines

OPTIONS_H#
OPTION(options, var, def)#

Define for reading options which passes the variable name.

OPTION2(options, var1, var2, def)#
OPTION3(options, var1, var2, var3, def)#
OPTION4(options, var1, var2, var3, var4, def)#
OPTION5(options, var1, var2, var3, var4, var5, def)#
OPTION6(options, var1, var2, var3, var4, var5, var6, def)#
VAROPTION(options, var, def)#
BOUT_OVERRIDE_DEFAULT_OPTION(name, value)#

Define for over-riding library defaults for options, should be called in global namespace so that the new default is set before main() is called.

Functions

template<>
std::string as<std::string>(const std::string &similar_to) const

Specialised as routines.

std::string toString(const Options &value)

Convert value to string.

template<class T, typename = bout::utils::EnableIfOptions<T>>
inline std::ostream &operator<<(std::ostream &out, const T &value)#

Output a stringified value to a stream

This is templated to avoid implict casting: anything is convertible to an Options, and we want exactly Options

class Options#
#include <options.hxx>

Class to represent hierarchy of options.

Getting and setting values

Each Options object represents a collection of key-value pairs which can be used as a map.

Options options;

// Set values
options["key"] = 1.0;

// Get values. Throws BoutException if not found
int val = options["key"]; // Sets val to 1 

// Return as specified type. Throws BoutException if not found
BoutReal var = options["key"].as<BoutReal>();

// A default value can be used if key is not found
BoutReal value = options["pi"].withDefault(3.14);

// Assign value with source label. Throws if already has a value from same source
options["newkey"].assign(1.0, "some source");

// Force assign a new value
options["newkey"].force(2.0, "some source");
A legacy interface is also supported:
options.set("key", 1.0, "code"); // Sets a key from source "code"

int val;
options.get("key", val, 0); // Sets val to 1, default to 0 if not found
If a variable has not been set then the default value is used
int other;
options.get("otherkey", other, 2.0); // Sets other to 2 because "otherkey" not found
Conversion is performed silently:
options.set("value", "2.34", "here"); // Set a string

BoutReal value;
options.get("value", value, 0.0); // Sets value to 2.34
If a conversion cannot be done, then an exception is thrown

Sections

Each Options object can also contain any number of sections, which are themselves Options objects.

Options &section = options["section"];
which can be nested:
options["section"]["subsection"]["value"] = 3;
This always succeeds; if the section does not exist then it is created.

The legacy interface uses pointers:

Options *section = options.getSection("section");
e.g. options->getSection(“section”)->getSection(“subsection”)->set(“value”, 3);

Options also know about their parents:

Options &parent = section.parent();
or
Options *parent = section->getParent();
Root options object

For convenience, to avoid having to pass Options objects around everywhere, there is a global singleton Options object which can be accessed with a static function

Options &root = Options::root();

or

Options *root = Options::getRoot();

This is used to represent all the options passed to BOUT++ either in a file or on the command line.

Copying options

The copy constructor and copy assignment operator are deleted, so this is a compile-time error:

Options options2 = options1["value"];
This is because it’s ambiguous what is meant, and because accidental copies were a frequent source of hard-to-understand bugs. Usually a reference is intended, rather than a copy:
Options& ref = options1["value"];
so that changes to ref or its children are reflected in options1. If the intent is to copy the value of the option, then just copy that:
option2.value = options1["value"].value;
If a full deep copy of the option, its attributes and children (recursively) is really desired, then use the copy() method:
Options options2 = options1["value"].copy();

Public Types

using ValueType = bout::utils::variant<bool, int, BoutReal, std::string, Field2D, Field3D, FieldPerp, Array<BoutReal>, Matrix<BoutReal>, Tensor<BoutReal>>#

The type used to store values.

using InitializerList = std::initializer_list<std::pair<std::string, CopyableOptions>>#

Type of initializer_list that can be used to create Options This is a workaround for initializer_lists not being movable.

Public Functions

Options() = default#

Constructor. This is called to create the root object.

inline Options(Options *parent_instance, std::string full_name)#

Constructor used to create non-root objects

Parameters:
  • parent[in] Parent object

  • sectionName[in] Name of the section, including path from the root

template<typename T>
inline Options(T value)#

Initialise with a value These enable Options to be constructed using initializer lists

Options(InitializerList values, Options *parent_instance = nullptr, std::string section_name = "")#

Construct with a nested initializer list This allows Options trees to be constructed using a mix of types.

Example: { {“key1”, 42}, {“key2”, field} }

Note: Options doesn’t have a copy constructor, and initializer lists don’t play nicely with uncopyable types. Instead, we create a tree of CopyableOptions and then move.

Options(const Options &other)#

Options must be explicitly copied

Option option2 = option1.copy();

Options &operator=(const Options &other)#

Copy assignment must be explicit

Option option2 = option1.copy();
Note that the value can be copied using:
option2.value = option1.value;

Options copy() const#

Make a deep copy of this Options, recursively copying children.

Options(Options &&other) noexcept#
Options &operator=(Options &&other) noexcept#
~Options() = default#
inline bool hasAttribute(const std::string &key) const#

Return true if this value has attribute key.

inline Options &setAttributes(const std::initializer_list<std::pair<std::string, Options::AttributeType>> &attrs)#

Set attributes, overwriting any already set

Parameters

An initializer_list so that multiple attributes can be set at the same time

Returns

A reference to this, for method chaining

Example

Options options;
options["value"].setAttributes({
    {"units", "m/s"},
    {"conversion", 10.2},
    {"long_name", "some velocity"}
  });
Options &operator[](const std::string &name)#

Get a sub-section or value

Example:

Options parent; auto child = parent[“child”];

parent is now a section.

inline Options &operator[](const char *name)#
const Options &operator[](const std::string &name) const#

Get a sub-section or value If this object is not a section, or if name is not a child, then a BoutException will be thrown

inline const Options &operator[](const char *name) const#
std::multiset<FuzzyMatch> fuzzyFind(const std::string &name, std::string::size_type distance = 4) const#

Find approximate matches for name throughout the whole tree. distance controls the similarity of results

Returns a set of possible matches ordered by similarity to name. A distance of 1 means: a single insertion, deletion, substitution, or transposition; that the case differs, for example, “key” and “KEY” match with distance 1; or that an unqualified name matches a fully-qualified name, for example “key” matches “section:key” with distance 1. Note that “first:second:key” will not (closely) match “third:fourth:key”, but “key” will match both.

template<typename T>
inline T operator=(T inputvalue)#

Assignment from any type T Note: Using this makes this object a value.

Tries to stream the input to a std::stringstream and then saves the resulting string.

template<typename T>
inline void assign(T val, std::string source = "")#

Assign a value to the option. This will throw an exception if already has a value

Example:

Options option; option[“test”].assign(42, “some source”);

Note: Specialised versions for types stored in ValueType

template<typename T>
inline void force(T val, const std::string source = "")#

Force to a value Overwrites any existing setting

template<typename T>
inline void assignRepeat(T val, std::string time_dimension = "t", bool save_repeat = true, std::string source = "")#

Assign a value that is expected to vary in time.

Overwrites any existing setting, and ensures the “time_dimension” attribute is set. If save_repeat is false, doesn’t set “time_dimension”. This can be useful in some generic functions

bool isSet() const#

Test if a key is set by the user. Values set via default values are ignored.

template<typename T, typename = typename std::enable_if_t<bout::utils::isVariantMember<T, ValueType>::value>>
inline operator T() const#

Cast operator, which allows this class to be assigned to type T. This is only allowed for types that are members of the ValueType variant. For other types, please use Options::as<T>()

Example:

Options option;
option["test"] = 2.0;
int value = option["test"];

template<typename T>
inline T as(const T &similar_to = {}) const#

Get the value as a specified type. If there is no value then an exception is thrown. Note there are specialised versions of this template for some types.

Example:

Options option;
option["test"] = 2.0;
int value = option["test"].as<int>();
An optional argument is an object which the result should be similar to. The main use for this is in Field2D and Field3D specialisations, where the Mesh and cell location are taken from this input.

Attributes override properties of the similar_to argument.

template<typename T>
inline T withDefault(T def)#

Get the value of this option. If not found, set to the default value

inline std::string withDefault(const char *def)#

Overloaded version for const char* Note: Different from template since return type is different to input

inline Options &withDefault(const Options &def)#

Overloaded version to copy from another option.

template<typename T>
inline T withDefault(T def) const#

Get the value of this option. If not found, return the default value but do not set

template<typename T>
inline T overrideDefault(T def)#

Allow the user to override defaults set later, also used by the BOUT_OVERRIDE_DEFAULT_OPTION.

inline std::string overrideDefault(const char *def)#

Overloaded version for const char* Note: Different from template since return type is different to input

inline Options &parent()#

Get the parent Options object.

template<typename T>
inline bool operator==(const T &other) const#

Equality operator Converts to the same type and compares This conversion may fail, throwing std::bad_cast

bool operator==(const char *other) const#

Overloaded equality operator for literal strings.

template<typename T>
inline bool operator<(const T &other) const#

Comparison operator.

bool operator<(const char *other) const#

Overloaded comparison operator for literal strings.

template<typename T>
inline void set(const std::string &key, T val, const std::string &source = "", bool force = false)#
template<typename T>
inline void forceSet(const std::string &key, T val, const std::string &source = "")#
inline bool isSet(const std::string &key) const#

Test if a key is set by the user. Values set via default values are ignored.

template<typename T, typename U>
inline void get(const std::string &key, T &val, U def, bool log = false)#

Get options, passing in a reference to a variable which will be set to the requested value.

template<typename T, typename U>
inline void get(const std::string &key, T &val, U def, bool log = false) const#
inline Options *getSection(const std::string &name)#

Creates new section if doesn’t exist.

inline const Options *getSection(const std::string &name) const#
inline Options *getParent() const#
inline std::string str() const#

Print string representation of this object and all sections in a tree structure

inline std::string name() const#

Print just the name of this object without parent sections.

Options getUnused(const std::vector<std::string> &exclude_sources = {"Output", "user_default"}) const#

Return a new Options instance which contains all the values not used from this instance. If an option has a “source” attribute in exclude_sources it is counted as having been used and so won’t be included in the returned value. By default, this is “Output” and “user_default” (used by overrideDefault).

void printUnused() const#

Print the options which haven’t been used.

void setConditionallyUsed()#

Set the attribute “conditionally used” to be true for options and all its children/sections, causing Options::getUnused to assume those options have been used. This is useful to ignore options when checking for typos etc.

std::map<std::string, const Options*> subsections() const#

Read-only access to internal options and sections to allow iteration over the tree

inline const std::map<std::string, Options> &getChildren() const#
std::vector<std::string> getFlattenedKeys() const#

Return a vector of all the full names of all the keys below this in the tree (not gauranteed to be sorted)

inline bool isValue() const#

Return true if this is a value.

bool isSection(const std::string &name = "") const#

Return true if this is a section.

inline bool valueUsed() const#

If the option value has been used anywhere.

inline Options &doc(const std::string &docstring)#

Set a documentation string as an attribute “doc” Returns a reference to this, to allow chaining

template<>
inline void assign(bool val, std::string source)#
template<>
inline void assign(int val, std::string source)#
template<>
inline void assign(BoutReal val, std::string source)#
template<>
inline void assign(std::string val, std::string source)#
template<>
inline void assign(const char *val, std::string source)#
template<>
void assign(Field2D val, std::string source)#
template<>
void assign(Field3D val, std::string source)#
template<>
void assign(FieldPerp val, std::string source)#
template<>
void assign(Array<BoutReal> val, std::string source)#
template<>
void assign(Matrix<BoutReal> val, std::string source)#
template<>
void assign(Tensor<BoutReal> val, std::string source)#
template<>
int as(const int &similar_to) const#
template<>
BoutReal as(const BoutReal &similar_to) const#
template<>
bool as(const bool &similar_to) const#
template<>
Field2D as(const Field2D &similar_to) const#
template<>
Field3D as(const Field3D &similar_to) const#
template<>
FieldPerp as(const FieldPerp &similar_to) const#
template<>
Array<BoutReal> as(const Array<BoutReal> &similar_to) const#
template<>
Matrix<BoutReal> as(const Matrix<BoutReal> &similar_to) const#
template<>
Tensor<BoutReal> as(const Tensor<BoutReal> &similar_to) const#

Public Members

ValueType value#

The value stored.

std::map<std::string, AttributeType> attributes#

A collection of attributes belonging to the value Special attributes:

  • time_dimension [string] If this is set then changes to the value do not need to be forced. The string will be used when writing the output as the name of the time dimension (unlimited first dimension in NetCDF files).

  • source [string] Describes where the value came from e.g. a file name, or “default”.

  • type [string] The type the Option is converted to when used.

  • doc [string] Documentation, describing what the variable does

Public Static Functions

static Options &root()#

Get a reference to the only root instance.

static void cleanup()#

Free all memory.

static inline Options *getRoot()#

Get a pointer to the only root instance (singleton)

static void cleanCache()#

clean the cache of parsed options

static std::string getDefaultSource()#

Private Functions

template<typename T>
inline void _set_no_check(T val, std::string source)#
template<typename T>
inline void _set(T val, std::string source, bool force)#
template<typename T>
inline bool similar(T lhs, T rhs) const#

Tests if two values are similar.

template<>
inline bool similar(BoutReal lhs, BoutReal rhs) const#

Specialised similar comparison methods.

Private Members

Options *parent_instance = {nullptr}#
std::string full_name#
bool is_section = true#

Is this Options object a section?

std::map<std::string, Options> children#

If a section then has children.

mutable bool value_used = false#

Record whether this value is used.

Private Static Attributes

static const std::string DEFAULT_SOURCE = {_("default")}#

The source label given to default values.

Friends

inline friend bool operator==(const Options &lhs, const Options &rhs)#
class AttributeType : public mpark::variant<bool, int, BoutReal, std::string>#
#include <options.hxx>

The type used to store attributes Extends the variant class so that cast operator can be implemented and assignment operator overloaded

Note: Due to default initialisation rules, if an attribute is used without being set, it will be false, 0, 0.0 and throw std::bad_cast if cast to std::string

Public Types

using Base = bout::utils::variant<bool, int, BoutReal, std::string>#

Public Functions

AttributeType() = default#
AttributeType(const AttributeType &other) = default#
AttributeType(AttributeType &&other) = default#
AttributeType &operator=(const AttributeType &other) = default#
AttributeType &operator=(AttributeType &&other) = default#
~AttributeType() = default#
inline AttributeType &operator=(const char *str)#

Assignment from const char*.

template<typename T>
inline AttributeType(T value)#

Initialise with a value This enables AttributeTypes to be constructed using initializer lists

template<typename T>
inline operator T() const#

Cast operator, which allows this class to be assigned to type T This will throw std::bad_cast if it can’t be done

template<typename T>
inline T as() const#

Get the value as a specified type This will throw std::bad_cast if it can’t be done

struct CopyableOptions#
#include <options.hxx>

A tree representation with leaves containing ValueType. Used to construct Options from initializer lists.

Note: Either there are children OR value is assigned

Public Functions

template<typename T>
inline CopyableOptions(T value)#
inline CopyableOptions(const char *value)#

Special case for char*, which can otherwise become cast to bool.

inline CopyableOptions(std::initializer_list<std::pair<std::string, CopyableOptions>> children)#

Public Members

ValueType value#
std::initializer_list<std::pair<std::string, CopyableOptions>> children#
struct FuzzyMatch#
#include <options.hxx>

Return type of Options::fuzzyFind

Public Members

const Options &match#

The matching option.

std::string::size_type distance#

Edit distance from original search term.

Friends

inline friend bool operator<(const FuzzyMatch &lhs, const FuzzyMatch &rhs)#

Comparison operator so this works in a std::multiset.

template<>
struct formatter<Options> : public bout::details::OptionsFormatterBase#
#include <options.hxx>

Format Options to string. Format string specification is:

  • ‘d’: include ‘doc’ attribute if present

  • ’i’: inline section names

  • ’k’: only print the key, not the value

  • ’s’: include ‘source’ attribute if present

namespace bout

Provides access to the Hypre library, handling initialisation and finalisation.

Usage

#include <bout/hyprelib.hxx>

class MyClass { public:

private: HypreLib lib; };

This will then automatically initialise Hypre the first time an object is created, and finalise it when the last object is destroyed.

Copyright 2012 B.D.Dudson, S.Farley, M.V.Umansky, X.Q.Xu

Contact: Ben Dudson, bd512@york.ac.uk

This file is part of BOUT++.

BOUT++ is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

BOUT++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with BOUT++. If not, see http://www.gnu.org/licenses/.

Information about the version of BOUT++

The build system will update this file on every commit, which may result in files that include it getting rebuilt. Therefore it should be included in as few places as possible

Information about the version of BOUT++

The build system will update this file at configure-time

SNB model

namespace details#
struct OptionsFormatterBase#
#include <options.hxx>

Implementation of fmt::formatter<Options> in a non-template class so that we can put the function definitions in the .cxx file, avoiding lengthy recompilation if we change it

Subclassed by fmt::formatter< Options >

Public Functions

auto parse(fmt::format_parse_context &ctx) -> fmt::format_parse_context::iterator#
auto format(const Options &options, fmt::format_context &ctx) const -> fmt::format_context::iterator#

Private Members

bool docstrings = {false}#

Include the ‘doc’ attribute, if present.

bool unused = {false}#

If an option is unused add a comment and whether it is conditionally unused

bool inline_section_names = {false}#

If true, print variables as ‘section:variable’, rather than a section header ‘[section]’ and plain ‘variable’

bool key_only = {false}#

Only include the key name, and not the value.

bool source = {false}#

Include the ‘source’ attribute, if present.

std::string format_string#

Format string to passed down to subsections.