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 DebugVerbosityLevel {
static constexpr int value = 1; };
65 template <
class TypeTag>
69 using MaterialLawManager =
typename GetProp<TypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
70 using ModelSimulator = GetPropType<TypeTag, Properties::Simulator>;
71 using Grid = GetPropType<TypeTag, Properties::Grid>;
72 using GridView = GetPropType<TypeTag, Properties::GridView>;
73 using Problem = GetPropType<TypeTag, Properties::Problem>;
74 using Scalar = GetPropType<TypeTag, Properties::Scalar>;
75 using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>;
77 using Simulator = SimulatorFullyImplicitBlackoil<TypeTag>;
79 FlowMain(
int argc,
char **argv,
bool output_cout,
bool output_files )
80 : argc_{argc}, argv_{argv},
81 output_cout_{output_cout}, output_files_{output_files}
100 Parameters::Register<Parameters::OutputInterval>
101 (
"Specify the number of report steps between two consecutive writes of restart data");
102 Parameters::Register<Parameters::EnableLoggingFalloutWarning>
103 (
"Developer option to see whether logging was on non-root processors. "
104 "In that case it will be appended to the *.DBG or *.PRT files");
105 Parameters::Register<Parameters::DebugVerbosityLevel>
106 (
"Set debug verbosity level globally. Default is 1, increasing values give additional output and 0 disables most messages to the .DBG file");
109 registerAllParameters_<TypeTag>(
false);
113 detail::hideUnusedParameters<Scalar>();
117 int mpiRank = comm.rank();
120 int status = ::Opm::setupParameters_<TypeTag>(argc,
121 const_cast<const char**
>(argv),
130 int unknownKeyWords = 0;
134 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
135 unknownKeyWords = globalUnknownKeyWords;
136 if ( unknownKeyWords )
140 std::string msg =
"Aborting simulation due to unknown "
141 "parameters. Please query \"flow --help\" for "
142 "supported command line parameters.";
143 if (OpmLog::hasBackend(
"STREAMLOG"))
148 std::cerr << msg << std::endl;
155 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
174 return execute_(&FlowMain::runSimulator,
true);
177 int executeInitStep()
179 return execute_(&FlowMain::runSimulatorInit,
false);
186 return simulator_->runStep(*simtimer_);
191 int executeStepsCleanup()
193 SimulatorReport report = simulator_->finalize();
194 runSimulatorAfterSim_(report);
195 return report.success.exit_status;
198 ModelSimulator* getSimulatorPtr()
200 return modelSimulator_.get();
203 SimulatorTimer* getSimTimer()
205 return simtimer_.get();
209 double getPreviousReportStepSize()
211 return simtimer_->stepLengthTaken();
216 int execute_(
int (FlowMain::* runOrInitFunc)(),
bool cleanup)
218 auto logger = [
this](
const std::exception& e,
const std::string& message_start) {
219 std::ostringstream message;
220 message << message_start << e.what();
222 if (this->output_cout_) {
225 if (OpmLog::hasBackend(
"STREAMLOG")) {
226 OpmLog::error(message.str());
229 std::cout << message.str() <<
"\n";
239 Dune::Timer setupTimerAfterReadingDeck;
240 setupTimerAfterReadingDeck.start();
248 setupModelSimulator();
251 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
252 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
255 int exitCode = (this->*runOrInitFunc)();
261 catch (
const TimeSteppingBreakdown& e) {
262 auto exitCode = logger(e,
"Simulation aborted: ");
266 catch (
const std::exception& e) {
267 auto exitCode = logger(e,
"Simulation aborted as program threw an unexpected exception: ");
273 void executeCleanup_() {
279 void setupParallelism()
285 mpi_rank_ = comm.rank();
286 mpi_size_ = comm.size();
291 static void setMaxThreads()
298 constexpr int default_threads = 2;
299 const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
300 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
301 int threads = requested_threads > 0 ? requested_threads : default_threads;
303 const char* env_var = getenv(
"OMP_NUM_THREADS");
305 int omp_num_threads = -1;
306 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
307 if (result.ec == std::errc() && omp_num_threads > 0) {
309 threads = omp_num_threads;
311 OpmLog::warning(
"Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
314 OpmLog::warning(
"Invalid value for OMP_NUM_THREADS environment variable.");
320 if (env_var || !(isSet && requested_threads == -1)) {
321 omp_set_num_threads(threads);
325 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
332 OpmLog::removeAllBackends();
334 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
339 Parameters::Get<Parameters::EclDeckFileName>(),
340 Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
343 void setupModelSimulator()
346 modelSimulator_->executionTimer().start();
347 modelSimulator_->model().applyInitialSolution();
350 const EclipseState& eclState()
const
351 {
return modelSimulator_->vanguard().eclState(); }
353 EclipseState& eclState()
354 {
return modelSimulator_->vanguard().eclState(); }
356 const Schedule& schedule()
const
357 {
return modelSimulator_->vanguard().schedule(); }
362 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
365 int runSimulatorInit()
367 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
372 int runSimulatorRunCallback_()
374#ifdef RESERVOIR_COUPLING_ENABLED
375 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
377 SimulatorReport report = simulator_->run(*simtimer_);
379 runSimulatorAfterSim_(report);
380 return report.success.exit_status;
384 int runSimulatorInitCallback_()
386#ifdef RESERVOIR_COUPLING_ENABLED
387 simulator_->init(*simtimer_, this->argc_, this->argv_);
389 simulator_->init(*simtimer_);
395 void runSimulatorAfterSim_(SimulatorReport &report)
397 if (simulator_->model().hasNlddSolver()) {
398 const auto& odir = eclState().getIOConfig().getOutputDir();
400 simulator_->model().writeNonlinearIterationsPerCell(odir);
403 simulator_->model().localAccumulatedReports(),
408 if (! this->output_cout_) {
413#if !defined(_OPENMP) || !_OPENMP
416 = omp_get_max_threads();
419 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report);
422 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
423 R
"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
424 eclState().getIOConfig().getOutputDir(),
425 eclState().getIOConfig().getBaseName());
429 int runSimulatorInitOrRun_(
int (FlowMain::* initOrRunFunc)())
432 const auto& schedule = this->schedule();
433 auto& ioConfig = eclState().getIOConfig();
434 simtimer_ = std::make_unique<SimulatorTimer>();
437 const auto& initConfig = eclState().getInitConfig();
438 simtimer_->init(schedule,
static_cast<std::size_t
>(initConfig.getRestartStep()));
440 if (this->output_cout_) {
441 std::ostringstream oss;
446 std::cout <<
"----------------- Unrecognized parameters: -----------------\n";
447 std::cout << oss.str();
448 std::cout <<
"----------------------------------------------------------------" << std::endl;
452 if (!ioConfig.initOnly()) {
453 if (this->output_cout_) {
455 msg =
"\n\n================ Starting main simulation loop ===============\n";
459 return (this->*initOrRunFunc)();
462 if (this->output_cout_) {
463 std::cout <<
"\n\n================ Simulation turned off ===============\n" << std::flush;
475 void createSimulator()
478 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
482 {
return modelSimulator_->vanguard().grid(); }
485 std::unique_ptr<ModelSimulator> modelSimulator_;
488 std::any parallel_information_;
489 std::unique_ptr<Simulator> simulator_;
490 std::unique_ptr<SimulatorTimer> simtimer_;
495 double total_setup_time_ = 0.0;
496 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:214
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:43
void printFlowTrailer(int nprocs, int nthreads, const double total_setup_time, const double deck_read_time, const SimulatorReport &report)
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.