FlowMain.hpp
Go to the documentation of this file.
1/*
2 Copyright 2013, 2014, 2015 SINTEF ICT, Applied Mathematics.
3 Copyright 2014 Dr. Blatt - HPC-Simulation-Software & Services
4 Copyright 2015 IRIS AS
5 Copyright 2014 STATOIL ASA.
6
7 This file is part of the Open Porous Media project (OPM).
8
9 OPM is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 OPM is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with OPM. If not, see <http://www.gnu.org/licenses/>.
21*/
22#ifndef OPM_FLOW_MAIN_HEADER_INCLUDED
23#define OPM_FLOW_MAIN_HEADER_INCLUDED
24
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>
28
30
36
37#if HAVE_DUNE_FEM
38#include <dune/fem/misc/mpimanager.hh>
39#else
40#include <dune/common/parallel/mpihelper.hh>
41#endif
42
43#ifdef _OPENMP
44#include <omp.h>
45#endif
46
47#include <charconv>
48#include <cstddef>
49#include <memory>
50
51namespace Opm::Parameters {
52
53// Do not merge parallel output files or warn about them
54struct EnableLoggingFalloutWarning { static constexpr bool value = false; };
55struct OutputInterval { static constexpr int value = 1; };
56// Stop after this report step; negative means run to the end of the schedule
57struct EndStep { static constexpr int value = -1; };
58// Set global debug verbosity level
59struct DebugVerbosityLevel { static constexpr int value = 1; };
60} // namespace Opm::Parameters
61
62namespace Opm {
63
64 class Deck;
65
66 // The FlowMain class is the standard fully implicit flow simulator.
67 template <class TypeTag>
68 class FlowMain
69 {
70 public:
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>;
78
79 using Simulator = SimulatorFullyImplicit<TypeTag>;
80
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}
84 {
85
86 }
87
88 // Read the command line parameters. Throws an exception if something goes wrong.
89 static int setupParameters_(int argc, char** argv, Parallel::Communication comm)
90 {
92 // We have already successfully run setupParameters_().
93 // For the dynamically chosen runs (as from the main flow
94 // executable) we must run this function again with the
95 // real typetag to be used, as the first time was with the
96 // "FlowEarlyBird" typetag. However, for the static ones (such
97 // as 'flow_onephase_energy') it has already been run with the
98 // correct typetag.
99 return EXIT_SUCCESS;
100 }
101 // register the flow specific parameters
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");
112
113 // register the base parameters
114 registerAllParameters_<TypeTag>(/*finalizeRegistration=*/false);
115
117
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>();
123 }
124
126
127 int mpiRank = comm.rank();
128
129 // read in the command line parameters
130 int status = ::Opm::setupParameters_<TypeTag>(argc,
131 const_cast<const char**>(argv),
132 /*doRegistration=*/false,
133 /*allowUnused=*/true,
134 /*handleHelp=*/(mpiRank==0),
135 mpiRank);
136 if (status == 0) {
137
138 // deal with unknown parameters.
139
140 int unknownKeyWords = 0;
141 if (mpiRank == 0) {
142 unknownKeyWords = Parameters::printUnused(std::cerr);
143 }
144 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
145 unknownKeyWords = globalUnknownKeyWords;
146 if ( unknownKeyWords )
147 {
148 if ( mpiRank == 0 )
149 {
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"))
154 {
155 OpmLog::error(msg);
156 }
157 else {
158 std::cerr << msg << std::endl;
159 }
160 }
161 return EXIT_FAILURE;
162 }
163
164 // deal with --print-parameters and unknown parameters.
165 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
166 if (mpiRank == 0) {
167 Parameters::printValues(std::cout);
168 }
169 return -1;
170 }
171 }
172
173 // set the maximum limit on OMP threads
174 setMaxThreads();
175
176 return status;
177 }
178
182 int execute()
183 {
184 return execute_(&FlowMain::runSimulator, /*cleanup=*/true);
185 }
186
187 int executeInitStep()
188 {
189 return execute_(&FlowMain::runSimulatorInit, /*cleanup=*/false);
190 }
191
192 // Returns true unless "EXIT" was encountered in the schedule
193 // section of the input datafile.
194 int executeStep()
195 {
196 return simulator_->runStep(*simtimer_);
197 }
198
199 // Called from Python to cleanup after having executed the last
200 // executeStep()
201 int executeStepsCleanup()
202 {
203 SimulatorReport report = simulator_->finalize();
204 runSimulatorAfterSim_(report);
205 return report.success.exit_status;
206 }
207
208 ModelSimulator* getSimulatorPtr()
209 {
210 return modelSimulator_.get();
211 }
212
213 SimulatorTimer* getSimTimer()
214 {
215 return simtimer_.get();
216 }
217
222 Simulator* getStepDriverPtr()
223 {
224 return simulator_.get();
225 }
226
228 double getPreviousReportStepSize()
229 {
230 return simtimer_->stepLengthTaken();
231 }
232
233 private:
234 // called by execute() or executeInitStep()
235 int execute_(int (FlowMain::* runOrInitFunc)(), bool cleanup)
236 {
237 auto logger = [this](const std::exception& e, const std::string& message_start) {
238 std::ostringstream message;
239 message << message_start << e.what();
240
241 if (this->output_cout_) {
242 // in some cases exceptions are thrown before the logging system is set
243 // up.
244 if (OpmLog::hasBackend("STREAMLOG")) {
245 OpmLog::error(message.str());
246 }
247 else {
248 std::cout << message.str() << "\n";
249 }
250 }
252 return EXIT_FAILURE;
253 };
254
255 try {
256 // deal with some administrative boilerplate
257
258 Dune::Timer setupTimerAfterReadingDeck;
259 setupTimerAfterReadingDeck.start();
260
261 int status = setupParameters_(this->argc_, this->argv_, FlowGenericVanguard::comm());
262 if (status) {
263 return status;
264 }
265
266 setupParallelism();
267 setupModelSimulator();
268 createSimulator();
269
270 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
271 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
272
273 // if run, do the actual work, else just initialize
274 int exitCode = (this->*runOrInitFunc)();
275 if (cleanup) {
276 executeCleanup_();
277 }
278 return exitCode;
279 }
280 catch (const TimeSteppingBreakdown& e) {
281 auto exitCode = logger(e, "Simulation aborted: ");
282 executeCleanup_();
283 return exitCode;
284 }
285 catch (const std::exception& e) {
286 auto exitCode = logger(e, "Simulation aborted as program threw an unexpected exception: ");
287 executeCleanup_();
288 return exitCode;
289 }
290 }
291
292 void executeCleanup_() {
293 // clean up
295 }
296
297 protected:
298 void setupParallelism()
299 {
300 // determine the rank of the current process and the number of processes
301 // involved in the simulation. MPI must have already been initialized
302 // here. (yes, the name of this method is misleading.)
303 auto comm = FlowGenericVanguard::comm();
304 mpi_rank_ = comm.rank();
305 mpi_size_ = comm.size();
306
307 setMaxThreads();
308 }
309
310 static void setMaxThreads()
311 {
312#if _OPENMP
313 // If openMP is available, default to 2 threads per process unless
314 // OMP_NUM_THREADS is set or command line --threads-per-process used.
315 // Issue a warning if both OMP_NUM_THREADS and --threads-per-process are set,
316 // but let the environment variable take precedence.
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;
321
322 const char* env_var = getenv("OMP_NUM_THREADS");
323 if (env_var) {
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) {
327 // Set threads to omp_num_threads if it was successfully parsed and is positive
328 threads = omp_num_threads;
329 if (isSet) {
330 OpmLog::warning("Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
331 }
332 } else {
333 OpmLog::warning("Invalid value for OMP_NUM_THREADS environment variable.");
334 }
335 }
336
337 // Requesting -1 thread will let OMP automatically deduce the number
338 // but setting OMP_NUM_THREADS takes precedence.
339 if (env_var || !(isSet && requested_threads == -1)) {
340 omp_set_num_threads(threads);
341 }
342#endif
343
344 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
345 TM::init(false);
346 }
347
349 {
350 // force closing of all log files.
351 OpmLog::removeAllBackends();
352
353 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
354 return;
355 }
356
357 detail::mergeParallelLogFiles(eclState().getIOConfig().getOutputDir(),
358 Parameters::Get<Parameters::EclDeckFileName>(),
359 Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
360 }
361
362 void setupModelSimulator()
363 {
364 modelSimulator_ = std::make_unique<ModelSimulator>(FlowGenericVanguard::comm(), /*verbose=*/false);
365 modelSimulator_->executionTimer().start();
366 modelSimulator_->model().applyInitialSolution();
367 }
368
369 const EclipseState& eclState() const
370 { return modelSimulator_->vanguard().eclState(); }
371
372 EclipseState& eclState()
373 { return modelSimulator_->vanguard().eclState(); }
374
375 const Schedule& schedule() const
376 { return modelSimulator_->vanguard().schedule(); }
377
378 // Run the simulator.
379 int runSimulator()
380 {
381 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
382 }
383
384 int runSimulatorInit()
385 {
386 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
387 }
388
389 private:
390 // Callback that will be called from runSimulatorInitOrRun_().
391 int runSimulatorRunCallback_()
392 {
393#ifdef RESERVOIR_COUPLING_ENABLED
394 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
395#else
396 SimulatorReport report = simulator_->run(*simtimer_);
397#endif
398 runSimulatorAfterSim_(report);
399 return report.success.exit_status;
400 }
401
402 // Callback that will be called from runSimulatorInitOrRun_().
403 int runSimulatorInitCallback_()
404 {
405#ifdef RESERVOIR_COUPLING_ENABLED
406 simulator_->init(*simtimer_, this->argc_, this->argv_);
407#else
408 simulator_->init(*simtimer_);
409#endif
410 return EXIT_SUCCESS;
411 }
412
413 // Output summary after simulation has completed
414 void runSimulatorAfterSim_(SimulatorReport &report)
415 {
416 if (simulator_->model().hasNlddSolver()) {
417 const auto& odir = eclState().getIOConfig().getOutputDir();
418 // Write the number of nonlinear iterations per cell to a file in ResInsight compatible format
419 simulator_->model().writeNonlinearIterationsPerCell(odir);
420 // Write the NLDD statistics to the DBG file
421 reportNlddStatistics(simulator_->model().domainAccumulatedReports(),
422 simulator_->model().localAccumulatedReports(),
423 this->output_cout_,
425 }
426
427 if (! this->output_cout_) {
428 return;
429 }
430
431 const int threads
432#if !defined(_OPENMP) || !_OPENMP
433 = 1;
434#else
435 = omp_get_max_threads();
436#endif
437
438 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
439 simulator_->model().simulator().problem().extraTrailerSummary());
440
442 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
443 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
444 eclState().getIOConfig().getOutputDir(),
445 eclState().getIOConfig().getBaseName());
446 }
447
448 // Run the simulator.
449 int runSimulatorInitOrRun_(int (FlowMain::* initOrRunFunc)())
450 {
451
452 const auto& schedule = this->schedule();
453 auto& ioConfig = eclState().getIOConfig();
454 simtimer_ = std::make_unique<SimulatorTimer>();
455
456 // initialize variables
457 const auto& initConfig = eclState().getInitConfig();
458 simtimer_->init(schedule,
459 static_cast<std::size_t>(initConfig.getRestartStep()),
460 Parameters::Get<Parameters::EndStep>());
461
462 if (this->output_cout_) {
463 std::ostringstream oss;
464
465 // This allows a user to catch typos and misunderstandings in the
466 // use of simulator parameters.
467 if (Parameters::printUnused(oss)) {
468 std::cout << "----------------- Unrecognized parameters: -----------------\n";
469 std::cout << oss.str();
470 std::cout << "----------------------------------------------------------------" << std::endl;
471 }
472 }
473
474 if (!ioConfig.initOnly()) {
475 if (this->output_cout_) {
476 std::string msg;
477 msg = "\n\n================ Starting main simulation loop ===============\n";
478 OpmLog::info(msg);
479 }
480
481 return (this->*initOrRunFunc)();
482 }
483 else {
484 if (this->output_cout_) {
485 std::cout << "\n\n================ Simulation turned off ===============\n" << std::flush;
486 }
487 return EXIT_SUCCESS;
488 }
489 }
490
491 protected:
492
494 // Create simulator instance.
495 // Writes to:
496 // simulator_
497 void createSimulator()
498 {
499 // Create the simulator instance.
500 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
501 }
502
503 Grid& grid()
504 { return modelSimulator_->vanguard().grid(); }
505
506 private:
507 std::unique_ptr<ModelSimulator> modelSimulator_;
508 int mpi_rank_ = 0;
509 int mpi_size_ = 1;
510 std::any parallel_information_;
511 std::unique_ptr<Simulator> simulator_;
512 std::unique_ptr<SimulatorTimer> simtimer_;
513 int argc_;
514 char **argv_;
515 bool output_cout_;
516 bool output_files_;
517 double total_setup_time_ = 0.0;
518 double deck_read_time_ = 0.0;
519 };
520
521} // namespace Opm
522
523#endif // OPM_FLOW_MAIN_HEADER_INCLUDED
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.