opm-simulators
FlowMain.hpp
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 
31 #include <opm/simulators/flow/Banners.hpp>
32 #include <opm/simulators/flow/FlowUtils.hpp>
33 #include <opm/simulators/flow/NlddReporting.hpp>
34 #include <opm/simulators/flow/SimulatorFullyImplicit.hpp>
35 #include <opm/simulators/flow/rescoup/ReservoirCouplingEnabled.hpp>
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 
51 namespace Opm::Parameters {
52 
53 // Do not merge parallel output files or warn about them
54 struct EnableLoggingFalloutWarning { static constexpr bool value = false; };
55 struct OutputInterval { static constexpr int value = 1; };
56 // Set global debug verbosity level
57 struct DebugVerbosityLevel { static constexpr int value = 1; };
58 } // namespace Opm::Parameters
59 
60 namespace Opm {
61 
62  class Deck;
63 
64  // The FlowMain class is the standard fully implicit flow simulator.
65  template <class TypeTag>
66  class FlowMain
67  {
68  public:
69  using MaterialLawManager = typename GetProp<TypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
70  using ModelSimulator = GetPropType<TypeTag, Properties::Simulator>;
76 
78 
79  FlowMain(int argc, char **argv, bool output_cout, bool output_files )
80  : argc_{argc}, argv_{argv},
81  output_cout_{output_cout}, output_files_{output_files}
82  {
83 
84  }
85 
86  // Read the command line parameters. Throws an exception if something goes wrong.
87  static int setupParameters_(int argc, char** argv, Parallel::Communication comm)
88  {
89  if (!Parameters::IsRegistrationOpen()) {
90  // We have already successfully run setupParameters_().
91  // For the dynamically chosen runs (as from the main flow
92  // executable) we must run this function again with the
93  // real typetag to be used, as the first time was with the
94  // "FlowEarlyBird" typetag. However, for the static ones (such
95  // as 'flow_onephase_energy') it has already been run with the
96  // correct typetag.
97  return EXIT_SUCCESS;
98  }
99  // register the flow specific parameters
100  Parameters::Register<Parameters::OutputInterval>
101  ("Specify the number of report steps between two consecutive writes of restart data");
102  Parameters::Register<Parameters::EnableLoggingFalloutWarning>
103  ("Developer option to see whether logging was on non-root processors. "
104  "In that case it will be appended to the *.DBG or *.PRT files");
105  Parameters::Register<Parameters::DebugVerbosityLevel>
106  ("Set debug verbosity level globally. Default is 1, increasing values give additional output and 0 disables most messages to the .DBG file");
107 
108  // register the base parameters
109  registerAllParameters_<TypeTag>(/*finalizeRegistration=*/false);
110 
112 
113  detail::hideUnusedParameters<Scalar>();
114  if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()) {
115  Parameters::Hide<Parameters::VtkWriteTortuosities>();
116  Parameters::Hide<Parameters::VtkWriteDiffusionCoefficients>();
117  Parameters::Hide<Parameters::VtkWriteEffectiveDiffusionCoefficients>();
118  }
119 
120  Parameters::endRegistration();
121 
122  int mpiRank = comm.rank();
123 
124  // read in the command line parameters
125  int status = ::Opm::setupParameters_<TypeTag>(argc,
126  const_cast<const char**>(argv),
127  /*doRegistration=*/false,
128  /*allowUnused=*/true,
129  /*handleHelp=*/(mpiRank==0),
130  mpiRank);
131  if (status == 0) {
132 
133  // deal with unknown parameters.
134 
135  int unknownKeyWords = 0;
136  if (mpiRank == 0) {
137  unknownKeyWords = Parameters::printUnused(std::cerr);
138  }
139  int globalUnknownKeyWords = comm.sum(unknownKeyWords);
140  unknownKeyWords = globalUnknownKeyWords;
141  if ( unknownKeyWords )
142  {
143  if ( mpiRank == 0 )
144  {
145  std::string msg = "Aborting simulation due to unknown "
146  "parameters. Please query \"flow --help\" for "
147  "supported command line parameters.";
148  if (OpmLog::hasBackend("STREAMLOG"))
149  {
150  OpmLog::error(msg);
151  }
152  else {
153  std::cerr << msg << std::endl;
154  }
155  }
156  return EXIT_FAILURE;
157  }
158 
159  // deal with --print-parameters and unknown parameters.
160  if (Parameters::Get<Parameters::PrintParameters>() == 1) {
161  if (mpiRank == 0) {
162  Parameters::printValues(std::cout);
163  }
164  return -1;
165  }
166  }
167 
168  // set the maximum limit on OMP threads
169  setMaxThreads();
170 
171  return status;
172  }
173 
177  int execute()
178  {
179  return execute_(&FlowMain::runSimulator, /*cleanup=*/true);
180  }
181 
182  int executeInitStep()
183  {
184  return execute_(&FlowMain::runSimulatorInit, /*cleanup=*/false);
185  }
186 
187  // Returns true unless "EXIT" was encountered in the schedule
188  // section of the input datafile.
189  int executeStep()
190  {
191  return simulator_->runStep(*simtimer_);
192  }
193 
194  // Called from Python to cleanup after having executed the last
195  // executeStep()
196  int executeStepsCleanup()
197  {
198  SimulatorReport report = simulator_->finalize();
199  runSimulatorAfterSim_(report);
200  return report.success.exit_status;
201  }
202 
203  ModelSimulator* getSimulatorPtr()
204  {
205  return modelSimulator_.get();
206  }
207 
208  SimulatorTimer* getSimTimer()
209  {
210  return simtimer_.get();
211  }
212 
215  {
216  return simtimer_->stepLengthTaken();
217  }
218 
219  private:
220  // called by execute() or executeInitStep()
221  int execute_(int (FlowMain::* runOrInitFunc)(), bool cleanup)
222  {
223  auto logger = [this](const std::exception& e, const std::string& message_start) {
224  std::ostringstream message;
225  message << message_start << e.what();
226 
227  if (this->output_cout_) {
228  // in some cases exceptions are thrown before the logging system is set
229  // up.
230  if (OpmLog::hasBackend("STREAMLOG")) {
231  OpmLog::error(message.str());
232  }
233  else {
234  std::cout << message.str() << "\n";
235  }
236  }
237  detail::checkAllMPIProcesses();
238  return EXIT_FAILURE;
239  };
240 
241  try {
242  // deal with some administrative boilerplate
243 
244  Dune::Timer setupTimerAfterReadingDeck;
245  setupTimerAfterReadingDeck.start();
246 
247  int status = setupParameters_(this->argc_, this->argv_, FlowGenericVanguard::comm());
248  if (status) {
249  return status;
250  }
251 
252  setupParallelism();
253  setupModelSimulator();
254  createSimulator();
255 
256  this->deck_read_time_ = modelSimulator_->vanguard().setupTime();
257  this->total_setup_time_ = setupTimerAfterReadingDeck.elapsed() + this->deck_read_time_;
258 
259  // if run, do the actual work, else just initialize
260  int exitCode = (this->*runOrInitFunc)();
261  if (cleanup) {
262  executeCleanup_();
263  }
264  return exitCode;
265  }
266  catch (const TimeSteppingBreakdown& e) {
267  auto exitCode = logger(e, "Simulation aborted: ");
268  executeCleanup_();
269  return exitCode;
270  }
271  catch (const std::exception& e) {
272  auto exitCode = logger(e, "Simulation aborted as program threw an unexpected exception: ");
273  executeCleanup_();
274  return exitCode;
275  }
276  }
277 
278  void executeCleanup_() {
279  // clean up
280  mergeParallelLogFiles();
281  }
282 
283  protected:
284  void setupParallelism()
285  {
286  // determine the rank of the current process and the number of processes
287  // involved in the simulation. MPI must have already been initialized
288  // here. (yes, the name of this method is misleading.)
289  auto comm = FlowGenericVanguard::comm();
290  mpi_rank_ = comm.rank();
291  mpi_size_ = comm.size();
292 
293  setMaxThreads();
294  }
295 
296  static void setMaxThreads()
297  {
298 #if _OPENMP
299  // If openMP is available, default to 2 threads per process unless
300  // OMP_NUM_THREADS is set or command line --threads-per-process used.
301  // Issue a warning if both OMP_NUM_THREADS and --threads-per-process are set,
302  // but let the environment variable take precedence.
303  constexpr int default_threads = 2;
304  const bool isSet = Parameters::IsSet<Parameters::ThreadsPerProcess>();
305  const int requested_threads = Parameters::Get<Parameters::ThreadsPerProcess>();
306  int threads = requested_threads > 0 ? requested_threads : default_threads;
307 
308  const char* env_var = getenv("OMP_NUM_THREADS");
309  if (env_var) {
310  int omp_num_threads = -1;
311  auto result = std::from_chars(env_var, env_var + std::strlen(env_var), omp_num_threads);
312  if (result.ec == std::errc() && omp_num_threads > 0) {
313  // Set threads to omp_num_threads if it was successfully parsed and is positive
314  threads = omp_num_threads;
315  if (isSet) {
316  OpmLog::warning("Environment variable OMP_NUM_THREADS takes precedence over the --threads-per-process cmdline argument.");
317  }
318  } else {
319  OpmLog::warning("Invalid value for OMP_NUM_THREADS environment variable.");
320  }
321  }
322 
323  // Requesting -1 thread will let OMP automatically deduce the number
324  // but setting OMP_NUM_THREADS takes precedence.
325  if (env_var || !(isSet && requested_threads == -1)) {
326  omp_set_num_threads(threads);
327  }
328 #endif
329 
330  using TM = GetPropType<TypeTag, Properties::ThreadManager>;
331  TM::init(false);
332  }
333 
334  void mergeParallelLogFiles()
335  {
336  // force closing of all log files.
337  OpmLog::removeAllBackends();
338 
339  if (mpi_rank_ != 0 || mpi_size_ < 2 || !this->output_files_ || !modelSimulator_) {
340  return;
341  }
342 
343  detail::mergeParallelLogFiles(eclState().getIOConfig().getOutputDir(),
344  Parameters::Get<Parameters::EclDeckFileName>(),
345  Parameters::Get<Parameters::EnableLoggingFalloutWarning>());
346  }
347 
348  void setupModelSimulator()
349  {
350  modelSimulator_ = std::make_unique<ModelSimulator>(FlowGenericVanguard::comm(), /*verbose=*/false);
351  modelSimulator_->executionTimer().start();
352  modelSimulator_->model().applyInitialSolution();
353  }
354 
355  const EclipseState& eclState() const
356  { return modelSimulator_->vanguard().eclState(); }
357 
358  EclipseState& eclState()
359  { return modelSimulator_->vanguard().eclState(); }
360 
361  const Schedule& schedule() const
362  { return modelSimulator_->vanguard().schedule(); }
363 
364  // Run the simulator.
365  int runSimulator()
366  {
367  return runSimulatorInitOrRun_(&FlowMain::runSimulatorRunCallback_);
368  }
369 
370  int runSimulatorInit()
371  {
372  return runSimulatorInitOrRun_(&FlowMain::runSimulatorInitCallback_);
373  }
374 
375  private:
376  // Callback that will be called from runSimulatorInitOrRun_().
377  int runSimulatorRunCallback_()
378  {
379 #ifdef RESERVOIR_COUPLING_ENABLED
380  SimulatorReport report = simulator_->run(*simtimer_, this->argc_, this->argv_);
381 #else
382  SimulatorReport report = simulator_->run(*simtimer_);
383 #endif
384  runSimulatorAfterSim_(report);
385  return report.success.exit_status;
386  }
387 
388  // Callback that will be called from runSimulatorInitOrRun_().
389  int runSimulatorInitCallback_()
390  {
391 #ifdef RESERVOIR_COUPLING_ENABLED
392  simulator_->init(*simtimer_, this->argc_, this->argv_);
393 #else
394  simulator_->init(*simtimer_);
395 #endif
396  return EXIT_SUCCESS;
397  }
398 
399  // Output summary after simulation has completed
400  void runSimulatorAfterSim_(SimulatorReport &report)
401  {
402  if (simulator_->model().hasNlddSolver()) {
403  const auto& odir = eclState().getIOConfig().getOutputDir();
404  // Write the number of nonlinear iterations per cell to a file in ResInsight compatible format
405  simulator_->model().writeNonlinearIterationsPerCell(odir);
406  // Write the NLDD statistics to the DBG file
407  reportNlddStatistics(simulator_->model().domainAccumulatedReports(),
408  simulator_->model().localAccumulatedReports(),
409  this->output_cout_,
411  }
412 
413  if (! this->output_cout_) {
414  return;
415  }
416 
417  const int threads
418 #if !defined(_OPENMP) || !_OPENMP
419  = 1;
420 #else
421  = omp_get_max_threads();
422 #endif
423 
424  printFlowTrailer(mpi_size_, threads, total_setup_time_, deck_read_time_, report);
425 
426  detail::handleExtraConvergenceOutput(report,
427  Parameters::Get<Parameters::OutputExtraConvergenceInfo>(),
428  R"(OutputExtraConvergenceInfo (--output-extra-convergence-info))",
429  eclState().getIOConfig().getOutputDir(),
430  eclState().getIOConfig().getBaseName());
431  }
432 
433  // Run the simulator.
434  int runSimulatorInitOrRun_(int (FlowMain::* initOrRunFunc)())
435  {
436 
437  const auto& schedule = this->schedule();
438  auto& ioConfig = eclState().getIOConfig();
439  simtimer_ = std::make_unique<SimulatorTimer>();
440 
441  // initialize variables
442  const auto& initConfig = eclState().getInitConfig();
443  simtimer_->init(schedule, static_cast<std::size_t>(initConfig.getRestartStep()));
444 
445  if (this->output_cout_) {
446  std::ostringstream oss;
447 
448  // This allows a user to catch typos and misunderstandings in the
449  // use of simulator parameters.
450  if (Parameters::printUnused(oss)) {
451  std::cout << "----------------- Unrecognized parameters: -----------------\n";
452  std::cout << oss.str();
453  std::cout << "----------------------------------------------------------------" << std::endl;
454  }
455  }
456 
457  if (!ioConfig.initOnly()) {
458  if (this->output_cout_) {
459  std::string msg;
460  msg = "\n\n================ Starting main simulation loop ===============\n";
461  OpmLog::info(msg);
462  }
463 
464  return (this->*initOrRunFunc)();
465  }
466  else {
467  if (this->output_cout_) {
468  std::cout << "\n\n================ Simulation turned off ===============\n" << std::flush;
469  }
470  return EXIT_SUCCESS;
471  }
472  }
473 
474  protected:
475 
477  // Create simulator instance.
478  // Writes to:
479  // simulator_
481  {
482  // Create the simulator instance.
483  simulator_ = std::make_unique<Simulator>(*modelSimulator_);
484  }
485 
486  Grid& grid()
487  { return modelSimulator_->vanguard().grid(); }
488 
489  private:
490  std::unique_ptr<ModelSimulator> modelSimulator_;
491  int mpi_rank_ = 0;
492  int mpi_size_ = 1;
493  std::any parallel_information_;
494  std::unique_ptr<Simulator> simulator_;
495  std::unique_ptr<SimulatorTimer> simtimer_;
496  int argc_;
497  char **argv_;
498  bool output_cout_;
499  bool output_files_;
500  double total_setup_time_ = 0.0;
501  double deck_read_time_ = 0.0;
502  };
503 
504 } // namespace Opm
505 
506 #endif // OPM_FLOW_MAIN_HEADER_INCLUDED
Definition: FlowMain.hpp:55
Definition: FlowMain.hpp:57
typename Properties::Detail::GetPropImpl< TypeTag, Property >::type::type GetPropType
get the type alias defined in the property (equivalent to old macro GET_PROP_TYPE(...))
Definition: propertysystem.hh:233
typename Properties::Detail::GetPropImpl< TypeTag, Property >::type GetProp
get the type of a property (equivalent to old macro GET_PROP(...))
Definition: propertysystem.hh:224
void reportNlddStatistics(const std::vector< SimulatorReport > &domain_reports, const SimulatorReport &local_report, const bool output_cout, const Parallel::Communication &comm)
Reports NLDD statistics after simulation.
Definition: NlddReporting.cpp:97
Top-level driver for a fully implicit flow simulation.
Definition: SimulatorFullyImplicit.hpp:113
void createSimulator()
This is the main function of Flow.
Definition: FlowMain.hpp:480
Definition: FlowMain.hpp:66
double getPreviousReportStepSize()
Get the size of the previous report step.
Definition: FlowMain.hpp:214
Structs needed for tpfalinearizer and its gpuparams struct extracted to be defined in one place that ...
Definition: blackoilbioeffectsmodules.hh:45
Definition: blackoilnewtonmethodparams.hpp:31
static Parallel::Communication & comm()
Obtain global communicator.
Definition: FlowGenericVanguard.hpp:336
int execute()
This is the main function of Flow.
Definition: FlowMain.hpp:177
static void registerParameters()
Register all parameters consumed by this class and its major collaborators.
Definition: SimulatorFullyImplicit_impl.hpp:87
Provides convenience routines to bring up the simulation at runtime.