22#ifndef OPM_FLOW_MAIN_HEADER_INCLUDED
23#define OPM_FLOW_MAIN_HEADER_INCLUDED
25#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
26#include <opm/input/eclipse/EclipseState/IOConfig/IOConfig.hpp>
27#include <opm/input/eclipse/EclipseState/InitConfig/InitConfig.hpp>
38#include <dune/fem/misc/mpimanager.hh>
40#include <dune/common/parallel/mpihelper.hh>
54struct EnableLoggingFalloutWarning {
static constexpr bool value =
false; };
55struct OutputInterval {
static constexpr int value = 1; };
57struct EndStep {
static constexpr int value = -1; };
59struct DebugVerbosityLevel {
static constexpr int value = 1; };
67 template <
class TypeTag>
71 using MaterialLawManager =
typename GetProp<TypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
72 using ModelSimulator = GetPropType<TypeTag, Properties::Simulator>;
73 using Grid = GetPropType<TypeTag, Properties::Grid>;
74 using GridView = GetPropType<TypeTag, Properties::GridView>;
75 using Problem = GetPropType<TypeTag, Properties::Problem>;
76 using Scalar = GetPropType<TypeTag, Properties::Scalar>;
77 using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>;
79 using Simulator = SimulatorFullyImplicit<TypeTag>;
81 FlowMain(
int argc,
char **argv,
bool output_cout,
bool output_files )
82 : argc_{argc}, argv_{argv},
83 output_cout_{output_cout}, output_files_{output_files}
102 Parameters::Register<Parameters::OutputInterval>
103 (
"Specify the number of report steps between two consecutive writes of restart data");
104 Parameters::Register<Parameters::EnableLoggingFalloutWarning>
105 (
"Developer option to see whether logging was on non-root processors. "
106 "In that case it will be appended to the *.DBG or *.PRT files");
107 Parameters::Register<Parameters::DebugVerbosityLevel>
108 (
"Set debug verbosity level globally. Default is 1, increasing values give additional output and 0 disables most messages to the .DBG file");
109 Parameters::Register<Parameters::EndStep>
110 (
"Stop the simulation after this report step. "
111 "A negative value runs to the end of the schedule");
114 registerAllParameters_<TypeTag>(
false);
118 detail::hideUnusedParameters<Scalar>();
119 if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()) {
120 Parameters::Hide<Parameters::VtkWriteTortuosities>();
121 Parameters::Hide<Parameters::VtkWriteDiffusionCoefficients>();
122 Parameters::Hide<Parameters::VtkWriteEffectiveDiffusionCoefficients>();
127 int mpiRank = comm.rank();
130 int status = ::Opm::setupParameters_<TypeTag>(argc,
131 const_cast<const char**
>(argv),
140 int unknownKeyWords = 0;
144 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
145 unknownKeyWords = globalUnknownKeyWords;
146 if ( unknownKeyWords )
150 std::string msg =
"Aborting simulation due to unknown "
151 "parameters. Please query \"flow --help\" for "
152 "supported command line parameters.";
153 if (OpmLog::hasBackend(
"STREAMLOG"))
158 std::cerr << msg << std::endl;
165 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
184 return execute_(&FlowMain::runSimulator,
true);
187 int executeInitStep()
189 return execute_(&FlowMain::runSimulatorInit,
false);
196 return simulator_->runStep(*simtimer_);
201 int executeStepsCleanup()
203 SimulatorReport report = simulator_->finalize();
204 runSimulatorAfterSim_(report);
205 return report.success.exit_status;
208 ModelSimulator* getSimulatorPtr()
210 return modelSimulator_.get();
213 SimulatorTimer* getSimTimer()
215 return simtimer_.get();
222 Simulator* getStepDriverPtr()
224 return simulator_.get();
228 double getPreviousReportStepSize()
230 return simtimer_->stepLengthTaken();
235 int execute_(
int (FlowMain::* runOrInitFunc)(),
bool cleanup)
237 auto logger = [
this](
const std::exception& e,
const std::string& message_start) {
238 std::ostringstream message;
239 message << message_start << e.what();
241 if (this->output_cout_) {
244 if (OpmLog::hasBackend(
"STREAMLOG")) {
245 OpmLog::error(message.str());
248 std::cout << message.str() <<
"\n";
258 Dune::Timer setupTimerAfterReadingDeck;
259 setupTimerAfterReadingDeck.start();
267 setupModelSimulator();
270 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
271 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
274 int exitCode = (this->*runOrInitFunc)();
280 catch (
const TimeSteppingBreakdown& e) {
281 auto exitCode = logger(e,
"Simulation aborted: ");
285 catch (
const std::exception& e) {
286 auto exitCode = logger(e,
"Simulation aborted as program threw an unexpected exception: ");
292 void executeCleanup_() {
298 void setupParallelism()
304 mpi_rank_ = comm.rank();
305 mpi_size_ = comm.size();
310 static void setMaxThreads()
317 constexpr int default_threads = 2;
318 const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
319 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
320 int threads = requested_threads > 0 ? requested_threads : default_threads;
322 const char* env_var = getenv(
"OMP_NUM_THREADS");
324 int omp_num_threads = -1;
325 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
326 if (result.ec == std::errc() && omp_num_threads > 0) {
328 threads = omp_num_threads;
330 OpmLog::warning(
"Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
333 OpmLog::warning(
"Invalid value for OMP_NUM_THREADS environment variable.");
339 if (env_var || !(isSet && requested_threads == -1)) {
340 omp_set_num_threads(threads);
344 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
351 OpmLog::removeAllBackends();
353 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
358 Parameters::Get<Parameters::EclDeckFileName>(),
359 Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
362 void setupModelSimulator()
365 modelSimulator_->executionTimer().start();
366 modelSimulator_->model().applyInitialSolution();
369 const EclipseState& eclState()
const
370 {
return modelSimulator_->vanguard().eclState(); }
372 EclipseState& eclState()
373 {
return modelSimulator_->vanguard().eclState(); }
375 const Schedule& schedule()
const
376 {
return modelSimulator_->vanguard().schedule(); }
381 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
384 int runSimulatorInit()
386 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
391 int runSimulatorRunCallback_()
393#ifdef RESERVOIR_COUPLING_ENABLED
394 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
396 SimulatorReport report = simulator_->run(*simtimer_);
398 runSimulatorAfterSim_(report);
399 return report.success.exit_status;
403 int runSimulatorInitCallback_()
405#ifdef RESERVOIR_COUPLING_ENABLED
406 simulator_->init(*simtimer_, this->argc_, this->argv_);
408 simulator_->init(*simtimer_);
414 void runSimulatorAfterSim_(SimulatorReport &report)
416 if (simulator_->model().hasNlddSolver()) {
417 const auto& odir = eclState().getIOConfig().getOutputDir();
419 simulator_->model().writeNonlinearIterationsPerCell(odir);
422 simulator_->model().localAccumulatedReports(),
427 if (! this->output_cout_) {
432#if !defined(_OPENMP) || !_OPENMP
435 = omp_get_max_threads();
438 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
439 simulator_->model().simulator().problem().extraTrailerSummary());
442 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
443 R
"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
444 eclState().getIOConfig().getOutputDir(),
445 eclState().getIOConfig().getBaseName());
449 int runSimulatorInitOrRun_(
int (FlowMain::* initOrRunFunc)())
452 const auto& schedule = this->schedule();
453 auto& ioConfig = eclState().getIOConfig();
454 simtimer_ = std::make_unique<SimulatorTimer>();
457 const auto& initConfig = eclState().getInitConfig();
458 simtimer_->init(schedule,
459 static_cast<std::size_t
>(initConfig.getRestartStep()),
460 Parameters::Get<Parameters::EndStep>());
462 if (this->output_cout_) {
463 std::ostringstream oss;
468 std::cout <<
"----------------- Unrecognized parameters: -----------------\n";
469 std::cout << oss.str();
470 std::cout <<
"----------------------------------------------------------------" << std::endl;
474 if (!ioConfig.initOnly()) {
475 if (this->output_cout_) {
477 msg =
"\n\n================ Starting main simulation loop ===============\n";
481 return (this->*initOrRunFunc)();
484 if (this->output_cout_) {
485 std::cout <<
"\n\n================ Simulation turned off ===============\n" << std::flush;
497 void createSimulator()
500 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
504 {
return modelSimulator_->vanguard().grid(); }
507 std::unique_ptr<ModelSimulator> modelSimulator_;
510 std::any parallel_information_;
511 std::unique_ptr<Simulator> simulator_;
512 std::unique_ptr<SimulatorTimer> simtimer_;
517 double total_setup_time_ = 0.0;
518 double deck_read_time_ = 0.0;
static Parallel::Communication & comm()
Obtain global communicator.
Definition: FlowGenericVanguard.hpp:336
static void registerParameters()
Registers all runtime parameters used by the simulation.
Definition: simulator.hh:215
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Definition: blackoilnewtonmethodparams.hpp:31
void printValues(std::ostream &os)
Print values of the run-time parameters.
bool IsRegistrationOpen()
Query whether parameter registration is open or not.
void endRegistration()
Indicate that all parameters are registered for a given type tag.
bool printUnused(std::ostream &os)
Print the list of unused run-time parameters.
void handleExtraConvergenceOutput(const SimulatorReport &report, std::string_view option, std::string_view optionName, std::string_view output_dir, std::string_view base_name)
void mergeParallelLogFiles(std::string_view output_dir, std::string_view deck_filename, bool enableLoggingFalloutWarning)
void checkAllMPIProcesses()
Definition: blackoilbioeffectsmodules.hh:45
void printFlowTrailer(int nprocs, int nthreads, const double total_setup_time, const double deck_read_time, const SimulatorReport &report, std::string_view extra_summary)
void reportNlddStatistics(const std::vector< SimulatorReport > &domain_reports, const SimulatorReport &local_report, const bool output_cout, const Parallel::Communication &comm)
Provides convenience routines to bring up the simulation at runtime.