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>
40#include <dune/fem/misc/mpimanager.hh>
42#include <dune/common/parallel/mpihelper.hh>
56struct EnableLoggingFalloutWarning {
static constexpr bool value =
false; };
57struct OutputInterval {
static constexpr int value = 1; };
59struct EndStep {
static constexpr int value = -1; };
61struct DebugVerbosityLevel {
static constexpr int value = 1; };
71 inline bool allRanksDebugLoggingEnabled()
76 return Parameters::Get<Parameters::EnableLoggingFalloutWarning>()
77 || (Parameters::IsSet<Parameters::FlashVerbosity>(
false)
78 && (Parameters::Get<Parameters::FlashVerbosity>(
false) > 0));
84 template <
class TypeTag>
88 using MaterialLawManager =
typename GetProp<TypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
89 using ModelSimulator = GetPropType<TypeTag, Properties::Simulator>;
90 using Grid = GetPropType<TypeTag, Properties::Grid>;
91 using GridView = GetPropType<TypeTag, Properties::GridView>;
92 using Problem = GetPropType<TypeTag, Properties::Problem>;
93 using Scalar = GetPropType<TypeTag, Properties::Scalar>;
94 using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>;
96 using Simulator = SimulatorFullyImplicit<TypeTag>;
98 FlowMain(
int argc,
char **argv,
bool output_cout,
bool output_files )
99 : argc_{argc}, argv_{argv},
100 output_cout_{output_cout}, output_files_{output_files}
119 Parameters::Register<Parameters::OutputInterval>
120 (
"Specify the number of report steps between two consecutive writes of restart data");
121 Parameters::Register<Parameters::EnableLoggingFalloutWarning>
122 (
"Developer option to see whether logging was on non-root processors. "
123 "In that case it will be appended to the *.DBG or *.PRT files");
124 Parameters::Register<Parameters::DebugVerbosityLevel>
125 (
"Set debug verbosity level globally. Default is 1, increasing values give additional output and 0 disables most messages to the .DBG file");
126 Parameters::Register<Parameters::EndStep>
127 (
"Stop the simulation after this report step. "
128 "A negative value runs to the end of the schedule");
131 registerAllParameters_<TypeTag>(
false);
135 detail::hideUnusedParameters<Scalar>();
136 if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()) {
137 Parameters::Hide<Parameters::VtkWriteTortuosities>();
138 Parameters::Hide<Parameters::VtkWriteDiffusionCoefficients>();
139 Parameters::Hide<Parameters::VtkWriteEffectiveDiffusionCoefficients>();
144 int mpiRank = comm.rank();
147 int status = ::Opm::setupParameters_<TypeTag>(argc,
148 const_cast<const char**
>(argv),
157 int unknownKeyWords = 0;
161 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
162 unknownKeyWords = globalUnknownKeyWords;
163 if ( unknownKeyWords )
167 std::string msg =
"Aborting simulation due to unknown "
168 "parameters. Please query \"flow --help\" for "
169 "supported command line parameters.";
170 if (OpmLog::hasBackend(
"STREAMLOG"))
175 std::cerr << msg << std::endl;
182 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
201 return execute_(&FlowMain::runSimulator,
true);
204 int executeInitStep()
206 return execute_(&FlowMain::runSimulatorInit,
false);
213 return simulator_->runStep(*simtimer_);
218 int executeStepsCleanup()
220 SimulatorReport report = simulator_->finalize();
221 runSimulatorAfterSim_(report);
222 return report.success.exit_status;
225 ModelSimulator* getSimulatorPtr()
227 return modelSimulator_.get();
230 SimulatorTimer* getSimTimer()
232 return simtimer_.get();
239 Simulator* getStepDriverPtr()
241 return simulator_.get();
245 double getPreviousReportStepSize()
247 return simtimer_->stepLengthTaken();
252 int execute_(
int (FlowMain::* runOrInitFunc)(),
bool cleanup)
254 auto logger = [
this](
const std::exception& e,
const std::string& message_start) {
255 std::ostringstream message;
256 message << message_start << e.what();
258 if (this->output_cout_) {
261 if (OpmLog::hasBackend(
"STREAMLOG")) {
262 OpmLog::error(message.str());
265 std::cout << message.str() <<
"\n";
275 Dune::Timer setupTimerAfterReadingDeck;
276 setupTimerAfterReadingDeck.start();
284 setupModelSimulator();
287 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
288 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
291 int exitCode = (this->*runOrInitFunc)();
297 catch (
const TimeSteppingBreakdown& e) {
298 auto exitCode = logger(e,
"Simulation aborted: ");
302 catch (
const std::exception& e) {
303 auto exitCode = logger(e,
"Simulation aborted as program threw an unexpected exception: ");
309 void executeCleanup_() {
315 void setupParallelism()
321 mpi_rank_ = comm.rank();
322 mpi_size_ = comm.size();
327 static void setMaxThreads()
334 constexpr int default_threads = 2;
335 const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
336 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
337 int threads = requested_threads > 0 ? requested_threads : default_threads;
339 const char* env_var = getenv(
"OMP_NUM_THREADS");
341 int omp_num_threads = -1;
342 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
343 if (result.ec == std::errc() && omp_num_threads > 0) {
345 threads = omp_num_threads;
347 OpmLog::warning(
"Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
350 OpmLog::warning(
"Invalid value for OMP_NUM_THREADS environment variable.");
356 if (env_var || !(isSet && requested_threads == -1)) {
357 omp_set_num_threads(threads);
361 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
368 OpmLog::removeAllBackends();
370 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
375 Parameters::Get<Parameters::EclDeckFileName>(),
376 detail::allRanksDebugLoggingEnabled());
379 void setupModelSimulator()
382 modelSimulator_->executionTimer().start();
383 modelSimulator_->model().applyInitialSolution();
386 const EclipseState& eclState()
const
387 {
return modelSimulator_->vanguard().eclState(); }
389 EclipseState& eclState()
390 {
return modelSimulator_->vanguard().eclState(); }
392 const Schedule& schedule()
const
393 {
return modelSimulator_->vanguard().schedule(); }
398 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
401 int runSimulatorInit()
403 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
408 int runSimulatorRunCallback_()
410#ifdef RESERVOIR_COUPLING_ENABLED
411 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
413 SimulatorReport report = simulator_->run(*simtimer_);
415 runSimulatorAfterSim_(report);
416 return report.success.exit_status;
420 int runSimulatorInitCallback_()
422#ifdef RESERVOIR_COUPLING_ENABLED
423 simulator_->init(*simtimer_, this->argc_, this->argv_);
425 simulator_->init(*simtimer_);
431 void runSimulatorAfterSim_(SimulatorReport &report)
433 if (simulator_->model().hasNlddSolver()) {
434 const auto& odir = eclState().getIOConfig().getOutputDir();
436 simulator_->model().writeNonlinearIterationsPerCell(odir);
439 simulator_->model().localAccumulatedReports(),
444 if (! this->output_cout_) {
449#if !defined(_OPENMP) || !_OPENMP
452 = omp_get_max_threads();
455 const auto extraConvOutput = ConvergenceOutputConfiguration {
456 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
457 R
"(OutputExtraConvergenceInfo (--output-extra-convergence-info))"
460 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
461 simulator_->model().simulator().problem().extraTrailerSummary(),
465 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
466 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
467 eclState().getIOConfig().getOutputDir(),
468 eclState().getIOConfig().getBaseName());
472 int runSimulatorInitOrRun_(
int (FlowMain::* initOrRunFunc)())
475 const auto& schedule = this->schedule();
476 auto& ioConfig = eclState().getIOConfig();
477 simtimer_ = std::make_unique<SimulatorTimer>();
480 const auto& initConfig = eclState().getInitConfig();
481 simtimer_->init(schedule,
482 static_cast<std::size_t
>(initConfig.getRestartStep()),
483 Parameters::Get<Parameters::EndStep>());
485 if (this->output_cout_) {
486 std::ostringstream oss;
491 std::cout <<
"----------------- Unrecognized parameters: -----------------\n";
492 std::cout << oss.str();
493 std::cout <<
"----------------------------------------------------------------" << std::endl;
497 if (!ioConfig.initOnly()) {
498 if (this->output_cout_) {
500 msg =
"\n\n================ Starting main simulation loop ===============\n";
504 return (this->*initOrRunFunc)();
507 if (this->output_cout_) {
508 std::cout <<
"\n\n================ Simulation turned off ===============\n" << std::flush;
520 void createSimulator()
523 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
527 {
return modelSimulator_->vanguard().grid(); }
530 std::unique_ptr<ModelSimulator> modelSimulator_;
533 std::any parallel_information_;
534 std::unique_ptr<Simulator> simulator_;
535 std::unique_ptr<SimulatorTimer> simtimer_;
540 double total_setup_time_ = 0.0;
541 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:218
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, const bool performance_details=false)
void reportNlddStatistics(const std::vector< SimulatorReport > &domain_reports, const SimulatorReport &local_report, const bool output_cout, const Parallel::Communication &comm)
Declares the parameters for the compositional multi-phase model based on flash calculations.
Provides convenience routines to bring up the simulation at runtime.