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
34
35#if HAVE_DUNE_FEM
36#include <dune/fem/misc/mpimanager.hh>
37#else
38#include <dune/common/parallel/mpihelper.hh>
39#endif
40
41#ifdef _OPENMP
42#include <omp.h>
43#endif
44
45#include <charconv>
46#include <cstddef>
47#include <memory>
48
49namespace Opm::Parameters {
50
51// Do not merge parallel output files or warn about them
52struct EnableLoggingFalloutWarning { static constexpr bool value = false; };
53
54struct OutputInterval { static constexpr int value = 1; };
55
56} // namespace Opm::Parameters
57
58namespace Opm {
59
60 class Deck;
61
62 // The FlowMain class is the black-oil simulator.
63 template <class TypeTag>
64 class FlowMain
65 {
66 public:
67 using MaterialLawManager = typename GetProp<TypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
68 using ModelSimulator = GetPropType<TypeTag, Properties::Simulator>;
69 using Grid = GetPropType<TypeTag, Properties::Grid>;
70 using GridView = GetPropType<TypeTag, Properties::GridView>;
71 using Problem = GetPropType<TypeTag, Properties::Problem>;
72 using Scalar = GetPropType<TypeTag, Properties::Scalar>;
73 using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>;
74
75 using Simulator = SimulatorFullyImplicitBlackoil<TypeTag>;
76
77 FlowMain(int argc, char **argv, bool output_cout, bool output_files )
78 : argc_{argc}, argv_{argv},
79 output_cout_{output_cout}, output_files_{output_files}
80 {
81
82 }
83
84 // Read the command line parameters. Throws an exception if something goes wrong.
85 static int setupParameters_(int argc, char** argv, Parallel::Communication comm)
86 {
88 // We have already successfully run setupParameters_().
89 // For the dynamically chosen runs (as from the main flow
90 // executable) we must run this function again with the
91 // real typetag to be used, as the first time was with the
92 // "FlowEarlyBird" typetag. However, for the static ones (such
93 // as 'flow_onephase_energy') it has already been run with the
94 // correct typetag.
95 return EXIT_SUCCESS;
96 }
97 // register the flow specific parameters
98 Parameters::Register<Parameters::OutputInterval>
99 ("Specify the number of report steps between two consecutive writes of restart data");
100 Parameters::Register<Parameters::EnableLoggingFalloutWarning>
101 ("Developer option to see whether logging was on non-root processors. "
102 "In that case it will be appended to the *.DBG or *.PRT files");
103
106
107 // register the base parameters
108 registerAllParameters_<TypeTag>(/*finalizeRegistration=*/false);
109
110 detail::hideUnusedParameters<Scalar>();
111
113
114 int mpiRank = comm.rank();
115
116 // read in the command line parameters
117 int status = ::Opm::setupParameters_<TypeTag>(argc,
118 const_cast<const char**>(argv),
119 /*doRegistration=*/false,
120 /*allowUnused=*/true,
121 /*handleHelp=*/(mpiRank==0));
122 if (status == 0) {
123
124 // deal with unknown parameters.
125
126 int unknownKeyWords = 0;
127 if (mpiRank == 0) {
128 unknownKeyWords = Parameters::printUnused(std::cerr);
129 }
130 int globalUnknownKeyWords = comm.sum(unknownKeyWords);
131 unknownKeyWords = globalUnknownKeyWords;
132 if ( unknownKeyWords )
133 {
134 if ( mpiRank == 0 )
135 {
136 std::string msg = "Aborting simulation due to unknown "
137 "parameters. Please query \"flow --help\" for "
138 "supported command line parameters.";
139 if (OpmLog::hasBackend("STREAMLOG"))
140 {
141 OpmLog::error(msg);
142 }
143 else {
144 std::cerr << msg << std::endl;
145 }
146 }
147 return EXIT_FAILURE;
148 }
149
150 // deal with --print-parameters and unknown parameters.
151 if (Parameters::Get<Parameters::PrintParameters>() == 1) {
152 if (mpiRank == 0) {
153 Parameters::printValues(std::cout);
154 }
155 return -1;
156 }
157 }
158
159 return status;
160 }
161
165 int execute()
166 {
167 return execute_(&FlowMain::runSimulator, /*cleanup=*/true);
168 }
169
170 int executeInitStep()
171 {
172 return execute_(&FlowMain::runSimulatorInit, /*cleanup=*/false);
173 }
174
175 // Returns true unless "EXIT" was encountered in the schedule
176 // section of the input datafile.
177 int executeStep()
178 {
179 return simulator_->runStep(*simtimer_);
180 }
181
182 // Called from Python to cleanup after having executed the last
183 // executeStep()
184 int executeStepsCleanup()
185 {
186 SimulatorReport report = simulator_->finalize();
187 runSimulatorAfterSim_(report);
188 return report.success.exit_status;
189 }
190
191 ModelSimulator* getSimulatorPtr()
192 {
193 return modelSimulator_.get();
194 }
195
196 SimulatorTimer* getSimTimer()
197 {
198 return simtimer_.get();
199 }
200
202 double getPreviousReportStepSize()
203 {
204 return simtimer_->stepLengthTaken();
205 }
206
207 private:
208 // called by execute() or executeInitStep()
209 int execute_(int (FlowMain::* runOrInitFunc)(), bool cleanup)
210 {
211 auto logger = [this](const std::exception& e, const std::string& message_start) {
212 std::ostringstream message;
213 message << message_start << e.what();
214
215 if (this->output_cout_) {
216 // in some cases exceptions are thrown before the logging system is set
217 // up.
218 if (OpmLog::hasBackend("STREAMLOG")) {
219 OpmLog::error(message.str());
220 }
221 else {
222 std::cout << message.str() << "\n";
223 }
224 }
226 return EXIT_FAILURE;
227 };
228
229 try {
230 // deal with some administrative boilerplate
231
232 Dune::Timer setupTimerAfterReadingDeck;
233 setupTimerAfterReadingDeck.start();
234
235 int status = setupParameters_(this->argc_, this->argv_, FlowGenericVanguard::comm());
236 if (status) {
237 return status;
238 }
239
240 setupParallelism();
241 setupModelSimulator();
242 createSimulator();
243
244 this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
245 this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
246
247 // if run, do the actual work, else just initialize
248 int exitCode = (this->*runOrInitFunc)();
249 if (cleanup) {
250 executeCleanup_();
251 }
252 return exitCode;
253 }
254 catch (const TimeSteppingBreakdown& e) {
255 auto exitCode = logger(e, "Simulation aborted: ");
256 executeCleanup_();
257 return exitCode;
258 }
259 catch (const std::exception& e) {
260 auto exitCode = logger(e, "Simulation aborted as program threw an unexpected exception: ");
261 executeCleanup_();
262 return exitCode;
263 }
264 }
265
266 void executeCleanup_() {
267 // clean up
269 }
270
271 protected:
272 void setupParallelism()
273 {
274 // determine the rank of the current process and the number of processes
275 // involved in the simulation. MPI must have already been initialized
276 // here. (yes, the name of this method is misleading.)
277 auto comm = FlowGenericVanguard::comm();
278 mpi_rank_ = comm.rank();
279 mpi_size_ = comm.size();
280
281#if _OPENMP
282 // If openMP is available, default to 2 threads per process unless
283 // OMP_NUM_THREADS is set or command line --threads-per-process used.
284 // Issue a warning if both OMP_NUM_THREADS and --threads-per-process are set,
285 // but let the environment variable take precedence.
286 constexpr int default_threads = 2;
287 const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
288 int threads = requested_threads > 0 ? requested_threads : default_threads;
289
290 const char* env_var = getenv("OMP_NUM_THREADS");
291 if (env_var) {
292 int omp_num_threads = -1;
293 auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
294 if (result.ec == std::errc() && omp_num_threads > 0) {
295 // Set threads to omp_num_threads if it was successfully parsed and is positive
296 threads = omp_num_threads;
297 // Warning in 'Main.hpp', where this code is duplicated
298 // if (requested_threads > 0) {
299 // OpmLog::warning("Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
300 // }
301 } else {
302 OpmLog::warning("Invalid value for OMP_NUM_THREADS environment variable.");
303 }
304 }
305
306 // We are not limiting this to the number of processes
307 // reported by OpenMP as on some hardware (and some OpenMPI
308 // versions) this will be 1 when run with mpirun
309 omp_set_num_threads(threads);
310#endif
311
312 using TM = GetPropType<TypeTag, Properties::ThreadManager>;
313 TM::init(false);
314 }
315
317 {
318 // force closing of all log files.
319 OpmLog::removeAllBackends();
320
321 if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
322 return;
323 }
324
325 detail::mergeParallelLogFiles(eclState().getIOConfig().getOutputDir(),
326 Parameters::Get<Parameters::EclDeckFileName>(),
327 Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
328 }
329
330 void setupModelSimulator()
331 {
332 modelSimulator_ = std::make_unique<ModelSimulator>(FlowGenericVanguard::comm(), /*verbose=*/false);
333 modelSimulator_->executionTimer().start();
334 modelSimulator_->model().applyInitialSolution();
335 }
336
337 const EclipseState& eclState() const
338 { return modelSimulator_->vanguard().eclState(); }
339
340 EclipseState& eclState()
341 { return modelSimulator_->vanguard().eclState(); }
342
343 const Schedule& schedule() const
344 { return modelSimulator_->vanguard().schedule(); }
345
346 // Run the simulator.
347 int runSimulator()
348 {
349 return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
350 }
351
352 int runSimulatorInit()
353 {
354 return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
355 }
356
357 private:
358 // Callback that will be called from runSimulatorInitOrRun_().
359 int runSimulatorRunCallback_()
360 {
361 SimulatorReport report = simulator_->run(*simtimer_);
362 runSimulatorAfterSim_(report);
363 return report.success.exit_status;
364 }
365
366 // Callback that will be called from runSimulatorInitOrRun_().
367 int runSimulatorInitCallback_()
368 {
369 simulator_->init(*simtimer_);
370 return EXIT_SUCCESS;
371 }
372
373 // Output summary after simulation has completed
374 void runSimulatorAfterSim_(SimulatorReport &report)
375 {
376 if (! this->output_cout_) {
377 return;
378 }
379
380 const int threads
381#if !defined(_OPENMP) || !_OPENMP
382 = 1;
383#else
384 = omp_get_max_threads();
385#endif
386
387 printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report, simulator_->model().localAccumulatedReports());
388
390 Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
391 R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
392 eclState().getIOConfig().getOutputDir(),
393 eclState().getIOConfig().getBaseName());
394 }
395
396 // Run the simulator.
397 int runSimulatorInitOrRun_(int (FlowMain::* initOrRunFunc)())
398 {
399
400 const auto& schedule = this->schedule();
401 auto& ioConfig = eclState().getIOConfig();
402 simtimer_ = std::make_unique<SimulatorTimer>();
403
404 // initialize variables
405 const auto& initConfig = eclState().getInitConfig();
406 simtimer_->init(schedule, static_cast<std::size_t>(initConfig.getRestartStep()));
407
408 if (this->output_cout_) {
409 std::ostringstream oss;
410
411 // This allows a user to catch typos and misunderstandings in the
412 // use of simulator parameters.
413 if (Parameters::printUnused(oss)) {
414 std::cout << "----------------- Unrecognized parameters: -----------------\n";
415 std::cout << oss.str();
416 std::cout << "----------------------------------------------------------------" << std::endl;
417 }
418 }
419
420 if (!ioConfig.initOnly()) {
421 if (this->output_cout_) {
422 std::string msg;
423 msg = "\n\n================ Starting main simulation loop ===============\n";
424 OpmLog::info(msg);
425 }
426
427 return (this->*initOrRunFunc)();
428 }
429 else {
430 if (this->output_cout_) {
431 std::cout << "\n\n================ Simulation turned off ===============\n" << std::flush;
432 }
433 return EXIT_SUCCESS;
434 }
435 }
436
437 protected:
438
440 // Create simulator instance.
441 // Writes to:
442 // simulator_
443 void createSimulator()
444 {
445 // Create the simulator instance.
446 simulator_ = std::make_unique<Simulator>(*modelSimulator_);
447 }
448
449 Grid& grid()
450 { return modelSimulator_->vanguard().grid(); }
451
452 private:
453 std::unique_ptr<ModelSimulator> modelSimulator_;
454 int mpi_rank_ = 0;
455 int mpi_size_ = 1;
456 std::any parallel_information_;
457 std::unique_ptr<Simulator> simulator_;
458 std::unique_ptr<SimulatorTimer> simtimer_;
459 int argc_;
460 char **argv_;
461 bool output_cout_;
462 bool output_files_;
463 double total_setup_time_ = 0.0;
464 double deck_read_time_ = 0.0;
465 };
466
467} // namespace Opm
468
469#endif // OPM_FLOW_MAIN_HEADER_INCLUDED
static Parallel::Communication & comm()
Obtain global communicator.
Definition: FlowGenericVanguard.hpp:306
static void registerParameters()
Registers all runtime parameters used by the simulation.
Definition: simulator.hh:240
static void registerParameters()
Register all run-time parameters of the thread manager.
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 mergeParallelLogFiles(std::string_view output_dir, std::string_view deck_filename, bool enableLoggingFalloutWarning)
void checkAllMPIProcesses()
void handleExtraConvergenceOutput(SimulatorReport &report, std::string_view option, std::string_view optionName, std::string_view output_dir, std::string_view base_name)
Definition: blackoilboundaryratevector.hh:37
void printFlowTrailer(int nprocs, int nthreads, const double total_setup_time, const double deck_read_time, const SimulatorReport &report, const SimulatorReportSingle &localsolves_report)
Provides convenience routines to bring up the simulation at runtime.