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
31
38
39#if HAVE_DUNE_FEM
40#include <dune/fem/misc/mpimanager.hh>
41#else
42#include <dune/common/parallel/mpihelper.hh>
43#endif
44
45#ifdef _OPENMP
46#include <omp.h>
47#endif
48
49#include <charconv>
50#include <cstddef>
51#include <memory>
52
53namespace Opm::Parameters {
54
55// Do not merge parallel output files or warn about them
56struct EnableLoggingFalloutWarning { static constexpr bool value = false; };
57struct OutputInterval { static constexpr int value = 1; };
58// Stop after this report step; negative means run to the end of the schedule
59struct EndStep { static constexpr int value = -1; };
60// Set global debug verbosity level
61struct DebugVerbosityLevel { static constexpr int value = 1; };
62} // namespace Opm::Parameters
63
64namespace Opm {
65
66 class Deck;
67
68 namespace detail
69 {
70
71 inline bool allRanksDebugLoggingEnabled()
72 {
73 // FlashVerbosity is only registered by compositional models, so neither
74 // query may insist on prior registration: IsSet() only looks for a
75 // user-supplied value, and Get() must read it without the registry.
76 return Parameters::Get<Parameters::EnableLoggingFalloutWarning>()
77 || (Parameters::IsSet<Parameters::FlashVerbosity>(false)
78 && (Parameters::Get<Parameters::FlashVerbosity>(false) > 0));
79 }
80
81 } // namespace detail
82
83 // The FlowMain class is the standard fully implicit flow simulator.
84 template <class TypeTag>
85 class FlowMain
86 {
87 public:
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>;
95
96 using Simulator = SimulatorFullyImplicit<TypeTag>;
97
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}
101 {
102
103 }
104
105 // Read the command line parameters. Throws an exception if something goes wrong.
106 static int setupParameters_(int argc, char** argv, Parallel::Communication comm)
107 {
109 // We have already successfully run setupParameters_().
110 // For the dynamically chosen runs (as from the main flow
111 // executable) we must run this function again with the
112 // real typetag to be used, as the first time was with the
113 // "FlowEarlyBird" typetag. However, for the static ones (such
114 // as 'flow_onephase_energy') it has already been run with the
115 // correct typetag.
116 return EXIT_SUCCESS;
117 }
118 // register the flow specific parameters
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");
129
130 // register the base parameters
131 registerAllParameters_<TypeTag>(/*finalizeRegistration=*/false);
132
134
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>();
140 }
141
143
144 int mpiRank = comm.rank();
145
146 // read in the command line parameters
147 int status = ::Opm::setupParameters_<TypeTag>(argc,
148 const_cast<const char**>(argv),
149 /*doRegistration=*/false,
150 /*allowUnused=*/true,
151 /*handleHelp=*/(mpiRank==0),
152 mpiRank);
153 if (status == 0) {
154
155 // deal with unknown parameters.
156
157 int unknownKeyWords = 0;
158 if (mpiRank == 0) {
159 unknownKeyWords = Parameters::printUnused(std::cerr);
160 }
161 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
162 unknownKeyWords = globalUnknownKeyWords;
163 if ( unknownKeyWords )
164 {
165 if ( mpiRank == 0 )
166 {
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"))
171 {
172 OpmLog::error(msg);
173 }
174 else {
175 std::cerr << msg << std::endl;
176 }
177 }
178 return EXIT_FAILURE;
179 }
180
181 // deal with --print-parameters and unknown parameters.
182 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
183 if (mpiRank == 0) {
184 Parameters::printValues(std::cout);
185 }
186 return -1;
187 }
188 }
189
190 // set the maximum limit on OMP threads
191 setMaxThreads();
192
193 return status;
194 }
195
199 int execute()
200 {
201 return execute_(&FlowMain::runSimulator, /*cleanup=*/true);
202 }
203
204 int executeInitStep()
205 {
206 return execute_(&FlowMain::runSimulatorInit, /*cleanup=*/false);
207 }
208
209 // Returns true unless "EXIT" was encountered in the schedule
210 // section of the input datafile.
211 int executeStep()
212 {
213 return simulator_->runStep(*simtimer_);
214 }
215
216 // Called from Python to cleanup after having executed the last
217 // executeStep()
218 int executeStepsCleanup()
219 {
220 SimulatorReport report = simulator_->finalize();
221 runSimulatorAfterSim_(report);
222 return report.success.exit_status;
223 }
224
225 ModelSimulator* getSimulatorPtr()
226 {
227 return modelSimulator_.get();
228 }
229
230 SimulatorTimer* getSimTimer()
231 {
232 return simtimer_.get();
233 }
234
239 Simulator* getStepDriverPtr()
240 {
241 return simulator_.get();
242 }
243
245 double getPreviousReportStepSize()
246 {
247 return simtimer_->stepLengthTaken();
248 }
249
250 private:
251 // called by execute() or executeInitStep()
252 int execute_(int (FlowMain::* runOrInitFunc)(), bool cleanup)
253 {
254 auto logger = [this](const std::exception& e, const std::string& message_start) {
255 std::ostringstream message;
256 message << message_start << e.what();
257
258 if (this->output_cout_) {
259 // in some cases exceptions are thrown before the logging system is set
260 // up.
261 if (OpmLog::hasBackend("STREAMLOG")) {
262 OpmLog::error(message.str());
263 }
264 else {
265 std::cout << message.str() << "\n";
266 }
267 }
269 return EXIT_FAILURE;
270 };
271
272 try {
273 // deal with some administrative boilerplate
274
275 Dune::Timer setupTimerAfterReadingDeck;
276 setupTimerAfterReadingDeck.start();
277
278 int status = setupParameters_(this->argc_, this->argv_, FlowGenericVanguard::comm());
279 if (status) {
280 return status;
281 }
282
283 setupParallelism();
284 setupModelSimulator();
285 createSimulator();
286
287 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
288 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
289
290 // if run, do the actual work, else just initialize
291 int exitCode = (this->*runOrInitFunc)();
292 if (cleanup) {
293 executeCleanup_();
294 }
295 return exitCode;
296 }
297 catch (const TimeSteppingBreakdown& e) {
298 auto exitCode = logger(e, "Simulation aborted: ");
299 executeCleanup_();
300 return exitCode;
301 }
302 catch (const std::exception& e) {
303 auto exitCode = logger(e, "Simulation aborted as program threw an unexpected exception: ");
304 executeCleanup_();
305 return exitCode;
306 }
307 }
308
309 void executeCleanup_() {
310 // clean up
312 }
313
314 protected:
315 void setupParallelism()
316 {
317 // determine the rank of the current process and the number of processes
318 // involved in the simulation. MPI must have already been initialized
319 // here. (yes, the name of this method is misleading.)
320 auto comm = FlowGenericVanguard::comm();
321 mpi_rank_ = comm.rank();
322 mpi_size_ = comm.size();
323
324 setMaxThreads();
325 }
326
327 static void setMaxThreads()
328 {
329#if _OPENMP
330 // If openMP is available, default to 2 threads per process unless
331 // OMP_NUM_THREADS is set or command line --threads-per-process used.
332 // Issue a warning if both OMP_NUM_THREADS and --threads-per-process are set,
333 // but let the environment variable take precedence.
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;
338
339 const char* env_var = getenv("OMP_NUM_THREADS");
340 if (env_var) {
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) {
344 // Set threads to omp_num_threads if it was successfully parsed and is positive
345 threads = omp_num_threads;
346 if (isSet) {
347 OpmLog::warning("Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
348 }
349 } else {
350 OpmLog::warning("Invalid value for OMP_NUM_THREADS environment variable.");
351 }
352 }
353
354 // Requesting -1 thread will let OMP automatically deduce the number
355 // but setting OMP_NUM_THREADS takes precedence.
356 if (env_var || !(isSet && requested_threads == -1)) {
357 omp_set_num_threads(threads);
358 }
359#endif
360
361 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
362 TM::init(false);
363 }
364
366 {
367 // force closing of all log files.
368 OpmLog::removeAllBackends();
369
370 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
371 return;
372 }
373
374 detail::mergeParallelLogFiles(eclState().getIOConfig().getOutputDir(),
375 Parameters::Get<Parameters::EclDeckFileName>(),
376 detail::allRanksDebugLoggingEnabled());
377 }
378
379 void setupModelSimulator()
380 {
381 modelSimulator_ = std::make_unique<ModelSimulator>(FlowGenericVanguard::comm(), /*verbose=*/false);
382 modelSimulator_->executionTimer().start();
383 modelSimulator_->model().applyInitialSolution();
384 }
385
386 const EclipseState& eclState() const
387 { return modelSimulator_->vanguard().eclState(); }
388
389 EclipseState& eclState()
390 { return modelSimulator_->vanguard().eclState(); }
391
392 const Schedule& schedule() const
393 { return modelSimulator_->vanguard().schedule(); }
394
395 // Run the simulator.
396 int runSimulator()
397 {
398 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
399 }
400
401 int runSimulatorInit()
402 {
403 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
404 }
405
406 private:
407 // Callback that will be called from runSimulatorInitOrRun_().
408 int runSimulatorRunCallback_()
409 {
410#ifdef RESERVOIR_COUPLING_ENABLED
411 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
412#else
413 SimulatorReport report = simulator_->run(*simtimer_);
414#endif
415 runSimulatorAfterSim_(report);
416 return report.success.exit_status;
417 }
418
419 // Callback that will be called from runSimulatorInitOrRun_().
420 int runSimulatorInitCallback_()
421 {
422#ifdef RESERVOIR_COUPLING_ENABLED
423 simulator_->init(*simtimer_, this->argc_, this->argv_);
424#else
425 simulator_->init(*simtimer_);
426#endif
427 return EXIT_SUCCESS;
428 }
429
430 // Output summary after simulation has completed
431 void runSimulatorAfterSim_(SimulatorReport &report)
432 {
433 if (simulator_->model().hasNlddSolver()) {
434 const auto& odir = eclState().getIOConfig().getOutputDir();
435 // Write the number of nonlinear iterations per cell to a file in ResInsight compatible format
436 simulator_->model().writeNonlinearIterationsPerCell(odir);
437 // Write the NLDD statistics to the DBG file
438 reportNlddStatistics(simulator_->model().domainAccumulatedReports(),
439 simulator_->model().localAccumulatedReports(),
440 this->output_cout_,
442 }
443
444 if (! this->output_cout_) {
445 return;
446 }
447
448 const int threads
449#if !defined(_OPENMP) || !_OPENMP
450 = 1;
451#else
452 = omp_get_max_threads();
453#endif
454
455 const auto extraConvOutput = ConvergenceOutputConfiguration {
456 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
457 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))"
458 };
459
460 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
461 simulator_->model().simulator().problem().extraTrailerSummary(),
463
465 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
466 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
467 eclState().getIOConfig().getOutputDir(),
468 eclState().getIOConfig().getBaseName());
469 }
470
471 // Run the simulator.
472 int runSimulatorInitOrRun_(int (FlowMain::* initOrRunFunc)())
473 {
474
475 const auto& schedule = this->schedule();
476 auto& ioConfig = eclState().getIOConfig();
477 simtimer_ = std::make_unique<SimulatorTimer>();
478
479 // initialize variables
480 const auto& initConfig = eclState().getInitConfig();
481 simtimer_->init(schedule,
482 static_cast<std::size_t>(initConfig.getRestartStep()),
483 Parameters::Get<Parameters::EndStep>());
484
485 if (this->output_cout_) {
486 std::ostringstream oss;
487
488 // This allows a user to catch typos and misunderstandings in the
489 // use of simulator parameters.
490 if (Parameters::printUnused(oss)) {
491 std::cout << "----------------- Unrecognized parameters: -----------------\n";
492 std::cout << oss.str();
493 std::cout << "----------------------------------------------------------------" << std::endl;
494 }
495 }
496
497 if (!ioConfig.initOnly()) {
498 if (this->output_cout_) {
499 std::string msg;
500 msg = "\n\n================ Starting main simulation loop ===============\n";
501 OpmLog::info(msg);
502 }
503
504 return (this->*initOrRunFunc)();
505 }
506 else {
507 if (this->output_cout_) {
508 std::cout << "\n\n================ Simulation turned off ===============\n" << std::flush;
509 }
510 return EXIT_SUCCESS;
511 }
512 }
513
514 protected:
515
517 // Create simulator instance.
518 // Writes to:
519 // simulator_
520 void createSimulator()
521 {
522 // Create the simulator instance.
523 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
524 }
525
526 Grid& grid()
527 { return modelSimulator_->vanguard().grid(); }
528
529 private:
530 std::unique_ptr<ModelSimulator> modelSimulator_;
531 int mpi_rank_ = 0;
532 int mpi_size_ = 1;
533 std::any parallel_information_;
534 std::unique_ptr<Simulator> simulator_;
535 std::unique_ptr<SimulatorTimer> simtimer_;
536 int argc_;
537 char **argv_;
538 bool output_cout_;
539 bool output_files_;
540 double total_setup_time_ = 0.0;
541 double deck_read_time_ = 0.0;
542 };
543
544} // namespace Opm
545
546#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: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.