1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
| // ----------------- Main class -----------------
// For now, we will either be instantiated from main() in flow.cpp,
// or from a Python pybind11 module..
// NOTE (March 2020): When used from a pybind11 module, we do not neccessarily
// want to run the whole simulation by calling run(), it is also
// useful to just run one report step at a time. According to these different
// usage scenarios, we refactored the original run() in flow.cpp into this class.
class Main
{
private:
using FlowMainEbosType = FlowMainEbos<Properties::TTag::EclFlowProblem>;
public:
Main(int argc, char** argv) : argc_(argc), argv_(argv) { initMPI(); }
// This constructor can be called from Python
Main(const std::string& filename)
{
setArgvArgc_(filename);
initMPI();
}
// This constructor can be called from Python when Python has
// already parsed a deck
Main(std::shared_ptr<Deck> deck,
std::shared_ptr<EclipseState> eclipseState,
std::shared_ptr<Schedule> schedule,
std::shared_ptr<SummaryConfig> summaryConfig)
: deck_{std::move(deck)}
, eclipseState_{std::move(eclipseState)}
, schedule_{std::move(schedule)}
, summaryConfig_{std::move(summaryConfig)}
{
setArgvArgc_(deck_->getDataFile());
initMPI();
}
~Main()
{
#if HAVE_MPI
if (test_split_comm_) {
// Cannot use EclGenericVanguard::comm()
// to get world size here, as it may be
// a split communication at this point.
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
if (world_size > 1) {
MPI_Comm new_comm = EclGenericVanguard::comm();
int result;
MPI_Comm_compare(MPI_COMM_WORLD, new_comm, &result);
assert(result == MPI_UNEQUAL);
MPI_Comm_free(&new_comm);
}
}
#endif // HAVE_MPI
EclGenericVanguard::setCommunication(nullptr);
#if HAVE_MPI && !HAVE_DUNE_FEM
MPI_Finalize();
#endif
}
void setArgvArgc_(const std::string& filename)
{
this->deckFilename_ = filename;
this->flowProgName_ = "flow";
this->argc_ = 2;
this->saveArgs_[0] = const_cast<char *>(this->flowProgName_.c_str());
this->saveArgs_[1] = const_cast<char *>(this->deckFilename_.c_str());
// Note: argv[argc] must exist and be nullptr
assert ((sizeof this->saveArgs_) > (this->argc_ * sizeof this->saveArgs_[0]));
this->saveArgs_[this->argc_] = nullptr;
this->argv_ = this->saveArgs_;
}
void initMPI()
{
#if HAVE_DUNE_FEM
Dune::Fem::MPIManager::initialize(argc_, argv_);
#elif HAVE_MPI
MPI_Init(&argc_, &argv_);
#endif
EclGenericVanguard::setCommunication(std::make_unique<Parallel::Communication>());
handleTestSplitCommunicatorCmdLine_();
#if HAVE_MPI
if (test_split_comm_ && EclGenericVanguard::comm().size() > 1) {
int world_rank = EclGenericVanguard::comm().rank();
int color = (world_rank == 0);
MPI_Comm new_comm;
MPI_Comm_split(EclGenericVanguard::comm(), color, world_rank, &new_comm);
isSimulationRank_ = (world_rank > 0);
EclGenericVanguard::setCommunication(std::make_unique<Parallel::Communication>(new_comm));
}
#endif // HAVE_MPI
}
int runDynamic()
{
int exitCode = EXIT_SUCCESS;
if (isSimulationRank_) {
if (initialize_<Properties::TTag::FlowEarlyBird>(exitCode)) {
return this->dispatchDynamic_();
}
}
return exitCode;
}
template <class TypeTag>
int runStatic()
{
int exitCode = EXIT_SUCCESS;
if (isSimulationRank_) {
if (initialize_<TypeTag>(exitCode)) {
return this->dispatchStatic_<TypeTag>();
}
}
return exitCode;
}
// To be called from the Python interface code. Only do the
// initialization and then return a pointer to the FlowEbosMain
// object that can later be accessed directly from the Python interface
// to e.g. advance the simulator one report step
std::unique_ptr<FlowMainEbosType> initFlowEbosBlackoil(int& exitCode)
{
exitCode = EXIT_SUCCESS;
if (initialize_<Properties::TTag::FlowEarlyBird>(exitCode)) {
// TODO: check that this deck really represents a blackoil
// case. E.g. check that number of phases == 3
flowEbosBlackoilSetDeck(
setupTime_,
deck_,
eclipseState_,
schedule_,
std::move(udqState_),
std::move(this->actionState_),
std::move(this->wtestState_),
summaryConfig_);
return flowEbosBlackoilMainInit(
argc_, argv_, outputCout_, outputFiles_);
} else {
//NOTE: exitCode was set by initialize_() above;
return std::unique_ptr<FlowMainEbosType>(); // nullptr
}
}
private:
int dispatchDynamic_()
{
const auto& rspec = this->eclipseState_->runspec();
const auto& phases = rspec.phases();
// run the actual simulator
//
// TODO: make sure that no illegal combinations like thermal and
// twophase are requested.
// Single-phase case
if (rspec.micp()) {
return this->runMICP(phases);
}
// Twophase cases
else if (phases.size() == 2 && !eclipseState_->getSimulationConfig().isThermal()) {
return this->runTwoPhase(phases);
}
// Polymer case
else if (phases.active(Phase::POLYMER)) {
return this->runPolymer(phases);
}
// Foam case
else if (phases.active(Phase::FOAM)) {
return this->runFoam();
}
// Brine case
else if (phases.active(Phase::BRINE)) {
return this->runBrine(phases);
}
// Solvent case
else if (phases.active(Phase::SOLVENT)) {
return this->runSolvent();
}
// Extended BO case
else if (phases.active(Phase::ZFRACTION)) {
return this->runExtendedBlackOil();
}
// Energy case
else if (eclipseState_->getSimulationConfig().isThermal()) {
return this->runThermal(phases);
}
// Blackoil case
else if (phases.size() == 3) {
return this->runBlackOil();
}
else {
if (outputCout_) {
std::cerr << "No suitable configuration found, valid are "
<< "Twophase, polymer, foam, brine, solvent, "
<< "energy, and blackoil.\n";
}
return EXIT_FAILURE;
}
}
template <class TypeTag>
int dispatchStatic_()
{
flowEbosSetDeck<TypeTag>(
deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosMain<TypeTag>(argc_, argv_, outputCout_, outputFiles_);
}
/// \brief Initialize
/// \param exitCode The exitCode of the program.
///
/// \return Whether to actually run the simulator. I.e. true if
/// parsing of command line was successful and no --help,
/// --print-properties, or --print-parameters have been found.
template <class TypeTagEarlyBird>
bool initialize_(int& exitCode)
{
Dune::Timer externalSetupTimer;
externalSetupTimer.start();
handleVersionCmdLine_(argc_, argv_);
#if HAVE_DUNE_FEM
int mpiRank = Dune::Fem::MPIManager::rank();
#else
int mpiRank = EclGenericVanguard::comm().rank();
#endif
// we always want to use the default locale, and thus spare us the trouble
// with incorrect locale settings.
resetLocale();
// this is a work-around for a catch 22: we do not know what code path to use without
// parsing the deck, but we don't know the deck without having access to the
// parameters and this requires to know the type tag to be used. To solve this, we
// use a type tag just for parsing the parameters before we instantiate the actual
// simulator object. (Which parses the parameters again, but since this is done in an
// identical manner it does not matter.)
typedef TypeTagEarlyBird PreTypeTag;
using PreProblem = GetPropType<PreTypeTag, Properties::Problem>;
PreProblem::setBriefDescription("Flow, an advanced reservoir simulator for ECL-decks provided by the Open Porous Media project.");
int status = FlowMainEbos<PreTypeTag>::setupParameters_(argc_, argv_, EclGenericVanguard::comm());
if (status != 0) {
// if setupParameters_ returns a value smaller than 0, there was no error, but
// the program should abort. This is the case e.g. for the --help and the
// --print-properties parameters.
#if HAVE_MPI
if (status >= 0)
MPI_Abort(MPI_COMM_WORLD, status);
#endif
exitCode = (status > 0) ? status : EXIT_SUCCESS;
return false; // Whether to run the simulator
}
FileOutputMode outputMode = FileOutputMode::OUTPUT_NONE;
outputCout_ = false;
if (mpiRank == 0)
outputCout_ = EWOMS_GET_PARAM(PreTypeTag, bool, EnableTerminalOutput);
std::string deckFilename;
std::string outputDir;
if ( eclipseState_ ) {
deckFilename = eclipseState_->getIOConfig().fullBasePath();
outputDir = eclipseState_->getIOConfig().getOutputDir();
}
else {
deckFilename = EWOMS_GET_PARAM(PreTypeTag, std::string, EclDeckFileName);
}
if (deckFilename.empty()) {
if (mpiRank == 0) {
std::cerr << "No input case given. Try '--help' for a usage description.\n";
}
exitCode = EXIT_FAILURE;
return false;
}
using PreVanguard = GetPropType<PreTypeTag, Properties::Vanguard>;
try {
deckFilename = PreVanguard::canonicalDeckPath(deckFilename);
}
catch (const std::exception& e) {
if ( mpiRank == 0 ) {
std::cerr << "Exception received: " << e.what() << ". Try '--help' for a usage description.\n";
}
#if HAVE_MPI
MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
#endif
exitCode = EXIT_FAILURE;
return false;
}
if (outputCout_) {
FlowMainEbos<PreTypeTag>::printBanner(EclGenericVanguard::comm());
}
// Create Deck and EclipseState.
try {
auto python = std::make_shared<Python>();
const bool init_from_restart_file = !EWOMS_GET_PARAM(PreTypeTag, bool, SchedRestart);
if (outputDir.empty())
outputDir = EWOMS_GET_PARAM(PreTypeTag, std::string, OutputDir);
outputMode = setupLogging(mpiRank,
deckFilename,
outputDir,
EWOMS_GET_PARAM(PreTypeTag, std::string, OutputMode),
outputCout_, "STDOUT_LOGGER");
auto parseContext =
std::make_unique<ParseContext>(std::vector<std::pair<std::string , InputError::Action>>
{{ParseContext::PARSE_RANDOM_SLASH, InputError::IGNORE},
{ParseContext::PARSE_MISSING_DIMS_KEYWORD, InputError::WARN},
{ParseContext::SUMMARY_UNKNOWN_WELL, InputError::WARN},
{ParseContext::SUMMARY_UNKNOWN_GROUP, InputError::WARN}});
if (EWOMS_GET_PARAM(PreTypeTag, bool, EclStrictParsing))
parseContext->update(InputError::DELAYED_EXIT1);
FlowMainEbos<PreTypeTag>::printPRTHeader(outputCout_);
if (outputCout_) {
OpmLog::info("Reading deck file '" + deckFilename + "'");
}
std::optional<int> outputInterval;
int output_param = EWOMS_GET_PARAM(PreTypeTag, int, EclOutputInterval);
if (output_param >= 0)
outputInterval = output_param;
readDeck(EclGenericVanguard::comm(), deckFilename, deck_, eclipseState_, schedule_, udqState_, actionState_, wtestState_,
summaryConfig_, nullptr, python, std::move(parseContext),
init_from_restart_file, outputCout_, outputInterval);
setupTime_ = externalSetupTimer.elapsed();
outputFiles_ = (outputMode != FileOutputMode::OUTPUT_NONE);
}
catch (const std::invalid_argument& e)
{
if (outputCout_) {
std::cerr << "Failed to create valid EclipseState object." << std::endl;
std::cerr << "Exception caught: " << e.what() << std::endl;
}
#if HAVE_MPI
MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);
#endif
exitCode = EXIT_FAILURE;
return false;
}
exitCode = EXIT_SUCCESS;
return true;
}
std::filesystem::path simulationCaseName_(const std::string& casename)
{
namespace fs = ::std::filesystem;
auto exists = [](const fs::path& f)
{
return (fs::exists(f) && fs::is_regular_file(f))
|| (fs::is_symlink(f) &&
fs::is_regular_file(fs::read_symlink(f)));
};
auto simcase = fs::path { casename };
if (exists(simcase)) {
return simcase;
}
for (const auto& ext : { std::string("DATA"), std::string("data") }) {
if (exists(simcase.replace_extension(ext))) {
return simcase;
}
}
throw std::invalid_argument {
"Cannot find input case '" + casename + '\''
};
}
// This function is an extreme special case, if the program has been invoked
// *exactly* as:
//
// flow --version
//
// the call is intercepted by this function which will print "flow $version"
// on stdout and exit(0).
void handleVersionCmdLine_(int argc, char** argv)
{
auto pos = std::find_if(argv, argv + argc,
[](const char* arg)
{
return std::strcmp(arg, "--version") == 0;
});
if (pos != argv + argc) {
std::cout << "flow " << moduleVersionName() << std::endl;
std::exit(EXIT_SUCCESS);
}
}
// This function is a special case, if the program has been invoked
// with the argument "--test-split-communicator=true" as the FIRST
// argument, it will be removed from the argument list and we set the
// test_split_comm_ flag to true.
// Note: initializing the parameter system before MPI could make this
// use the parameter system instead.
void handleTestSplitCommunicatorCmdLine_()
{
if (argc_ >= 2 && std::strcmp(argv_[1], "--test-split-communicator=true") == 0) {
test_split_comm_ = true;
--argc_; // We have one less argument.
argv_[1] = argv_[0]; // What used to be the first proper argument now becomes the command argument.
++argv_; // Pretend this is what it always was.
}
}
int runMICP(const Phases& phases)
{
if (!phases.active(Phase::WATER) || (phases.size() > 2)) {
if (outputCout_) {
std::cerr << "No valid configuration is found for MICP simulation, "
<< "the only valid option is water + MICP\n";
}
return EXIT_FAILURE;
}
flowEbosMICPSetDeck(this->setupTime_,
this->deck_,
this->eclipseState_,
this->schedule_,
this->summaryConfig_);
return flowEbosMICPMain(this->argc_,
this->argv_,
this->outputCout_,
this->outputFiles_);
}
int runTwoPhase(const Phases& phases)
{
// oil-gas
if (phases.active( Phase::OIL ) && phases.active( Phase::GAS )) {
flowEbosGasOilSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosGasOilMain(argc_, argv_, outputCout_, outputFiles_);
}
// oil-water
else if ( phases.active( Phase::OIL ) && phases.active( Phase::WATER ) ) {
flowEbosOilWaterSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosOilWaterMain(argc_, argv_, outputCout_, outputFiles_);
}
// gas-water
else if ( phases.active( Phase::GAS ) && phases.active( Phase::WATER ) ) {
flowEbosGasWaterSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosGasWaterMain(argc_, argv_, outputCout_, outputFiles_);
}
else {
if (outputCout_) {
std::cerr << "No suitable configuration found, valid are Twophase (oilwater, oilgas and gaswater), polymer, solvent, or blackoil" << std::endl;
}
return EXIT_FAILURE;
}
}
int runPolymer(const Phases& phases)
{
if (! phases.active(Phase::WATER)) {
if (outputCout_)
std::cerr << "No valid configuration is found for polymer simulation, valid options include "
<< "oilwater + polymer and blackoil + polymer" << std::endl;
return EXIT_FAILURE;
}
// Need to track the polymer molecular weight
// for the injectivity study
if (phases.active(Phase::POLYMW)) {
// only oil water two phase for now
assert (phases.size() == 4);
return flowEbosOilWaterPolymerInjectivityMain(argc_, argv_, outputCout_, outputFiles_);
}
if (phases.size() == 3) { // oil water polymer case
flowEbosOilWaterPolymerSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosOilWaterPolymerMain(argc_, argv_, outputCout_, outputFiles_);
}
else {
flowEbosPolymerSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosPolymerMain(argc_, argv_, outputCout_, outputFiles_);
}
}
int runFoam()
{
flowEbosFoamSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosFoamMain(argc_, argv_, outputCout_, outputFiles_);
}
int runBrine(const Phases& phases)
{
if (! phases.active(Phase::WATER) || phases.size() == 2) {
if (outputCout_)
std::cerr << "No valid configuration is found for brine simulation, valid options include "
<< "oilwater + brine, gaswater + brine and blackoil + brine" << std::endl;
return EXIT_FAILURE;
}
if (phases.size() == 3) {
if (phases.active(Phase::OIL)){ // oil water brine case
flowEbosOilWaterBrineSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosOilWaterBrineMain(argc_, argv_, outputCout_, outputFiles_);
}
if (phases.active(Phase::GAS)){ // gas water brine case
flowEbosGasWaterBrineSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosGasWaterBrineMain(argc_, argv_, outputCout_, outputFiles_);
}
}
else if (eclipseState_->getSimulationConfig().hasPRECSALT()) {
flowEbosBrineSaltPrecipitationSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosBrineSaltPrecipitationMain(argc_, argv_, outputCout_, outputFiles_);
}
else {
flowEbosBrineSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosBrineMain(argc_, argv_, outputCout_, outputFiles_);
}
return EXIT_FAILURE;
}
int runSolvent()
{
flowEbosSolventSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosSolventMain(argc_, argv_, outputCout_, outputFiles_);
}
int runExtendedBlackOil()
{
flowEbosExtboSetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosExtboMain(argc_, argv_, outputCout_, outputFiles_);
}
int runThermal(const Phases& phases)
{
// oil-gas-thermal
if (!phases.active( Phase::WATER ) && phases.active( Phase::OIL ) && phases.active( Phase::GAS )) {
flowEbosGasOilEnergySetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosGasOilEnergyMain(argc_, argv_, outputCout_, outputFiles_);
}
flowEbosEnergySetDeck(
setupTime_, deck_, eclipseState_, schedule_, summaryConfig_);
return flowEbosEnergyMain(argc_, argv_, outputCout_, outputFiles_);
}
int runBlackOil()
{
flowEbosBlackoilSetDeck(this->setupTime_,
this->deck_,
this->eclipseState_,
this->schedule_,
std::move(this->udqState_),
std::move(this->actionState_),
std::move(this->wtestState_),
this->summaryConfig_);
return flowEbosBlackoilMain(argc_, argv_, outputCout_, outputFiles_);
}
int argc_{0};
char** argv_{nullptr};
bool outputCout_{false};
bool outputFiles_{false};
double setupTime_{0.0};
std::string deckFilename_{};
std::string flowProgName_{};
char *saveArgs_[3]{nullptr};
std::unique_ptr<UDQState> udqState_{};
std::unique_ptr<Action::State> actionState_{};
std::unique_ptr<WellTestState> wtestState_{};
// These variables may be owned by both Python and the simulator
std::shared_ptr<Deck> deck_{};
std::shared_ptr<EclipseState> eclipseState_{};
std::shared_ptr<Schedule> schedule_{};
std::shared_ptr<SummaryConfig> summaryConfig_{};
// To demonstrate run with non_world_comm
bool test_split_comm_ = false;
bool isSimulationRank_ = true;
};
} // namespace Opm
#endif // OPM_MAIN_HEADER_INCLUDED |