time_step_controller.hh 9.19 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
#ifndef DUNE_DORIE_TIME_CONTROLLER_HH
#define DUNE_DORIE_TIME_CONTROLLER_HH

#include <iostream>
#include <cmath>
#include <algorithm>

#include <dune/common/exceptions.hh>
#include <dune/common/parametertree.hh>
#include <dune/common/float_cmp.hh>

#include <dune/dorie/common/logging.hh>

namespace Dune{
namespace Dorie{

/// Provides access to time step information, as read from a config file
/** This class facilitates the management of time and time step related user
 *  input via config file settings. It does not control the actual simulation
 *  time or time step. Many settings can also be directly manipulated,
 *  if required.
 *
 *  It is tailored for an implict time step scheme without specific criterion
 *  for a time step size. Time step suggestions are incorporated
 *  conservatively: Only suggestions below the current time step are accepted.
 *
 *  The usual way of using this controller would be as follows:
 *  1. Retrieve a time step suggestion from somewhere else.
 *  2. Call suggest_time_step() with the suggestion. Depending on the
 *     current time step, the suggestion may or may not be accepted.
 *  3. Adjust the time step to the simulation end by calling
 *     get_time_step() with the current simulation time as argument.
 *  4. Perform a solver iteration with the given time step.
 *  5. Increase the time step if the solver succeeded, and decrease it
 *     otherwise.
 *  6. Use set_time_step() to choose any time step within the specified
 *     limits. These limits can optionally be ignored.
 *
 *  \note set_time_step() and suggest_time_step() always return the new
 *      new time step. Programmers are free to ignore this value and
 *      retrieve it via get_time_step(), granting the option of adjusting
 *      the time step to the simulation end time.
 *
 *  \tparam TF Time data type
 *  \ingroup Common
 *  \author Lukas Riedel
 *  \date 2019
 */
template<typename TF>
class TimeStepController
{
private:
    using Logger = std::shared_ptr<spdlog::logger>;

    /// The logger for this instance
    const Logger _log;

    const TF _time_begin; //!< Simulation start
    TF _time_end; //!< Simulation end
    const TF _time_step_min, //!< Minimum time step
             _time_step_max, //!< Maximum time step
             _time_step_inc, //!< Time step increment factor
             _time_step_dec; //!< Time step decrement factor

    /// Current time step
    TF _time_step;

public:
    /// Read settings from config file and check input parameters
    /**
     *  \param config The configuration tree to read from
     *  \param log The logger for this instance
     *  \throw IOError if certain settings contradict each other
     */
    explicit TimeStepController (const Dune::ParameterTree& config,
                                 const Logger log=Dorie::get_logger(log_base)):
        _log(log),
        _time_begin(config.get<TF>("time.start")),
        _time_end(config.get<TF>("time.end")),
        _time_step_min(config.get<TF>("time.minTimestep")),
        _time_step_max(config.get<TF>("time.maxTimestep")),
        _time_step_inc(config.get<TF>("time.timestepIncreaseFactor")),
        _time_step_dec(config.get<TF>("time.timestepDecreaseFactor")),
        _time_step(config.get<TF>("time.startTimestep"))
    {
        if (not input_valid()) {
            DUNE_THROW(IOError, "Invalid input for time controller");
        }
    }

    /// Calculate a new time step from the current time and the suggestion
    /** If the new time step exceeds the simulation end time (#_time_end),
     *  it is adjusted to hit it exactly.
     *
     *  \param time Current time (required for adjustment to end time)
     *  \return The new time step
     */
    TF get_time_step (const TF time)
    {
        using namespace Dune::FloatCmp;

        if (ge(time, _time_end)) {
            _log->warn("Current time exceeds the prescribed simulation "
                       "end time");
        }
        // adjust to the simulation end time
        else if (ge(time + _time_step, _time_end)) {
            _log->trace("Adjusting time step to simulation end time");
            set_time_step(_time_end - time);
        }

        return get_time_step();
    }

    /// Return the currently stored time step
    TF get_time_step () const { return _time_step; }

    /// Return the minimum time step
    TF get_time_step_min () const { return _time_step_min; }

    /// Return the maximum time step
    TF get_time_step_max () const { return _time_step_max; }

