20#ifndef OPM_ADAPTIVE_TIME_STEPPING_IMPL_HPP
21#define OPM_ADAPTIVE_TIME_STEPPING_IMPL_HPP
24#ifndef OPM_ADAPTIVE_TIME_STEPPING_HPP
30#include <dune/common/timer.hh>
31#include <dune/istl/istlexception.hh>
33#include <opm/common/Exceptions.hpp>
34#include <opm/common/ErrorMacros.hpp>
35#include <opm/common/OpmLog/OpmLog.hpp>
36#include <opm/common/TimingMacros.hpp>
38#include <opm/grid/utility/StopWatch.hpp>
40#include <opm/input/eclipse/Schedule/Tuning.hpp>
42#include <opm/input/eclipse/Units/Units.hpp>
43#include <opm/input/eclipse/Units/UnitSystem.hpp>
56#include <boost/date_time/posix_time/posix_time.hpp>
57#include <fmt/format.h>
58#include <fmt/ranges.h>
66template<
class TypeTag>
70 const double max_next_tstep,
71 const bool terminal_output
73 : time_step_control_{}
74 , restart_factor_{Parameters::
Get<Parameters::SolverRestartFactor<Scalar>>()}
75 , growth_factor_{Parameters::
Get<Parameters::SolverGrowthFactor<Scalar>>()}
76 , max_growth_{Parameters::
Get<Parameters::SolverMaxGrowth<Scalar>>()}
78 Parameters::
Get<Parameters::SolverMaxTimeStepInDays<Scalar>>() * 24 * 60 * 60}
80 unit_system.to_si(UnitSystem::measure::time,
81 Parameters::
Get<Parameters::SolverMinTimeStep<Scalar>>())}
82 , ignore_convergence_failure_{
83 Parameters::
Get<Parameters::SolverContinueOnConvergenceFailure>()}
84 , solver_restart_max_{Parameters::
Get<Parameters::SolverMaxRestarts>()}
85 , solver_verbose_{Parameters::
Get<Parameters::SolverVerbosity>() > 0 && terminal_output}
86 , timestep_verbose_{Parameters::
Get<Parameters::TimeStepVerbosity>() > 0 && terminal_output}
87 , suggested_next_timestep_{
88 (max_next_tstep <= 0 ? Parameters::
Get<Parameters::InitialTimeStepInDays>()
89 : max_next_tstep) * 24 * 60 * 60}
90 , full_timestep_initially_{Parameters::
Get<Parameters::FullTimeStepInitially>()}
91 , timestep_after_event_{
92 Parameters::
Get<Parameters::TimeStepAfterEventInDays<Scalar>>() * 24 * 60 * 60}
93 , use_newton_iteration_{false}
94 , min_time_step_before_shutting_problematic_wells_{
95 Parameters::
Get<Parameters::MinTimeStepBeforeShuttingProblematicWellsInDays>() * unit::day}
107template<
class TypeTag>
110 const Tuning& tuning,
111 const UnitSystem& unit_system,
113 const bool terminal_output
115 : time_step_control_{}
116 , restart_factor_{tuning.TSFCNV}
117 , growth_factor_{tuning.TFDIFF}
118 , max_growth_{tuning.TSFMAX}
119 , max_time_step_{tuning.TSMAXZ}
120 , min_time_step_{tuning.TSMINZ}
121 , ignore_convergence_failure_{true}
122 , solver_restart_max_{Parameters::
Get<Parameters::SolverMaxRestarts>()}
123 , solver_verbose_{Parameters::
Get<Parameters::SolverVerbosity>() > 0 && terminal_output}
124 , timestep_verbose_{Parameters::
Get<Parameters::TimeStepVerbosity>() > 0 && terminal_output}
125 , suggested_next_timestep_{
126 max_next_tstep <= 0 ? Parameters::
Get<Parameters::InitialTimeStepInDays>() * 24 * 60 * 60
128 , full_timestep_initially_{Parameters::
Get<Parameters::FullTimeStepInitially>()}
129 , timestep_after_event_{tuning.TMAXWC}
130 , use_newton_iteration_{false}
131 , min_time_step_before_shutting_problematic_wells_{
132 Parameters::
Get<Parameters::MinTimeStepBeforeShuttingProblematicWellsInDays>() * unit::day}
138template<
class TypeTag>
150 switch (this->time_step_control_type_) {
152 result = castAndComp<HardcodedTimeStepControl>(rhs);
155 result = castAndComp<PIDAndIterationCountTimeStepControl>(rhs);
158 result = castAndComp<SimpleIterationCountTimeStepControl>(rhs);
161 result = castAndComp<PIDTimeStepControl>(rhs);
164 result = castAndComp<General3rdOrderController>(rhs);
180 this->min_time_step_before_shutting_problematic_wells_ ==
184template<
class TypeTag>
189 registerEclTimeSteppingParameters<Scalar>();
194template<
class TypeTag>
195template <
class Solver>
203 SubStepper<Solver> sub_stepper{
204 *
this, simulator_timer, solver, is_event, tuning_updater,
206 return sub_stepper.run();
209template<
class TypeTag>
210template<
class Serializer>
215 serializer(this->time_step_control_type_);
216 switch (this->time_step_control_type_) {
218 allocAndSerialize<HardcodedTimeStepControl>(serializer);
221 allocAndSerialize<PIDAndIterationCountTimeStepControl>(serializer);
224 allocAndSerialize<SimpleIterationCountTimeStepControl>(serializer);
227 allocAndSerialize<PIDTimeStepControl>(serializer);
230 allocAndSerialize<General3rdOrderController>(serializer);
233 serializer(this->restart_factor_);
234 serializer(this->growth_factor_);
235 serializer(this->max_growth_);
236 serializer(this->max_time_step_);
237 serializer(this->min_time_step_);
238 serializer(this->ignore_convergence_failure_);
239 serializer(this->solver_restart_max_);
240 serializer(this->solver_verbose_);
241 serializer(this->timestep_verbose_);
242 serializer(this->suggested_next_timestep_);
243 serializer(this->full_timestep_initially_);
244 serializer(this->timestep_after_event_);
245 serializer(this->use_newton_iteration_);
246 serializer(this->min_time_step_before_shutting_problematic_wells_);
249template<
class TypeTag>
257template<
class TypeTag>
262 return serializationTestObject_<HardcodedTimeStepControl>();
265template<
class TypeTag>
270 return serializationTestObject_<PIDTimeStepControl>();
273template<
class TypeTag>
278 return serializationTestObject_<PIDAndIterationCountTimeStepControl>();
281template<
class TypeTag>
286 return serializationTestObject_<SimpleIterationCountTimeStepControl>();
289template<
class TypeTag>
294 return serializationTestObject_<General3rdOrderController>();
298template<
class TypeTag>
303 this->suggested_next_timestep_ = x;
306template<
class TypeTag>
311 return this->suggested_next_timestep_;
314template<
class TypeTag>
319 return *this->time_step_control_;
323template<
class TypeTag>
330 if (max_next_tstep > 0) {
331 this->suggested_next_timestep_ = max_next_tstep;
335template<
class TypeTag>
338updateTUNING(
double max_next_tstep,
const Tuning& tuning)
340 this->restart_factor_ = tuning.TSFCNV;
341 this->growth_factor_ = tuning.TFDIFF;
342 this->max_growth_ = tuning.TSFMAX;
343 this->max_time_step_ = tuning.TSMAXZ;
344 updateNEXTSTEP(max_next_tstep);
345 this->timestep_after_event_ = tuning.TMAXWC;
352template<
class TypeTag>
353template<
class T,
class Serializer>
358 if (!serializer.isSerializing()) {
359 this->time_step_control_ = std::make_unique<T>();
361 serializer(*
static_cast<T*
>(this->time_step_control_.get()));
364template<
class TypeTag>
367AdaptiveTimeStepping<TypeTag>::
368castAndComp(
const AdaptiveTimeStepping<TypeTag>& Rhs)
const
370 const T* lhs =
static_cast<const T*
>(this->time_step_control_.get());
371 const T* rhs =
static_cast<const T*
>(Rhs.time_step_control_.get());
375template<
class TypeTag>
377AdaptiveTimeStepping<TypeTag>::
378maybeModifySuggestedTimeStepAtBeginningOfReportStep_(
const double original_time_step,
382 if (this->suggested_next_timestep_ < 0) {
383 this->suggested_next_timestep_ = this->restart_factor_ * original_time_step;
386 if (this->full_timestep_initially_) {
387 this->suggested_next_timestep_ = original_time_step;
391 if (is_event && this->timestep_after_event_ > 0) {
392 this->suggested_next_timestep_ = this->timestep_after_event_;
396template<
class TypeTag>
397template<
class Controller>
398AdaptiveTimeStepping<TypeTag>
399AdaptiveTimeStepping<TypeTag>::
400serializationTestObject_()
402 AdaptiveTimeStepping<TypeTag> result;
404 result.restart_factor_ = 1.0;
405 result.growth_factor_ = 2.0;
406 result.max_growth_ = 3.0;
407 result.max_time_step_ = 4.0;
408 result.min_time_step_ = 5.0;
409 result.ignore_convergence_failure_ =
true;
410 result.solver_restart_max_ = 6;
411 result.solver_verbose_ =
true;
412 result.timestep_verbose_ =
true;
413 result.suggested_next_timestep_ = 7.0;
414 result.full_timestep_initially_ =
true;
415 result.use_newton_iteration_ =
true;
416 result.min_time_step_before_shutting_problematic_wells_ = 9.0;
417 result.time_step_control_type_ = Controller::Type;
418 result.time_step_control_ =
419 std::make_unique<Controller>(Controller::serializationTestObject());
428template<
class TypeTag>
430init_(
const UnitSystem& unitSystem)
432 std::tie(time_step_control_type_,
436 if (this->growth_factor_ < 1.0) {
437 OPM_THROW(std::runtime_error,
438 "Growth factor cannot be less than 1.");
448template<
class TypeTag>
449template<
class Solver>
455 const TuningUpdateCallback& tuning_updater)
456 : adaptive_time_stepping_{adaptive_time_stepping}
457 , simulator_timer_{simulator_timer}
459 , is_event_{is_event}
460 , tuning_updater_{tuning_updater}
464template<
class TypeTag>
465template<
class Solver>
466AdaptiveTimeStepping<TypeTag>&
467AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
468getAdaptiveTimerStepper()
470 return adaptive_time_stepping_;
473template<
class TypeTag>
474template<
class Solver>
476AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
479#ifdef RESERVOIR_COUPLING_ENABLED
480 if (isReservoirCouplingSlave_() && reservoirCouplingSlave_().activated()) {
481 return runStepReservoirCouplingSlave_();
483 else if (isReservoirCouplingMaster_() && reservoirCouplingMaster_().activated()) {
484 return runStepReservoirCouplingMaster_();
487 return runStepOriginal_();
490 return runStepOriginal_();
498#ifdef RESERVOIR_COUPLING_ENABLED
499template<
class TypeTag>
500template<
class Solver>
502AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
503isReservoirCouplingMaster_()
const
505 return this->solver_.model().simulator().reservoirCouplingMaster() !=
nullptr;
508template<
class TypeTag>
509template<
class Solver>
511AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
512isReservoirCouplingSlave_()
const
514 return this->solver_.model().simulator().reservoirCouplingSlave() !=
nullptr;
518template<
class TypeTag>
519template<
class Solver>
521AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
522maybeModifySuggestedTimeStepAtBeginningOfReportStep_(
const double original_time_step)
524 this->adaptive_time_stepping_.maybeModifySuggestedTimeStepAtBeginningOfReportStep_(
525 original_time_step, this->is_event_
532 struct ZeroRelativeChange final : RelativeChangeInterface {
533 double relativeChange()
const override {
return 0.0; }
534 } zero_relative_change;
536 const auto* hardcoded_control =
static_cast<const HardcodedTimeStepControl*
>(
537 this->adaptive_time_stepping_.time_step_control_.get());
538 AdaptiveSimulatorTimer report_step_timer{
539 this->simulator_timer_.startDateTime(),
541 this->simulator_timer_.simulationTimeElapsed(),
543 this->simulator_timer_.reportStepNum(),
547 const double hardcoded_initial_step = hardcoded_control->computeTimeStepSize(
550 zero_relative_change,
552 if (std::isfinite(hardcoded_initial_step) && hardcoded_initial_step > 0.0) {
553 this->adaptive_time_stepping_.setSuggestedNextStep(hardcoded_initial_step);
560template<
class TypeTag>
561template<
class Solver>
563AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
564maybeUpdateTuning_(
double elapsed,
double substep_length,
int sub_step_number)
const
566 return this->tuning_updater_(elapsed, substep_length, sub_step_number);
569template<
class TypeTag>
570template<
class Solver>
572AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
575 return this->adaptive_time_stepping_.max_time_step_;
578template <
class TypeTag>
579template <
class Solver>
581AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
584 const auto elapsed = this->simulator_timer_.simulationTimeElapsed();
585 const auto original_time_step = this->simulator_timer_.currentStepLength();
586 const auto report_step = this->simulator_timer_.reportStepNum();
587 maybeUpdateTuning_(elapsed, suggestedNextTimestep_(), 0);
588 maybeModifySuggestedTimeStepAtBeginningOfReportStep_(original_time_step);
590 AdaptiveSimulatorTimer substep_timer{
591 this->simulator_timer_.startDateTime(),
594 suggestedNextTimestep_(),
598 SubStepIteration<Solver> substepIteration{*
this, substep_timer, original_time_step,
true};
599 return substepIteration.run();
602template <
class TypeTag>
603template <
class Solver>
605AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
606suggestedNextTimestep_()
const
608 return this->adaptive_time_stepping_.suggestedNextStep();
612#ifdef RESERVOIR_COUPLING_ENABLED
618template <
class TypeTag>
619template <
class Solver>
621AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
622checkIfSlaveIsTerminated_()
624 if (reservoirCouplingSlave_().terminated()) {
625 OPM_THROW(ReservoirCouplingError,
626 "Internal error: attempt to run a coupled substep loop after the slave "
627 "has been terminated by the master process");
646template <
class TypeTag>
647template <
class Solver>
649AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
650getRcMasterSyncStepLength_(
double prev_step,
652 double step_end_time)
654 const bool sync_at_report_steps = reservoirCouplingMaster_().syncAtReportSteps();
655 double current_step_length;
656 if (sync_at_report_steps) {
657 current_step_length = prev_step;
659 const double remaining = step_end_time - current_time;
660 current_step_length = std::min({suggestedNextTimestep_(), maxTimeStep_(), remaining});
673 current_step_length = reservoirCouplingMaster_().maybeChopSubStep(current_step_length, current_time);
674 auto num_active = reservoirCouplingMaster_().numCoupledSlaves();
675 OpmLog::info(fmt::format(
676 "\nChoosing next sync time{} between master and {} active slave {}: {:.2f} days",
677 sync_at_report_steps ?
" (RSYNC)" :
"",
678 num_active, (num_active == 1 ?
"process" :
"processes"),
679 current_step_length / unit::day
681 return current_step_length;
684template <
class TypeTag>
685template <
class Solver>
686ReservoirCouplingMaster<typename AdaptiveTimeStepping<TypeTag>::Scalar>&
687AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
688reservoirCouplingMaster_()
690 return *(this->solver_.model().simulator().reservoirCouplingMaster());
693template <
class TypeTag>
694template <
class Solver>
695ReservoirCouplingSlave<typename AdaptiveTimeStepping<TypeTag>::Scalar>&
696AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
697reservoirCouplingSlave_()
699 return *(this->solver_.model().simulator().reservoirCouplingSlave());
756template <
class TypeTag>
757template <
class Solver>
759AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
760runStepReservoirCouplingMaster_()
763 const double original_time_step = this->simulator_timer_.currentStepLength();
764 double current_time{this->simulator_timer_.simulationTimeElapsed()};
765 double step_end_time = current_time + original_time_step;
766 const double report_step_start_time = current_time;
767 int report_step_substep_offset = 0;
774 auto current_step_length = original_time_step;
775 auto report_step_idx = this->simulator_timer_.currentStepNum();
776 if (report_step_idx == 0 && iteration == 0) {
777 reservoirCouplingMaster_().initTimeStepping();
779 SimulatorReport report;
781 reservoirCouplingMaster_().maybeReceiveActivationHandshakeFromSlaves(current_time);
783 reservoirCouplingMaster_().sendDontTerminateSignalToSlaves();
784 reservoirCouplingMaster_().receiveNextReportDateFromSlaves();
785 const bool start_of_report_step = (iteration == 0);
786 if (start_of_report_step) {
787 reservoirCouplingMaster_().initStartOfReportStep(report_step_idx);
788 maybeUpdateTuning_(current_time, suggestedNextTimestep_(), 0);
789 maybeModifySuggestedTimeStepAtBeginningOfReportStep_(original_time_step);
791 current_step_length = getRcMasterSyncStepLength_(
792 current_step_length, current_time, step_end_time);
793 reservoirCouplingMaster_().sendNextTimeStepToSlaves(current_step_length);
794 AdaptiveSimulatorTimer substep_timer{
795 this->simulator_timer_.startDateTime(),
798 suggestedNextTimestep_(),
799 this->simulator_timer_.reportStepNum(),
805 substep_timer.setReportStepStartTime(report_step_start_time);
806 substep_timer.setReportStepTotalTime(step_end_time);
807 substep_timer.setReportStepSubstepOffset(report_step_substep_offset);
809 current_time + current_step_length, step_end_time
814 reservoirCouplingMaster_().setFirstSubstepOfSyncTimestep(
true);
818 reservoirCouplingMaster_().setNeedsSlaveDataReceive(
true);
819 SubStepIteration<Solver> substepIteration{*
this, substep_timer, current_step_length, final_step};
820 const auto sub_steps_report = substepIteration.run();
821 report += sub_steps_report;
822 report_step_substep_offset += substep_timer.currentStepNum();
823 current_time += current_step_length;
832template <
class TypeTag>
833template <
class Solver>
835AdaptiveTimeStepping<TypeTag>::SubStepper<Solver>::
836runStepReservoirCouplingSlave_()
838 checkIfSlaveIsTerminated_();
840 const double original_time_step = this->simulator_timer_.currentStepLength();
841 double current_time{this->simulator_timer_.simulationTimeElapsed()};
842 double step_end_time = current_time + original_time_step;
843 const double report_step_start_time = current_time;
844 int report_step_substep_offset = 0;
845 SimulatorReport report;
846 auto report_step_idx = this->simulator_timer_.currentStepNum();
847 if (report_step_idx == 0 && iteration == 0) {
848 reservoirCouplingSlave_().initTimeStepping();
851 bool start_of_report_step = (iteration == 0);
852 if (reservoirCouplingSlave_().maybeReceiveTerminateSignalFromMaster()) {
856 reservoirCouplingSlave_().sendNextReportDateToMasterProcess();
857 const auto timestep = reservoirCouplingSlave_().receiveNextTimeStepFromMaster();
858 if (start_of_report_step) {
859 maybeUpdateTuning_(current_time, suggestedNextTimestep_(), 0);
860 maybeModifySuggestedTimeStepAtBeginningOfReportStep_(timestep);
862 AdaptiveSimulatorTimer substep_timer{
863 this->simulator_timer_.startDateTime(),
866 suggestedNextTimestep_(),
867 this->simulator_timer_.reportStepNum(),
873 substep_timer.setReportStepStartTime(report_step_start_time);
874 substep_timer.setReportStepTotalTime(step_end_time);
875 substep_timer.setReportStepSubstepOffset(report_step_substep_offset);
877 current_time + timestep, step_end_time
882 reservoirCouplingSlave_().setFirstSubstepOfSyncTimestep(
true);
883 SubStepIteration<Solver> substepIteration{*
this, substep_timer, timestep, final_step};
884 const auto sub_steps_report = substepIteration.run();
885 report += sub_steps_report;
886 report_step_substep_offset += substep_timer.currentStepNum();
887 current_time += timestep;
902template<
class TypeTag>
903template<
class Solver>
904AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
905SubStepIteration(SubStepper<Solver>& substepper,
906 AdaptiveSimulatorTimer& substep_timer,
907 const double original_time_step,
909 : substepper_{substepper}
910 , substep_timer_{substep_timer}
911 , original_time_step_{original_time_step}
912 , final_step_{final_step}
913 , adaptive_time_stepping_{substepper.getAdaptiveTimerStepper()}
917template <
class TypeTag>
918template <
class Solver>
920AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
923 auto& simulator = solver_().model().simulator();
924 auto& problem = simulator.problem();
925 const bool truncateTimeStepToFloat = Parameters::Get<Parameters::TruncateTimeStepToFloat>();
928 SimulatorReport report;
931 while (!this->substep_timer_.done()) {
935 maybeUpdateTuningAndTimeStep_();
937 const double dt = this->substep_timer_.currentStepLength();
938 if (timeStepVerbose_()) {
942 maybeUpdateLastSubstepOfSyncTimestep_(dt);
943 auto substep_report = runSubStep_();
944 markFirstSubStepAsFinished_();
946 if (substep_report.converged || checkContinueOnUnconvergedSolution_(dt)) {
947 Dune::Timer perfTimer;
950 problem.setSubStepReport(substep_report);
951 auto& full_report = adaptive_time_stepping_.report();
952 full_report += substep_report;
953 problem.setSimulationReport(full_report);
954 problem.endTimeStep();
955 substep_report.pre_post_time += perfTimer.stop();
957 report += substep_report;
959 OPM_TIMEBLOCK(convergenceSucceeded);
966 double dt_taken = dt;
967 if (truncateTimeStepToFloat) {
968 const double model_dt = simulator.timeStepSize();
969 const double remaining = this->substep_timer_.totalTime()
970 - this->substep_timer_.simulationTimeElapsed();
971 if (model_dt > 0.0 && dt < remaining) {
972 this->substep_timer_.setCurrentStepLength(model_dt);
976 ++this->substep_timer_;
978 const int iterations = getNumIterations_(substep_report);
979 auto dt_estimate = timeStepControlComputeEstimate_(
980 dt_taken, iterations, this->substep_timer_);
982 assert(dt_estimate > 0);
983 dt_estimate = maybeRestrictTimeStepGrowth_(dt_taken, dt_estimate, restarts);
986 maybeReportSubStep_(substep_report);
987 if (this->final_step_ && this->substep_timer_.done()) {
992 report.success.output_write_time += writeOutput_();
996 checkTimeStepCanAdvance_(dt_taken, dt_estimate);
997 setTimeStep_(dt_estimate);
999 report.success.converged = this->substep_timer_.done();
1000 this->substep_timer_.setLastStepFailed(
false);
1003 OPM_TIMEBLOCK(convergenceFailed);
1004 report += substep_report;
1005 this->substep_timer_.setLastStepFailed(
true);
1006 checkTimeStepMaxRestartLimit_(restarts);
1008 double new_time_step = restartFactor_() * dt;
1009 if (substep_report.time_step_rejected) {
1010 const double tol = Parameters::Get<Parameters::TimeStepControlTolerance>();
1011 const double safetyFactor = Parameters::Get<Parameters::TimeStepControlSafetyFactor>();
1012 const double temp_time_step = std::sqrt(safetyFactor * tol / solver_().model().relativeChange()) * dt;
1013 if (temp_time_step < dt) {
1014 new_time_step = temp_time_step;
1017 checkTimeStepMinLimit_(new_time_step);
1018 bool wells_shut =
false;
1019 if (new_time_step > minTimeStepBeforeClosingWells_()) {
1020 chopTimeStep_(new_time_step);
1022 wells_shut = chopTimeStepOrCloseFailingWells_(new_time_step);
1031 problem.setNextTimeStepSize(this->substep_timer_.currentStepLength());
1033 updateSuggestedNextStep_();
1043template<
class TypeTag>
1044template<
class Solver>
1046AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1047checkContinueOnUnconvergedSolution_(
double dt)
const
1049 const bool continue_on_uncoverged_solution = ignoreConvergenceFailure_() && dt <= minTimeStep_();
1050 if (continue_on_uncoverged_solution && solverVerbose_()) {
1052 const auto msg = fmt::format(
1053 "Solver failed to converge but timestep {} is smaller or equal to {}\n"
1054 "which is the minimum threshold given by option --solver-min-time-step\n",
1057 OpmLog::problem(msg);
1059 return continue_on_uncoverged_solution;
1062template<
class TypeTag>
1063template<
class Solver>
1065AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1066checkTimeStepMaxRestartLimit_(
const int restarts)
const
1070 if (restarts >= solverRestartMax_()) {
1071 const auto msg = fmt::format(
1072 fmt::runtime(
"Solver failed to converge after cutting timestep {} times."), restarts
1074 if (solverVerbose_()) {
1078 throw TimeSteppingBreakdown{msg};
1082template<
class TypeTag>
1083template<
class Solver>
1085AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1086checkTimeStepCanAdvance_(
const double current_time_step,
1087 const double new_time_step)
const
1094 if (new_time_step >= minTimeStep_()) {
1102 if (this->substep_timer_.done() || new_time_step >= current_time_step) {
1107 fmt::format(
"Time step control proposed a step of {:.3E} DAYS, below the "
1108 "minimum of {:.3E} DAYS, while every substep converges. The "
1109 "run is not advancing past {:.6E} DAYS.",
1110 new_time_step / 86400.0,
1111 minTimeStep_() / 86400.0,
1112 this->substep_timer_.simulationTimeElapsed() / 86400.0);
1114 if (solverVerbose_()) {
1119 throw TimeSteppingBreakdown{msg};
1122template<
class TypeTag>
1123template<
class Solver>
1125AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1126checkTimeStepMinLimit_(
const double new_time_step)
const
1128 using Meas = UnitSystem::measure;
1131 if (new_time_step < minTimeStep_()) {
1132 std::string msg =
"Solver failed to converge after cutting timestep to ";
1133 if (Parameters::Get<Parameters::EnableTuning>()) {
1134 const UnitSystem& unit_system = solver_().model().simulator().vanguard().eclState().getDeckUnitSystem();
1136 "{:.3E} {}\nwhich is the minimum threshold given by the TUNING keyword\n",
1137 unit_system.from_si(Meas::time, minTimeStep_()),
1138 unit_system.name(Meas::time)
1143 "{:.3E} DAYS\nwhich is the minimum threshold given by option --solver-min-time-step\n",
1144 minTimeStep_() / 86400.0
1147 if (solverVerbose_()) {
1151 throw TimeSteppingBreakdown{msg};
1155template<
class TypeTag>
1156template<
class Solver>
1158AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1159chopTimeStep_(
const double new_time_step)
1161 setTimeStep_(new_time_step);
1162 if (solverVerbose_()) {
1163 const auto msg = fmt::format(fmt::runtime(
"{}\nTimestep chopped to {} days\n"),
1164 this->cause_of_failure_,
1165 unit::convert::to(this->substep_timer_.currentStepLength(), unit::day));
1166 OpmLog::problem(msg);
1170template<
class TypeTag>
1171template<
class Solver>
1173AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1174chopTimeStepOrCloseFailingWells_(
const double new_time_step)
1176 bool wells_shut =
false;
1183 const bool requireRepeatedFailures =
1184 new_time_step > (minTimeStepBeforeClosingWells_() * restartFactor_() * restartFactor_());
1185 const std::set<std::string> failing_wells =
1188 if (failing_wells.empty()) {
1190 chopTimeStep_(new_time_step);
1193 std::vector<std::string> shut_wells;
1194 for (
const auto& well : failing_wells) {
1195 const bool was_shut =
1196 solver_().model().wellModel().forceShutWellByName(well,
1197 this->substep_timer_.simulationTimeElapsed(),
1200 shut_wells.push_back(well);
1204 if (shut_wells.empty()) {
1205 for (
const auto& well : failing_wells) {
1206 const bool was_shut =
1207 solver_().model().wellModel().forceShutWellByName(well,
1208 this->substep_timer_.simulationTimeElapsed(),
1211 shut_wells.push_back(well);
1216 if (shut_wells.empty()) {
1217 chopTimeStep_(new_time_step);
1220 if (solverVerbose_()) {
1221 const std::string msg =
1222 fmt::format(fmt::runtime(
"\nProblematic well(s) were shut: {}"
1223 "(retrying timestep)\n"),
1224 fmt::join(shut_wells,
" "));
1225 OpmLog::problem(msg);
1232template<
class TypeTag>
1233template<
class Solver>
1234boost::posix_time::ptime
1235AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1236currentDateTime_()
const
1238 return simulatorTimer_().currentDateTime();
1241template<
class TypeTag>
1242template<
class Solver>
1244AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1245getNumIterations_(
const SimulatorReportSingle &substep_report)
const
1247 if (useNewtonIteration_()) {
1248 return substep_report.total_newton_iterations;
1251 return substep_report.total_linear_iterations;
1255template<
class TypeTag>
1256template<
class Solver>
1258AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1259growthFactor_()
const
1261 return this->adaptive_time_stepping_.growth_factor_;
1264template<
class TypeTag>
1265template<
class Solver>
1267AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1268ignoreConvergenceFailure_()
const
1270 return adaptive_time_stepping_.ignore_convergence_failure_;
1273template<
class TypeTag>
1274template<
class Solver>
1276AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1277isReservoirCouplingMaster_()
const
1279 return this->substepper_.isReservoirCouplingMaster_();
1282template<
class TypeTag>
1283template<
class Solver>
1285AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1286isReservoirCouplingSlave_()
const
1288 return this->substepper_.isReservoirCouplingSlave_();
1291template<
class TypeTag>
1292template<
class Solver>
1294AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1295markFirstSubStepAsFinished_()
const
1297#ifdef RESERVOIR_COUPLING_ENABLED
1301 if (isReservoirCouplingMaster_()) {
1302 reservoirCouplingMaster_().setFirstSubstepOfSyncTimestep(
false);
1304 else if (isReservoirCouplingSlave_()) {
1305 reservoirCouplingSlave_().setFirstSubstepOfSyncTimestep(
false);
1311template<
class TypeTag>
1312template<
class Solver>
1314AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1317 return this->adaptive_time_stepping_.max_growth_;
1320template<
class TypeTag>
1321template<
class Solver>
1323AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1324maybeReportSubStep_(SimulatorReportSingle substep_report)
const
1326 if (timeStepVerbose_()) {
1327 std::ostringstream ss;
1328 substep_report.reportStep(ss);
1329 OpmLog::info(ss.str());
1333template<
class TypeTag>
1334template<
class Solver>
1336AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1337maybeRestrictTimeStepGrowth_(
const double dt,
double dt_estimate,
const int restarts)
const
1340 dt_estimate = std::min(dt_estimate,
double(maxGrowth_() * dt));
1341 assert(dt_estimate > 0);
1344 dt_estimate = std::min(growthFactor_() * dt, dt_estimate);
1351template<
class TypeTag>
1352template<
class Solver>
1354AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1355maybeUpdateLastSubstepOfSyncTimestep_([[maybe_unused]]
const double dt)
1357#ifdef RESERVOIR_COUPLING_ENABLED
1362 if (isReservoirCouplingSlave_()) {
1364 this->substep_timer_.simulationTimeElapsed() + dt,
1365 this->substep_timer_.totalTime()
1367 reservoirCouplingSlave_().setLastSubstepOfSyncTimestep(is_last);
1375template<
class TypeTag>
1376template<
class Solver>
1378AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1379maybeUpdateTuningAndTimeStep_()
1387 const auto old_value = suggestedNextTimestep_();
1388 if (this->substepper_.maybeUpdateTuning_(this->substep_timer_.simulationTimeElapsed(),
1389 this->substep_timer_.currentStepLength(),
1390 this->substep_timer_.currentStepNum()))
1397 setTimeStep_(suggestedNextTimestep_());
1398 setSuggestedNextStep_(old_value);
1402template<
class TypeTag>
1403template<
class Solver>
1405AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1406minTimeStepBeforeClosingWells_()
const
1408 return this->adaptive_time_stepping_.min_time_step_before_shutting_problematic_wells_;
1411template<
class TypeTag>
1412template<
class Solver>
1414AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1417 return this->adaptive_time_stepping_.min_time_step_;
1420#ifdef RESERVOIR_COUPLING_ENABLED
1421template<
class TypeTag>
1422template<
class Solver>
1423ReservoirCouplingMaster<typename AdaptiveTimeStepping<TypeTag>::Scalar>&
1424AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1425reservoirCouplingMaster_()
const
1427 return this->substepper_.reservoirCouplingMaster_();
1430template<
class TypeTag>
1431template<
class Solver>
1432ReservoirCouplingSlave<typename AdaptiveTimeStepping<TypeTag>::Scalar>&
1433AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1434reservoirCouplingSlave_()
const
1436 return this->substepper_.reservoirCouplingSlave_();
1440template<
class TypeTag>
1441template<
class Solver>
1443AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1444restartFactor_()
const
1446 return this->adaptive_time_stepping_.restart_factor_;
1449template<
class TypeTag>
1450template<
class Solver>
1451SimulatorReportSingle
1452AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1456 SimulatorReportSingle substep_report;
1458 auto handleFailure = [
this, &substep_report]
1459 (
const std::string& failure_reason,
const std::exception& e,
bool log_exception =
true)
1461 substep_report = solver_().failureReport();
1465 this->cause_of_failure_ = failure_reason;
1466 if (
const std::string what = e.what();
1467 !what.empty() && what != failure_reason)
1469 this->cause_of_failure_ +=
" (" + what +
")";
1471 if (log_exception && solverVerbose_()) {
1472 OpmLog::debug(std::string(
"Caught Exception: ") + e.what());
1477 substep_report = solver_().step(this->substep_timer_, &this->adaptive_time_stepping_.timeStepControl());
1478 if (solverVerbose_()) {
1480 OpmLog::debug(
"Overall linear iterations used: "
1484 catch (
const TooManyIterations& e) {
1485 handleFailure(
"Solver convergence failure - Iteration limit reached", e);
1487 catch (
const TimeSteppingBreakdown& e) {
1488 handleFailure(e.what(), e);
1490 catch (
const ConvergenceMonitorFailure& e) {
1491 handleFailure(
"Convergence monitor failure", e,
false);
1493 catch (
const LinearSolverProblem& e) {
1494 handleFailure(
"Linear solver convergence failure", e);
1496 catch (
const NumericalProblem& e) {
1497 handleFailure(
"Solver convergence failure - Numerical problem encountered", e);
1499 catch (
const std::runtime_error& e) {
1500 handleFailure(
"Runtime error encountered", e);
1502 catch (
const Dune::ISTLError& e) {
1503 handleFailure(
"ISTL error - Time step too large", e);
1505 catch (
const Dune::MatrixBlockError& e) {
1506 handleFailure(
"Matrix block error", e);
1509 return substep_report;
1512template<
class TypeTag>
1513template<
class Solver>
1515AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1516setTimeStep_(
double dt_estimate)
1518 this->substep_timer_.provideTimeStepEstimate(dt_estimate);
1521template<
class TypeTag>
1522template<
class Solver>
1524AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1527 return this->substepper_.solver_;
1531template<
class TypeTag>
1532template<
class Solver>
1534AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1535solverRestartMax_()
const
1537 return this->adaptive_time_stepping_.solver_restart_max_;
1540template<
class TypeTag>
1541template<
class Solver>
1543AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1544setSuggestedNextStep_(
double step)
1546 this->adaptive_time_stepping_.setSuggestedNextStep(step);
1549template <
class TypeTag>
1550template <
class Solver>
1551const SimulatorTimer&
1552AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1553simulatorTimer_()
const
1555 return this->substepper_.simulator_timer_;
1558template <
class TypeTag>
1559template <
class Solver>
1561AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1562solverVerbose_()
const
1564 return this->adaptive_time_stepping_.solver_verbose_;
1567template<
class TypeTag>
1568template<
class Solver>
1569boost::posix_time::ptime
1570AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1571startDateTime_()
const
1573 return simulatorTimer_().startDateTime();
1576template <
class TypeTag>
1577template <
class Solver>
1579AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1580suggestedNextTimestep_()
const
1582 return this->adaptive_time_stepping_.suggestedNextStep();
1585template <
class TypeTag>
1586template <
class Solver>
1588AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1589timeStepControlComputeEstimate_(
const double dt,
const int iterations,
1590 const AdaptiveSimulatorTimer& substepTimer)
const
1593 const SolutionTimeErrorSolverWrapper<Solver> relative_change{solver_()};
1594 return this->adaptive_time_stepping_.time_step_control_->computeTimeStepSize(
1595 dt, iterations, relative_change, substepTimer);
1598template <
class TypeTag>
1599template <
class Solver>
1601AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1602timeStepVerbose_()
const
1604 return this->adaptive_time_stepping_.timestep_verbose_;
1614template <
class TypeTag>
1615template <
class Solver>
1617AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1618updateSuggestedNextStep_()
1620 auto suggested_next_step = this->substep_timer_.currentStepLength();
1621 if (! std::isfinite(suggested_next_step)) {
1622 suggested_next_step = this->original_time_step_;
1624 if (timeStepVerbose_()) {
1625 std::ostringstream ss;
1626 this->substep_timer_.report(ss);
1627 ss <<
"Suggested next step size = "
1628 << unit::convert::to(suggested_next_step, unit::day) <<
" (days)" << std::endl;
1629 OpmLog::debug(ss.str());
1631 setSuggestedNextStep_(suggested_next_step);
1634template <
class TypeTag>
1635template <
class Solver>
1637AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1638useNewtonIteration_()
const
1640 return this->adaptive_time_stepping_.use_newton_iteration_;
1643template <
class TypeTag>
1644template <
class Solver>
1646AdaptiveTimeStepping<TypeTag>::SubStepIteration<Solver>::
1649 time::StopWatch perf_timer;
1651 auto& problem = solver_().model().simulator().problem();
1652 problem.writeOutput(
true);
1653 return perf_timer.secsSinceStart();
1660template<
class TypeTag>
1661template<
class Solver>
1662AdaptiveTimeStepping<TypeTag>::
1663SolutionTimeErrorSolverWrapper<Solver>::
1664SolutionTimeErrorSolverWrapper(
const Solver& solver)
1668template<
class TypeTag>
1669template<
class Solver>
1670double AdaptiveTimeStepping<TypeTag>::SolutionTimeErrorSolverWrapper<Solver>::relativeChange()
const
1673 return solver_.model().relativeChange();
Defines some fundamental parameters for all models.
Adaptive time-stepping coordinator for the black-oil simulator.
Definition: AdaptiveTimeStepping.hpp:93
double max_growth_
factor that limits the maximum growth of a time step
Definition: AdaptiveTimeStepping.hpp:435
double max_time_step_
maximal allowed time step size in days
Definition: AdaptiveTimeStepping.hpp:436
bool solver_verbose_
solver verbosity
Definition: AdaptiveTimeStepping.hpp:440
int solver_restart_max_
how many restart of solver are allowed
Definition: AdaptiveTimeStepping.hpp:439
double timestep_after_event_
suggested size of timestep after an event
Definition: AdaptiveTimeStepping.hpp:444
void init_(const UnitSystem &unitSystem)
Definition: AdaptiveTimeStepping_impl.hpp:430
void setSuggestedNextStep(const double x)
Set the suggested length for the next substep [s].
Definition: AdaptiveTimeStepping_impl.hpp:301
double suggestedNextStep() const
Definition: AdaptiveTimeStepping_impl.hpp:309
bool operator==(const AdaptiveTimeStepping< TypeTag > &rhs) const
Definition: AdaptiveTimeStepping_impl.hpp:141
static AdaptiveTimeStepping< TypeTag > serializationTestObjectSimple()
Definition: AdaptiveTimeStepping_impl.hpp:284
bool ignore_convergence_failure_
continue instead of stop when minimum time step is reached
Definition: AdaptiveTimeStepping.hpp:438
void serializeOp(Serializer &serializer)
Definition: AdaptiveTimeStepping_impl.hpp:213
void updateTUNING(double max_next_tstep, const Tuning &tuning)
Apply TUNING keyword parameters.
Definition: AdaptiveTimeStepping_impl.hpp:338
TimeStepControlType time_step_control_type_
type of time step control object
Definition: AdaptiveTimeStepping.hpp:431
const TimeStepControlInterface & timeStepControl() const
Definition: AdaptiveTimeStepping_impl.hpp:317
std::function< bool(double elapsed, double substep_length, int sub_step_number)> TuningUpdateCallback
Callback invoked at the start of each substep to apply TUNING, NEXTSTEP (via ACTIONX),...
Definition: AdaptiveTimeStepping.hpp:119
bool full_timestep_initially_
beginning with the size of the time step from data file
Definition: AdaptiveTimeStepping.hpp:443
SimulatorReport step(const SimulatorTimer &simulator_timer, Solver &solver, const bool is_event, const TuningUpdateCallback &tuning_updater)
Run one report step by orchestrating adaptive substepping.
Definition: AdaptiveTimeStepping_impl.hpp:198
double growth_factor_
factor to multiply time step when solver recovered from failed convergence
Definition: AdaptiveTimeStepping.hpp:434
double restart_factor_
factor to multiply time step with when solver fails to converge
Definition: AdaptiveTimeStepping.hpp:433
double min_time_step_
minimal allowed time step size before throwing
Definition: AdaptiveTimeStepping.hpp:437
void updateNEXTSTEP(double max_next_tstep)
Set suggested_next_timestep_ to max_next_tstep iff max_next_tstep > 0.
Definition: AdaptiveTimeStepping_impl.hpp:326
static AdaptiveTimeStepping< TypeTag > serializationTestObjectHardcoded()
Definition: AdaptiveTimeStepping_impl.hpp:260
AdaptiveTimeStepping()=default
TimeStepController time_step_control_
time step control object
Definition: AdaptiveTimeStepping.hpp:432
static AdaptiveTimeStepping< TypeTag > serializationTestObjectPIDIt()
Definition: AdaptiveTimeStepping_impl.hpp:276
double min_time_step_before_shutting_problematic_wells_
< shut problematic wells when time step size in days are less than this
Definition: AdaptiveTimeStepping.hpp:448
static AdaptiveTimeStepping< TypeTag > serializationTestObject3rdOrder()
Definition: AdaptiveTimeStepping_impl.hpp:292
SimulatorReport & report()
Definition: AdaptiveTimeStepping_impl.hpp:252
static AdaptiveTimeStepping< TypeTag > serializationTestObjectPID()
Definition: AdaptiveTimeStepping_impl.hpp:268
static void registerParameters()
Definition: AdaptiveTimeStepping_impl.hpp:187
bool use_newton_iteration_
use newton iteration count for adaptive time step control
Definition: AdaptiveTimeStepping.hpp:445
Definition: SimulatorTimer.hpp:38
Definition: TimeStepControlInterface.hpp:51
auto Get(bool errorIfNotRegistered=true)
Retrieve a runtime parameter.
Definition: parametersystem.hpp:192
void logTimer(const AdaptiveSimulatorTimer &substep_timer)
void registerAdaptiveParameters()
std::set< std::string > consistentlyFailingWells(const std::vector< StepReport > &sr, bool requireRepeatedFailures)
std::tuple< TimeStepControlType, std::unique_ptr< TimeStepControlInterface >, bool > createController(const UnitSystem &unitSystem)
Definition: blackoilbioeffectsmodules.hh:45
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
This file provides the infrastructure to retrieve run-time parameters.
static bool compare_gt_or_eq(double a, double b)
Determines if a is greater than b within the specified tolerance.
Definition: SimulatorReport.hpp:202