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()
337 constexpr int default_threads = 2;
338 const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
339 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
340 int threads = requested_threads > 0 ? requested_threads : default_threads;
342 if (requested_threads > -1)
343 omp_set_num_threads(threads);
345 const char* env_var = getenv(
"OMP_NUM_THREADS");
347 int omp_num_threads = -1;
348 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
349 if (result.ec == std::errc() && omp_num_threads > 0) {
352 warn =
"Requested threads via --threads-per-process commandline argument";
354 warn =
"Will use default value 2 for --threads-per-process commandline argument, but it";
357 if (requested_threads != -1 && threads > omp_num_threads) {
358 OpmLog::warning(fmt::format(
"{} is larger than the value of "
359 "environment variable OMP_NUM_THREADS. Using it anyway.", warn));
362 OpmLog::warning(
"Invalid value for OMP_NUM_THREADS environment variable.");
368 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
375 OpmLog::removeAllBackends();
377 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
382 Parameters::Get<Parameters::EclDeckFileName>(),
383 detail::allRanksDebugLoggingEnabled());
386 void setupModelSimulator()
389 modelSimulator_->executionTimer().start();
390 modelSimulator_->model().applyInitialSolution();
393 const EclipseState& eclState()
const
394 {
return modelSimulator_->vanguard().eclState(); }
396 EclipseState& eclState()
397 {
return modelSimulator_->vanguard().eclState(); }
399 const Schedule& schedule()
const
400 {
return modelSimulator_->vanguard().schedule(); }
405 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
408 int runSimulatorInit()
410 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
415 int runSimulatorRunCallback_()
417#ifdef RESERVOIR_COUPLING_ENABLED
418 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
420 SimulatorReport report = simulator_->run(*simtimer_);
422 runSimulatorAfterSim_(report);
423 return report.success.exit_status;
427 int runSimulatorInitCallback_()
429#ifdef RESERVOIR_COUPLING_ENABLED
430 simulator_->init(*simtimer_, this->argc_, this->argv_);
432 simulator_->init(*simtimer_);
438 void runSimulatorAfterSim_(SimulatorReport &report)
440 if (simulator_->model().hasNlddSolver()) {
441 const auto& odir = eclState().getIOConfig().getOutputDir();
443 simulator_->model().writeNonlinearIterationsPerCell(odir);
446 simulator_->model().localAccumulatedReports(),
451 if (! this->output_cout_) {
456#if !defined(_OPENMP) || !_OPENMP
459 = omp_get_max_threads();
462 const auto extraConvOutput = ConvergenceOutputConfiguration {
463 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
464 R
"(OutputExtraConvergenceInfo (--output-extra-convergence-info))"
467 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
468 simulator_->model().simulator().problem().extraTrailerSummary(),
472 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
473 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
474 eclState().getIOConfig().getOutputDir(),
475 eclState().getIOConfig().getBaseName());
479 int runSimulatorInitOrRun_(
int (FlowMain::* initOrRunFunc)())
482 const auto& schedule = this->schedule();
483 auto& ioConfig = eclState().getIOConfig();
484 simtimer_ = std::make_unique<SimulatorTimer>();
487 const auto& initConfig = eclState().getInitConfig();
488 simtimer_->init(schedule,
489 static_cast<std::size_t
>(initConfig.getRestartStep()),
490 Parameters::Get<Parameters::EndStep>());
492 if (this->output_cout_) {
493 std::ostringstream oss;
498 std::cout <<
"----------------- Unrecognized parameters: -----------------\n";
499 std::cout << oss.str();
500 std::cout <<
"----------------------------------------------------------------" << std::endl;
504 if (!ioConfig.initOnly()) {
505 if (this->output_cout_) {
507 msg =
"\n\n================ Starting main simulation loop ===============\n";
511 return (this->*initOrRunFunc)();
514 if (this->output_cout_) {
515 std::cout <<
"\n\n================ Simulation turned off ===============\n" << std::flush;
527 void createSimulator()
530 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
534 {
return modelSimulator_->vanguard().grid(); }
537 std::unique_ptr<ModelSimulator> modelSimulator_;
540 std::any parallel_information_;
541 std::unique_ptr<Simulator> simulator_;
542 std::unique_ptr<SimulatorTimer> simtimer_;
547 double total_setup_time_ = 0.0;
548 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.