    /// Return the simulation start time as stored in this class
    TF get_time_begin () const { return _time_begin; }

    /// Return the simulation end time as stored in this class
    TF get_time_end () const { return _time_end; }

    /// Set the time step to any value within the prescribed value range
    /** If the value exceeds the range, a warning is issued and it is
     *  clamped.
     *
     *  \param time_step New time step
     *  \param force Ignore time step limits when setting the value
     *  \return The new time step
     *
     *  \warning Forcing the time step removes all sanity checks. In
     *      particular, negative time steps would be accepted.
     */
    TF set_time_step (const TF time_step, const bool force=false)
    {
        if (not force && not time_step_valid(time_step)) {
            _log->warn("Time step '{}' incompatible to chosen limits. "
                       "Adjusting automatically",
                       time_step);
            _time_step = std::clamp(time_step, _time_step_min, _time_step_max);
        }
        else {
             _time_step = time_step;
        }

        return get_time_step();
    }

    /// Suggest a new time step
    /** Uses the minimum of the stored time step and the suggested time step.
     *
     *  In the special case where the suggested time step and the current time
     *  step differ by less than the minimum time step, the resulting time
     *  step will be appropriately increased.
     *
     *  \param time_step_suggestion External suggestion for a time step.
     *  \return The new time step
     *
     *  \todo Add different policies on how to deal with suggested time steps
     */
    TF suggest_time_step (const TF time_step_suggestion)
    {
        using namespace Dune::FloatCmp;

        const auto time_step_new = std::min(_time_step,
                                            time_step_suggestion);

        // take suggestion to avoid time step smaller than dt_min
        if (ge(time_step_new + _time_step_min, time_step_suggestion))
        {
            set_time_step(time_step_suggestion);
        }
        else {
            set_time_step(time_step_new);
        }

        return get_time_step();
    }

    /// Set a new finish time of the simulation.
    /** \param time_end The new end time
     */
    void set_time_end (const TF time_end)
    {
        _time_end = time_end;
    }

    /// Decrease the time step by a certain decrement factor
    /** \param time_step_decrement Decrement factor
     */
    void decrease_time_step (const TF time_step_decrement)
    {
        _time_step = std::max(_time_step * time_step_decrement,
                              _time_step_min);
    }

    /// Decrease the time step by the default decrement factor
    void decrease_time_step ()
    {
        decrease_time_step(_time_step_dec);
    }

    /// Increase the time step by a certain increment factor
    /** \param time_step_increment Increment factor
     */
    void increase_time_step (const TF time_step_increment)
    {
        _time_step = std::min(_time_step * time_step_increment,
                              _time_step_max);
    }

    /// Increase the time step by the default increment factor
    void increase_time_step ()
    {
        increase_time_step(_time_step_inc);
    }

private:
    /// Some checks if user input makes sense
    /**
     *  \note This method does not throw exceptions by itself!
     *  \return True if the input variables are consistent
     */
    bool input_valid () const
    {
        if (_time_step_inc <= 1.0) {
            _log->error("timestepIncreaseFactor must be >1.0. Value is: {}",
                        _time_step_inc);
            return false;
        }
        if (_time_step_dec>=1.0 || _time_step_dec<=0.0) {
            _log->error("timestepDecreaseFactor exceeds (0.0, 1.0). "
                        "Value is: {}", _time_step_dec);
            return false;
        }
        if (_time_step_max < _time_step_min) {
            _log->error("maxTimestep must be >=minTimestep. "
                        "Values are: {}, {}", _time_step_max, _time_step_min);
            return false;
        }
        if (not time_step_valid(_time_step)) {
            _log->error("Current time step exceeds [minTimestep, "
                        "maxTimestep]. Value is: {}",
                        _time_step);
            return false;
        }

        return true;
    }

    /// Assert that a time step is within valid limits
    /** \param time_step The time step to check
     *  \return True if the time step is valid
     */
    bool time_step_valid (const TF time_step) const
    {
        if (time_step<_time_step_min || time_step>_time_step_max) {
            return false;
        }

        return true;
    }
};

} // namespace Dorie
} // namespace Dune

#endif // DUNE_DORIE_TIME_CONTROLLER_HH