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 = SimulatorFullyImplicit<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>();
114 if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()) {
115 Parameters::Hide<Parameters::VtkWriteTortuosities>();
116 Parameters::Hide<Parameters::VtkWriteDiffusionCoefficients>();
117 Parameters::Hide<Parameters::VtkWriteEffectiveDiffusionCoefficients>();
122 int mpiRank = comm.rank();
125 int status = ::Opm::setupParameters_<TypeTag>(argc,
126 const_cast<const char**
>(argv),
135 int unknownKeyWords = 0;
139 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
140 unknownKeyWords = globalUnknownKeyWords;
141 if ( unknownKeyWords )
145 std::string msg =
"Aborting simulation due to unknown "
146 "parameters. Please query \"flow --help\" for "
147 "supported command line parameters.";
148 if (OpmLog::hasBackend(
"STREAMLOG"))
153 std::cerr << msg << std::endl;
160 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
179 return execute_(&FlowMain::runSimulator,
true);
182 int executeInitStep()
184 return execute_(&FlowMain::runSimulatorInit,
false);
191 return simulator_->runStep(*simtimer_);
196 int executeStepsCleanup()
198 SimulatorReport report = simulator_->finalize();
199 runSimulatorAfterSim_(report);
200 return report.success.exit_status;
203 ModelSimulator* getSimulatorPtr()
205 return modelSimulator_.get();
208 SimulatorTimer* getSimTimer()
210 return simtimer_.get();
214 double getPreviousReportStepSize()
216 return simtimer_->stepLengthTaken();
221 int execute_(
int (FlowMain::* runOrInitFunc)(),
bool cleanup)
223 auto logger = [
this](
const std::exception& e,
const std::string& message_start) {
224 std::ostringstream message;
225 message << message_start << e.what();
227 if (this->output_cout_) {
230 if (OpmLog::hasBackend(
"STREAMLOG")) {
231 OpmLog::error(message.str());
234 std::cout << message.str() <<
"\n";
244 Dune::Timer setupTimerAfterReadingDeck;
245 setupTimerAfterReadingDeck.start();
253 setupModelSimulator();
256 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
257 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
260 int exitCode = (this->*runOrInitFunc)();
266 catch (
const TimeSteppingBreakdown& e) {
267 auto exitCode = logger(e,
"Simulation aborted: ");
271 catch (
const std::exception& e) {
272 auto exitCode = logger(e,
"Simulation aborted as program threw an unexpected exception: ");
278 void executeCleanup_() {
284 void setupParallelism()
290 mpi_rank_ = comm.rank();
291 mpi_size_ = comm.size();
296 static void setMaxThreads()
303 constexpr int default_threads = 2;
304 const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
305 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
306 int threads = requested_threads > 0 ? requested_threads : default_threads;
308 const char* env_var = getenv(
"OMP_NUM_THREADS");
310 int omp_num_threads = -1;
311 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
312 if (result.ec == std::errc() && omp_num_threads > 0) {
314 threads = omp_num_threads;
316 OpmLog::warning(
"Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
319 OpmLog::warning(
"Invalid value for OMP_NUM_THREADS environment variable.");
325 if (env_var || !(isSet && requested_threads == -1)) {
326 omp_set_num_threads(threads);
330 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
337 OpmLog::removeAllBackends();
339 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
344 Parameters::Get<Parameters::EclDeckFileName>(),
345 Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
348 void setupModelSimulator()
351 modelSimulator_->executionTimer().start();
352 modelSimulator_->model().applyInitialSolution();
355 const EclipseState& eclState()
const
356 {
return modelSimulator_->vanguard().eclState(); }
358 EclipseState& eclState()
359 {
return modelSimulator_->vanguard().eclState(); }
361 const Schedule& schedule()
const
362 {
return modelSimulator_->vanguard().schedule(); }
367 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
370 int runSimulatorInit()
372 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
377 int runSimulatorRunCallback_()
379#ifdef RESERVOIR_COUPLING_ENABLED
380 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
382 SimulatorReport report = simulator_->run(*simtimer_);
384 runSimulatorAfterSim_(report);
385 return report.success.exit_status;
389 int runSimulatorInitCallback_()
391#ifdef RESERVOIR_COUPLING_ENABLED
392 simulator_->init(*simtimer_, this->argc_, this->argv_);
394 simulator_->init(*simtimer_);
400 void runSimulatorAfterSim_(SimulatorReport &report)
402 if (simulator_->model().hasNlddSolver()) {
403 const auto& odir = eclState().getIOConfig().getOutputDir();
405 simulator_->model().writeNonlinearIterationsPerCell(odir);
408 simulator_->model().localAccumulatedReports(),
413 if (! this->output_cout_) {
418#if !defined(_OPENMP) || !_OPENMP
421 = omp_get_max_threads();
424 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report);
427 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
428 R
"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
429 eclState().getIOConfig().getOutputDir(),
430 eclState().getIOConfig().getBaseName());
434 int runSimulatorInitOrRun_(
int (FlowMain::* initOrRunFunc)())
437 const auto& schedule = this->schedule();
438 auto& ioConfig = eclState().getIOConfig();
439 simtimer_ = std::make_unique<SimulatorTimer>();
442 const auto& initConfig = eclState().getInitConfig();
443 simtimer_->init(schedule,
static_cast<std::size_t
>(initConfig.getRestartStep()));
445 if (this->output_cout_) {
446 std::ostringstream oss;
451 std::cout <<
"----------------- Unrecognized parameters: -----------------\n";
452 std::cout << oss.str();
453 std::cout <<
"----------------------------------------------------------------" << std::endl;
457 if (!ioConfig.initOnly()) {
458 if (this->output_cout_) {
460 msg =
"\n\n================ Starting main simulation loop ===============\n";
464 return (this->*initOrRunFunc)();
467 if (this->output_cout_) {
468 std::cout <<
"\n\n================ Simulation turned off ===============\n" << std::flush;
480 void createSimulator()
483 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
487 {
return modelSimulator_->vanguard().grid(); }
490 std::unique_ptr<ModelSimulator> modelSimulator_;
493 std::any parallel_information_;
494 std::unique_ptr<Simulator> simulator_;
495 std::unique_ptr<SimulatorTimer> simtimer_;
500 double total_setup_time_ = 0.0;
501 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:45
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.