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, the value of command line --threads-per-process
331 // will determine how many threads will be used. The default number is 2 if
332 // command line argument is not used. To let OpenMP determine how many threads
333 // will be used use value -1 for the command line argument. In this case either
334 // the same number of threads as logical CPUs will be used if the environment
335 // variable OMP_NUM_THREADS is not set. If it is set then that number will be
336 // used.
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;
341
342 if (requested_threads > -1)
343 omp_set_num_threads(threads);
344
345 const char* env_var = getenv("OMP_NUM_THREADS");
346 if (env_var) {
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) {
350 std::string warn;
351 if (isSet) {
352 warn = "Requested threads via --threads-per-process commandline argument";
353 } else {
354 warn = "Will use default value 2 for --threads-per-process commandline argument, but it";
355 }
356
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));
360 }
361 } else {
362 OpmLog::warning("Invalid value for OMP_NUM_THREADS environment variable.");
363 }
364 }
365
366#endif
367
368 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
369 TM::init(false);
370 }
371
373 {
374 // force closing of all log files.
375 OpmLog::removeAllBackends();
376
377 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
378 return;
379 }
380
381 detail::mergeParallelLogFiles(eclState().getIOConfig().getOutputDir(),
382 Parameters::Get<Parameters::EclDeckFileName>(),
383 detail::allRanksDebugLoggingEnabled());
384 }
385
386 void setupModelSimulator()
387 {
388 modelSimulator_ = std::make_unique<ModelSimulator>(FlowGenericVanguard::comm(), /*verbose=*/false);
389 modelSimulator_->executionTimer().start();
390 modelSimulator_->model().applyInitialSolution();
391 }
392
393 const EclipseState& eclState() const
394 { return modelSimulator_->vanguard().eclState(); }
395
396 EclipseState& eclState()
397 { return modelSimulator_->vanguard().eclState(); }
398
399 const Schedule& schedule() const
400 { return modelSimulator_->vanguard().schedule(); }
401
402 // Run the simulator.
403 int runSimulator()
404 {
405 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
406 }
407
408 int runSimulatorInit()
409 {
410 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
411 }
412
413 private:
414 // Callback that will be called from runSimulatorInitOrRun_().
415 int runSimulatorRunCallback_()
416 {
417#ifdef RESERVOIR_COUPLING_ENABLED
418 SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
419#else
420 SimulatorReport report = simulator_->run(*simtimer_);
421#endif
422 runSimulatorAfterSim_(report);
423 return report.success.exit_status;
424 }
425
426 // Callback that will be called from runSimulatorInitOrRun_().
427 int runSimulatorInitCallback_()
428 {
429#ifdef RESERVOIR_COUPLING_ENABLED
430 simulator_->init(*simtimer_, this->argc_, this->argv_);
431#else
432 simulator_->init(*simtimer_);
433#endif
434 return EXIT_SUCCESS;
435 }
436
437 // Output summary after simulation has completed
438 void runSimulatorAfterSim_(SimulatorReport &report)
439 {
440 if (simulator_->model().hasNlddSolver()) {
441 const auto& odir = eclState().getIOConfig().getOutputDir();
442 // Write the number of nonlinear iterations per cell to a file in ResInsight compatible format
443 simulator_->model().writeNonlinearIterationsPerCell(odir);
444 // Write the NLDD statistics to the DBG file
445 reportNlddStatistics(simulator_->model().domainAccumulatedReports(),
446 simulator_->model().localAccumulatedReports(),
447 this->output_cout_,
449 }
450
451 if (! this->output_cout_) {
452 return;
453 }
454
455 const int threads
456#if !defined(_OPENMP) || !_OPENMP
457 = 1;
458#else
459 = omp_get_max_threads();
460#endif
461
462 const auto extraConvOutput = ConvergenceOutputConfiguration {
463 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
464 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))"
465 };
466
467 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report,
468 simulator_->model().simulator().problem().extraTrailerSummary(),
470
472 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
473 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
474 eclState().getIOConfig().getOutputDir(),
475 eclState().getIOConfig().getBaseName());
476 }
477
478 // Run the simulator.
479 int runSimulatorInitOrRun_(int (FlowMain::* initOrRunFunc)())
480 {
481
482 const auto& schedule = this->schedule();
483 auto& ioConfig = eclState().getIOConfig();
484 simtimer_ = std::make_unique<SimulatorTimer>();
485
486 // initialize variables
487 const auto& initConfig = eclState().getInitConfig();
488 simtimer_->init(schedule,
489 static_cast<std::size_t>(initConfig.getRestartStep()),
490 Parameters::Get<Parameters::EndStep>());
491
492 if (this->output_cout_) {
493 std::ostringstream oss;
494
495 // This allows a user to catch typos and misunderstandings in the
496 // use of simulator parameters.
497 if (Parameters::printUnused(oss)) {
498 std::cout << "----------------- Unrecognized parameters: -----------------\n";
499 std::cout << oss.str();
500 std::cout << "----------------------------------------------------------------" << std::endl;
501 }
502 }
503
504 if (!ioConfig.initOnly()) {
505 if (this->output_cout_) {
506 std::string msg;
507 msg = "\n\n================ Starting main simulation loop ===============\n";
508 OpmLog::info(msg);
509 }
510
511 return (this->*initOrRunFunc)();
512 }
513 else {
514 if (this->output_cout_) {
515 std::cout << "\n\n================ Simulation turned off ===============\n" << std::flush;
516 }
517 return EXIT_SUCCESS;
518 }
519 }
520
521 protected:
522
524 // Create simulator instance.
525 // Writes to:
526 // simulator_
527 void createSimulator()
528 {
529 // Create the simulator instance.
530 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
531 }
532
533 Grid& grid()
534 { return modelSimulator_->vanguard().grid(); }
535
536 private:
537 std::unique_ptr<ModelSimulator> modelSimulator_;
538 int mpi_rank_ = 0;
539 int mpi_size_ = 1;
540 std::any parallel_information_;
541 std::unique_ptr<Simulator> simulator_;
542 std::unique_ptr<SimulatorTimer> simtimer_;
543 int argc_;
544 char **argv_;
545 bool output_cout_;
546 bool output_files_;
547 double total_setup_time_ = 0.0;
548 double deck_read_time_ = 0.0;
549 };
550
551} // namespace Opm
552
553#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.