FlowProblemBlackoil.hpp
Go to the documentation of this file.
1// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2// vi: set et ts=4 sw=4 sts=4:
3/*
4 Copyright 2023 INRIA
5 Copyright 2024 SINTEF Digital
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 2 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 Consult the COPYING file in the top-level source directory of this
23 module for the precise wording of the license and the list of
24 copyright holders.
25*/
31#ifndef OPM_FLOW_PROBLEM_BLACK_HPP
32#define OPM_FLOW_PROBLEM_BLACK_HPP
33
34#include <opm/input/eclipse/Schedule/Events.hpp>
35#include <opm/input/eclipse/Schedule/OilVaporizationProperties.hpp>
36
38
39#include <opm/input/eclipse/EclipseState/Aquifer/AquiferConfig.hpp>
40#include <opm/input/eclipse/EclipseState/Aquifer/NumericalAquifer/NumericalAquiferCell.hpp>
41#include <opm/input/eclipse/EclipseState/Aquifer/NumericalAquifer/NumericalAquifers.hpp>
42#include <opm/input/eclipse/EclipseState/Grid/FaceDir.hpp>
43
44#include <opm/output/eclipse/EclipseIO.hpp>
45
55
57
58#if HAVE_DAMARIS
60#endif
61
62#include <algorithm>
63#include <cmath>
64#include <cstddef>
65#include <functional>
66#include <limits>
67#include <memory>
68#include <stdexcept>
69#include <string>
70#include <string_view>
71#include <unordered_map>
72#include <vector>
73
74namespace Opm {
75
82template <class TypeTag>
83class FlowProblemBlackoil : public FlowProblem<TypeTag>
84{
85 // TODO: the naming of the Types might be able to be adjusted
86public:
88
89private:
90 using typename FlowProblemType::Scalar;
91 using typename FlowProblemType::Simulator;
92 using typename FlowProblemType::GridView;
93 using typename FlowProblemType::FluidSystem;
94 using typename FlowProblemType::Vanguard;
96 using typename FlowProblemType::EqVector;
102
103 // TODO: potentially some cleaning up depending on the usage later here
119
123
127
129 using typename FlowProblemType::RateVector;
131 using typename FlowProblemType::Indices;
133 using typename FlowProblemType::ElementContext;
134
135 using typename FlowProblemType::MaterialLaw;
136 using typename FlowProblemType::DimMatrix;
137
138 static constexpr bool enableDissolvedGas =
139 Indices::compositionSwitchIdx != std::numeric_limits<unsigned>::max();
140 enum { enableVapwat = getPropValue<TypeTag, Properties::EnableVapwat>() };
141 enum { enableDisgasInWater = getPropValue<TypeTag, Properties::EnableDisgasInWater>() };
142 enum { enableGeochemistry = getPropValue<TypeTag, Properties::EnableGeochemistry>() };
143 enum { enableMech = getPropValue<TypeTag, Properties::EnableMech>() };
144
145 using BioeffectsModule = BlackOilBioeffectsModule<TypeTag, enableBioeffects>;
146 using BrineModule = BlackOilBrineModule<TypeTag, enableBrine>;
147 using ConvectiveMixingModule = BlackOilConvectiveMixingModule<TypeTag, enableConvectiveMixing>;
150 using ExtboModule = BlackOilExtboModule<TypeTag, enableExtbo>;
151 using FoamModule = BlackOilFoamModule<TypeTag, enableFoam>;
152 using PolymerModule = BlackOilPolymerModule<TypeTag, enablePolymer>;
153 using SolventModule = BlackOilSolventModule<TypeTag, enableSolvent>;
154
155 using EclWriterType = EclWriter<TypeTag, OutputBlackOilModule<TypeTag> >;
156 using IndexTraits = typename FluidSystem::IndexTraitsType;
157 using InitialFluidState = typename EquilInitializer<TypeTag>::ScalarFluidState;
158 using HybridNewton = BlackOilHybridNewton<TypeTag>;
159
160#if HAVE_DAMARIS
161 using DamarisWriterType = DamarisWriter<TypeTag>;
162#endif
163
164public:
167
171 static void registerParameters()
172 {
174
176#if HAVE_DAMARIS
177 DamarisWriterType::registerParameters();
178#endif
180 }
181
185 explicit FlowProblemBlackoil(Simulator& simulator)
186 : FlowProblemType(simulator)
187 , mixControls_(simulator.vanguard().schedule())
188 , prev_timestep_state_(simulator.vanguard().schedule())
189 , actionHandler_(simulator.vanguard().eclState(),
190 simulator.vanguard().schedule(),
191 simulator.vanguard().actionState(),
192 simulator.vanguard().summaryState(),
193 this->wellModel_,
194 simulator.vanguard().grid().comm())
195 , hybridNewton_(simulator)
196 {
197 this->model().addOutputModule(std::make_unique<VtkTracerModule<TypeTag>>(simulator));
198
199 // Tell the black-oil extensions to initialize their internal data structures
200 const auto& vanguard = simulator.vanguard();
201
202 if constexpr (enableBrine) {
203 BlackOilBrineParams<Scalar> brineParams;
204 brineParams.template initFromState<enableBrine,
205 enableSaltPrecipitation>(vanguard.eclState());
206 BrineModule::setParams(std::move(brineParams));
207 }
208
209 if constexpr (enableDiffusion) {
210 DiffusionModule::initFromState(vanguard.eclState());
211 }
212
213 if constexpr (enableDispersion) {
214 DispersionModule::initFromState(vanguard.eclState());
215 }
216
217 if constexpr (enableExtbo) {
218 BlackOilExtboParams<Scalar> extboParams;
219 extboParams.template initFromState<enableExtbo>(vanguard.eclState());
220 ExtboModule::setParams(std::move(extboParams));
221 }
222
223 if constexpr (enableFoam) {
225 foamParams.template initFromState<enableFoam>(vanguard.eclState());
226 FoamModule::setParams(std::move(foamParams));
227 }
228
229 if constexpr (enableBioeffects) {
230 BlackOilBioeffectsParams<Scalar> bioeffectsParams;
231 bioeffectsParams.template initFromState<enableBioeffects, enableMICP>(vanguard.eclState());
232 BioeffectsModule::setParams(std::move(bioeffectsParams));
233 }
234
235 if constexpr (enablePolymer) {
236 BlackOilPolymerParams<Scalar> polymerParams;
237 polymerParams.template initFromState<enablePolymer, enablePolymerMolarWeight>(vanguard.eclState());
238 PolymerModule::setParams(std::move(polymerParams));
239 }
240
241 if constexpr (enableSolvent) {
242 BlackOilSolventParams<Scalar> solventParams;
243 solventParams.template initFromState<enableSolvent>(vanguard.eclState(), vanguard.schedule());
244 SolventModule::setParams(std::move(solventParams));
245 }
246
247 // create the ECL writer
248 eclWriter_ = std::make_unique<EclWriterType>(simulator);
249 enableEclOutput_ = Parameters::Get<Parameters::EnableEclOutput>();
250
251 // Safeguard against geochemistry since it exsist in a separate module with a separate problem class
252 if constexpr (!enableGeochemistry) {
253 if (vanguard.eclState().runspec().geochem().enabled()) {
254 throw std::runtime_error("GEOCHEM keyword in the deck but geochemistry module "
255 "was disabled at compile time!");
256 }
257 }
258
259 // Safeguard against TPSA-geomechanics since it requires FlowProblemTPSA
260 if constexpr (!enableMech) {
261 const auto& rspec = vanguard.eclState().runspec();
262 if (rspec.mech() && rspec.mechSolver().tpsa()) {
263 throw std::runtime_error("TPSA solver enabled in the deck, but geomechanics "
264 "module was disabled at compile time!");
265 }
266 }
267
268#if HAVE_DAMARIS
269 // create Damaris writer
270 damarisWriter_ = std::make_unique<DamarisWriterType>(simulator);
271 enableDamarisOutput_ = Parameters::Get<Parameters::EnableDamarisOutput>();
272#endif
273 }
274
278 void beginEpisode() override
279 {
280 checkGpuAssemblySchedule_();
282
283 auto& simulator = this->simulator();
284
285 const int episodeIdx = simulator.episodeIndex();
286 const auto& schedule = simulator.vanguard().schedule();
287
288 // Evaluate UDQ assign statements to make sure the settings are
289 // available as UDA controls for the current report step.
290 this->actionHandler_
291 .evalUDQAssignments(episodeIdx, simulator.vanguard().udqState());
292
293 if (episodeIdx >= 0) {
294 const auto& oilVap = schedule[episodeIdx].oilvap();
295 if (oilVap.getType() == OilVaporizationProperties::OilVaporization::VAPPARS) {
296 FluidSystem::setVapPars(oilVap.vap1(), oilVap.vap2());
297 }
298 else {
299 FluidSystem::setVapPars(0.0, 0.0);
300 }
301
302 if constexpr (enableConvectiveMixing) {
303 ConvectiveMixingModule::beginEpisode(simulator.vanguard().eclState(), schedule, episodeIdx,
304 this->moduleParams_.convectiveMixingModuleParam);
305 }
306 }
307 }
308
312 void beginTimeStep() override
313 {
316 }
317
322 {
323 FlowProblemType::finishInit();
324
325 auto& simulator = this->simulator();
326 const bool transmissibilitiesFinished =
328
329 const auto& eclState = simulator.vanguard().eclState();
330 const auto& schedule = simulator.vanguard().schedule();
332
333 // conserve inner energy instead of enthalpy if TEMP is used
334 // or THERMAL and parameter ConserveInnerEnergyThermal is true (default false)
335 bool isThermal = eclState.getSimulationConfig().isThermal();
336 bool isTemp = eclState.getSimulationConfig().isTemp();
337 bool conserveInnerEnergy = isTemp || (isThermal && Parameters::Get<Parameters::ConserveInnerEnergyThermal>());
338 FluidSystem::setEnergyEqualEnthalpy(conserveInnerEnergy);
339
341
342 // write the static output files (EGRID, INIT)
343 if (enableEclOutput_) {
344 this->eclWriter_->writeInit();
345 }
346
347 if (!transmissibilitiesFinished) {
349 }
350
351 const auto& initconfig = eclState.getInitConfig();
352 this->tracerModel_.init(initconfig.restartRequested());
353 if (initconfig.restartRequested()) {
355 }
356 else {
357 this->readInitialCondition_();
358 }
359 this->temperatureModel_.init();
360 this->tracerModel_.prepareTracerBatches();
361
362 this->updatePffDofData_();
363
364 if constexpr (getPropValue<TypeTag, Properties::EnablePolymer>()) {
365 const auto& vanguard = this->simulator().vanguard();
366 const auto& gridView = vanguard.gridView();
367 const int numElements = gridView.size(/*codim=*/0);
368 this->polymer_.maxAdsorption.resize(numElements, 0.0);
369 }
370
372
373 // compute and set eq weights based on initial b values
375
377 this->drift_.resize(this->model().numGridDof());
378 this->drift_ = 0.0;
379 }
380
381 // after finishing the initialization and writing the initial solution, we move
382 // to the first "real" episode/report step
383 // for restart the episode index and start is already set
384 if (!initconfig.restartRequested() && !eclState.getIOConfig().initOnly()) {
385 simulator.startNextEpisode(schedule.seconds(1));
386 simulator.setEpisodeIndex(0);
387 simulator.setTimeStepIndex(0);
388 }
389
390 if (Parameters::Get<Parameters::CheckSatfuncConsistency>() &&
392 {
393 // User requested that saturation functions be checked for
394 // consistency and essential/critical requirements are not met.
395 // Abort simulation run.
396 //
397 // Note: We need synchronisation here lest ranks other than the
398 // I/O rank throw exceptions too early thereby risking an
399 // incomplete failure report being shown to the user.
400 this->simulator().vanguard().grid().comm().barrier();
401
402 throw std::domain_error {
403 "Saturation function end-points do not "
404 "meet requisite consistency conditions"
405 };
406 }
407
408 // Checked once the initial solution has been applied.
409 this->checkAquiferEquilibration_ = !initconfig.restartRequested() && initconfig.hasEquil();
410
411 // TODO: move to the end for later refactoring of the function finishInit()
412 //
413 // deal with DRSDT
414 this->mixControls_.init(this->model().numGridDof(),
415 this->episodeIndex(),
416 eclState.runspec().tabdims().getNumPVTTables());
417
418 // Seed the DRSDT/DRVDT history from the initial composition. Left at
419 // zero, the limiter caps Rs at DRSDT * dt on the first step and boils
420 // the dissolved gas out of an undersaturated reservoir. A restarted
421 // run seeds it from the restart solution instead.
422 if (!initconfig.restartRequested()) {
423 for (std::size_t elemIdx = 0; elemIdx < this->initialFluidStates_.size(); ++elemIdx) {
424 const auto& fs = this->initialFluidStates_[elemIdx];
425 this->mixControls_.updateLastValues(elemIdx, fs.Rs(), fs.Rv());
426 }
427 }
428
429 if (this->enableVtkOutput_() && eclState.getIOConfig().initOnly()) {
430 simulator.setTimeStepSize(0.0);
431 simulator.model().applyInitialSolution();
433 }
434
435 if (!eclState.getIOConfig().initOnly()) {
436 if (!this->enableTuning_ && eclState.getSimulationConfig().anyTUNING()) {
437 OpmLog::info("\nThe deck has TUNING in the SCHEDULE section, but "
438 "it is ignored due\nto the flag --enable-tuning=false. "
439 "Set this flag to true to activate it.\n"
440 "Manually tuning the simulator with the TUNING keyword may "
441 "increase run time.\nIt is recommended using the simulator's "
442 "default tuning (--enable-tuning=false).");
443 }
444 }
445 }
446
450 void endTimeStep() override
451 {
453 this->endStepApplyAction();
454 }
455
457 {
458 // After the solution is updated, the values in output module needs
459 // also updated.
460 this->eclWriter().mutableOutputModule().invalidateLocalData();
461
462 // For CpGrid with LGRs, ecl/vtk output is not supported yet.
463 const auto& grid = this->simulator().vanguard().gridView().grid();
464
465 using GridType = std::remove_cv_t<std::remove_reference_t<decltype(grid)>>;
466 constexpr bool isCpGrid = std::is_same_v<GridType, Dune::CpGrid>;
467 if (!isCpGrid || (grid.maxLevel() == 0)) {
468 this->eclWriter_->evalSummaryState(!this->episodeWillBeOver());
469 }
470
471 {
472 OPM_TIMEBLOCK(applyActions);
473
474 const int episodeIdx = this->episodeIndex();
475 auto& simulator = this->simulator();
476
477 // Clear out any existing events as these have already been
478 // processed when we're running an action block
479 this->simulator().vanguard().schedule().clearEvents(episodeIdx);
480
481 // Re-ordering in case of Alugrid
482 this->actionHandler_
483 .applyActions(episodeIdx, simulator.time() + simulator.timeStepSize(),
484 [this](const bool global)
485 {
486 using TransUpdateQuantities = typename
487 Vanguard::TransmissibilityType::TransUpdateQuantities;
488
489 this->transmissibilities_
490 .update(global, TransUpdateQuantities::All,
491 [&vg = this->simulator().vanguard()]
492 (const unsigned int i)
493 {
494 return vg.gridIdxToEquilGridIdx(i);
495 });
496 });
497 // Actions can change coefficients within a report step. Check before
498 // advancing to a new report step, which clears the current events.
499 checkGpuAssemblySchedule_();
500 }
501 }
502
506 void endEpisode() override
507 {
508 OPM_TIMEBLOCK(endEpisode);
509
510 // Rerun UDQ assignents following action processing on the final
511 // time step of this episode to make sure that any UDQ ASSIGN
512 // operations triggered in action blocks take effect. This is
513 // mainly to work around a shortcoming of the ScheduleState copy
514 // constructor which clears pending UDQ assignments under the
515 // assumption that all such assignments have been processed. If an
516 // action block happens to trigger on the final time step of an
517 // episode and that action block runs a UDQ assignment, then that
518 // assignment would be dropped and the rest of the simulator will
519 // never see its effect without this hack.
520 this->actionHandler_
521 .evalUDQAssignments(this->episodeIndex(), this->simulator().vanguard().udqState());
522
523 FlowProblemType::endEpisode();
524 }
525
526 void writeReports(const SimulatorTimer& timer)
527 {
528 if (this->enableEclOutput_) {
529 this->eclWriter_->writeReports(timer);
530 }
531 }
532
533
538 void writeOutput(const bool verbose) override
539 {
540 FlowProblemType::writeOutput(verbose);
541
542 const auto isSubStep = !this->episodeWillBeOver();
543
544 auto localCellData = data::Solution {};
545
546#if HAVE_DAMARIS
547 // N.B. the Damaris output has to be done before the ECL output as the ECL one
548 // does all kinds of std::move() relocation of data
549 if (this->enableDamarisOutput_ && (this->damarisWriter_ != nullptr)) {
550 this->damarisWriter_->writeOutput(localCellData, isSubStep);
551 }
552#endif
553
554 if (this->enableEclOutput_ && (this->eclWriter_ != nullptr)) {
555 this->eclWriter_->writeOutput(std::move(localCellData), isSubStep,
556 this->simulator().vanguard().schedule()
557 .exitStatus().has_value());
558 }
559 }
560
562 {
563 OPM_TIMEBLOCK(finalizeOutput);
564 // this will write all pending output to disk
565 // to avoid corruption of output files
566 eclWriter_.reset();
567 }
568
569
574 {
575 FlowProblemType::initialSolutionApplied();
576
577 // let the object for threshold pressures initialize itself. this is done only at
578 // this point, because determining the threshold pressures may require to access
579 // the initial solution.
580 this->thresholdPressures_.finishInit();
581
582 if (this->checkAquiferEquilibration_) {
583 this->checkAquiferEquilibration_ = false;
584 this->checkNumericalAquiferEquilibration_();
585 }
586
587 // For CpGrid with LGRs, ecl-output is not supported yet.
588 const auto& grid = this->simulator().vanguard().gridView().grid();
589
590 using GridType = std::remove_cv_t<std::remove_reference_t<decltype(grid)>>;
591 constexpr bool isCpGrid = std::is_same_v<GridType, Dune::CpGrid>;
592 // Skip - for now - calculate the initial fip values for CpGrid with LGRs.
593 if (!isCpGrid || (grid.maxLevel() == 0)) {
594 if (this->simulator().episodeIndex() == 0) {
595 eclWriter_->writeInitialFIPReport();
596 }
597 }
598 }
599
601 unsigned globalDofIdx,
602 unsigned timeIdx) const override
603 {
604 this->aquiferModel_.addToSource(rate, globalDofIdx, timeIdx);
605
606 // Add source term from deck
607 const auto& source = this->simulator().vanguard().schedule()[this->episodeIndex()].source();
608 std::array<int,3> ijk;
609 this->simulator().vanguard().cartesianCoordinate(globalDofIdx, ijk);
610
611 if (source.hasSource(ijk)) {
612 const int pvtRegionIdx = this->pvtRegionIndex(globalDofIdx);
613 static std::array<SourceComponent, 3> sc_map = {SourceComponent::WATER, SourceComponent::OIL, SourceComponent::GAS};
614 static std::array<int, 3> phidx_map = {FluidSystem::waterPhaseIdx, FluidSystem::oilPhaseIdx, FluidSystem::gasPhaseIdx};
615 static std::array<int, 3> cidx_map = {waterCompIdx, oilCompIdx, gasCompIdx};
616
617 for (unsigned i = 0; i < phidx_map.size(); ++i) {
618 const auto phaseIdx = phidx_map[i];
619 const auto sourceComp = sc_map[i];
620 const auto compIdx = cidx_map[i];
621 if (!FluidSystem::phaseIsActive(phaseIdx)) {
622 continue;
623 }
624 Scalar mass_rate = source.rate(ijk, sourceComp) / this->model().dofTotalVolume(globalDofIdx);
625 if constexpr (getPropValue<TypeTag, Properties::BlackoilConserveSurfaceVolume>()) {
626 mass_rate /= FluidSystem::referenceDensity(phaseIdx, pvtRegionIdx);
627 }
628 rate[FluidSystem::canonicalToActiveCompIdx(compIdx)] += mass_rate;
629 }
630
631 if constexpr (enableSolvent) {
632 Scalar mass_rate = source.rate(ijk, SourceComponent::SOLVENT) / this->model().dofTotalVolume(globalDofIdx);
633 if constexpr (getPropValue<TypeTag, Properties::BlackoilConserveSurfaceVolume>()) {
634 const auto& solventPvt = SolventModule::solventPvt();
635 mass_rate /= solventPvt.referenceDensity(pvtRegionIdx);
636 }
637 rate[Indices::contiSolventEqIdx] += mass_rate;
638 }
639 if constexpr (enablePolymer) {
640 rate[Indices::polymerConcentrationIdx] += source.rate(ijk, SourceComponent::POLYMER) / this->model().dofTotalVolume(globalDofIdx);
641 }
642 if constexpr (enableMICP) {
643 rate[Indices::microbialConcentrationIdx] += source.rate(ijk, SourceComponent::MICR) / this->model().dofTotalVolume(globalDofIdx);
644 rate[Indices::oxygenConcentrationIdx] += source.rate(ijk, SourceComponent::OXYG) / this->model().dofTotalVolume(globalDofIdx);
645 rate[Indices::ureaConcentrationIdx] += source.rate(ijk, SourceComponent::UREA) / (this->model().dofTotalVolume(globalDofIdx));
646 }
647 if constexpr (energyModuleType == EnergyModules::FullyImplicitThermal) {
648 for (unsigned i = 0; i < phidx_map.size(); ++i) {
649 const auto phaseIdx = phidx_map[i];
650 if (!FluidSystem::phaseIsActive(phaseIdx)) {
651 continue;
652 }
653 const auto sourceComp = sc_map[i];
654 const auto source_hrate = source.hrate(ijk, sourceComp);
655 if (source_hrate) {
656 rate[Indices::contiEnergyEqIdx] += source_hrate.value() / this->model().dofTotalVolume(globalDofIdx);
657 } else {
658 const auto& intQuants = this->simulator().model().intensiveQuantities(globalDofIdx, /*timeIdx*/ 0);
659 auto fs = intQuants.fluidState();
660 // if temperature is not set, use cell temperature as default
661 const auto source_temp = source.temperature(ijk, sourceComp);
662 if (source_temp) {
663 Scalar temperature = source_temp.value();
664 fs.setTemperature(temperature);
665 }
666 const auto& h = FluidSystem::enthalpy(fs, phaseIdx, pvtRegionIdx);
667 Scalar mass_rate = source.rate(ijk, sourceComp)/ this->model().dofTotalVolume(globalDofIdx);
668 Scalar energy_rate = getValue(h)*mass_rate;
669 rate[Indices::contiEnergyEqIdx] += energy_rate;
670 }
671 }
672 }
673 }
674
675 // if requested, compensate systematic mass loss for cells which were "well
676 // behaved" in the last time step
677 if (this->enableDriftCompensation_) {
678 const auto& simulator = this->simulator();
679 const auto& model = this->model();
680
681 // we use a lower tolerance for the compensation too
682 // assure the added drift from the last step does not
683 // cause convergence issues on the current step
684 Scalar maxCompensation = model.newtonMethod().tolerance()/10;
685 Scalar poro = this->porosity(globalDofIdx, timeIdx);
686 Scalar dt = simulator.timeStepSize();
687 EqVector dofDriftRate = this->drift_[globalDofIdx];
688 dofDriftRate /= dt*model.dofTotalVolume(globalDofIdx);
689
690 // restrict drift compensation to the CNV tolerance
691 for (unsigned eqIdx = 0; eqIdx < numEq; ++ eqIdx) {
692 Scalar cnv = std::abs(dofDriftRate[eqIdx])*dt*model.eqWeight(globalDofIdx, eqIdx)/poro;
693 if (cnv > maxCompensation) {
694 dofDriftRate[eqIdx] *= maxCompensation/cnv;
695 }
696 }
697
698 for (unsigned eqIdx = 0; eqIdx < numEq; ++ eqIdx)
699 rate[eqIdx] -= dofDriftRate[eqIdx];
700 }
701 }
702
706 template <class LhsEval, class Callback>
707 LhsEval permFactTransMultiplier(const IntensiveQuantities& intQuants, unsigned elementIdx, Callback& obtain) const
708 {
709 OPM_TIMEBLOCK_LOCAL(permFactTransMultiplier, Subsystem::PvtProps);
710 if constexpr (enableSaltPrecipitation) {
711 const auto& fs = intQuants.fluidState();
712 unsigned tableIdx = this->simulator().problem().satnumRegionIndex(elementIdx);
713 LhsEval porosityFactor = obtain(1. - fs.saltSaturation());
714 porosityFactor = min(porosityFactor, 1.0);
715 const auto& permfactTable = BrineModule::permfactTable(tableIdx);
716 return permfactTable.eval(porosityFactor, /*extrapolation=*/true);
717 }
718 else if constexpr (enableBioeffects) {
719 return obtain(intQuants.permFactor());
720 }
721 else {
722 return 1.0;
723 }
724 }
725
726 // temporary solution to facilitate output of initial state from flow
727 const InitialFluidState& initialFluidState(unsigned globalDofIdx) const
728 { return initialFluidStates_[globalDofIdx]; }
729
730 std::vector<InitialFluidState>& initialFluidStates()
731 { return initialFluidStates_; }
732
733 const std::vector<InitialFluidState>& initialFluidStates() const
734 { return initialFluidStates_; }
735
736 const EclipseIO& eclIO() const
737 { return eclWriter_->eclIO(); }
738
740 { return eclWriter_->setSubStepReport(report); }
741
743 { return eclWriter_->setSimulationReport(report); }
744
745 InitialFluidState boundaryFluidState(unsigned globalDofIdx, const int directionId) const
746 {
747 OPM_TIMEBLOCK_LOCAL(boundaryFluidState, Subsystem::Assembly);
748 const auto& bcstate = this->simulator().vanguard().schedule()[this->episodeIndex()].bcstate;
749 if (bcstate.size() > 0) {
750 FaceDir::DirEnum dir = FaceDir::FromIntersectionIndex(directionId);
751
752 // index == 0: no boundary conditions for this
753 // global cell and direction
754 if (this->bcindex_(dir)[globalDofIdx] == 0)
755 return initialFluidStates_[globalDofIdx];
756
757 const auto& bc = bcstate[this->bcindex_(dir)[globalDofIdx]];
758 if (bc.bctype == BCType::DIRICHLET )
759 {
760 InitialFluidState fluidState;
761 const int pvtRegionIdx = this->pvtRegionIndex(globalDofIdx);
762 fluidState.setPvtRegionIndex(pvtRegionIdx);
763
764 switch (bc.component) {
765 case BCComponent::OIL:
766 if (!FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx))
767 throw std::logic_error("oil is not active and you're trying to add oil BC");
768
769 fluidState.setSaturation(FluidSystem::oilPhaseIdx, 1.0);
770 break;
771 case BCComponent::GAS:
772 if (!FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
773 throw std::logic_error("gas is not active and you're trying to add gas BC");
774
775 fluidState.setSaturation(FluidSystem::gasPhaseIdx, 1.0);
776 break;
777 case BCComponent::WATER:
778 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx))
779 throw std::logic_error("water is not active and you're trying to add water BC");
780
781 fluidState.setSaturation(FluidSystem::waterPhaseIdx, 1.0);
782 break;
783 case BCComponent::SOLVENT:
784 case BCComponent::POLYMER:
785 case BCComponent::MICR:
786 case BCComponent::OXYG:
787 case BCComponent::UREA:
789 throw std::logic_error("you need to specify a valid component (OIL, WATER or GAS) when DIRICHLET type is set in BC");
790 }
791 fluidState.setTotalSaturation(1.0);
792 double pressure = initialFluidStates_[globalDofIdx].pressure(this->refPressurePhaseIdx_());
793 const auto pressure_input = bc.pressure;
794 if (pressure_input) {
795 pressure = *pressure_input;
796 }
797
798 std::array<Scalar, numPhases> pc = {0};
799 const auto& matParams = this->materialLawParams(globalDofIdx);
800 MaterialLaw::capillaryPressures(pc, matParams, fluidState);
801 Valgrind::CheckDefined(pressure);
802 Valgrind::CheckDefined(pc);
803 for (unsigned activePhaseIdx = 0; activePhaseIdx < FluidSystem::numActivePhases(); ++activePhaseIdx) {
804 const auto phaseIdx = FluidSystem::activeToCanonicalPhaseIdx(activePhaseIdx);
805 if (Indices::oilEnabled)
806 fluidState.setPressure(phaseIdx, pressure + (pc[phaseIdx] - pc[oilPhaseIdx]));
807 else if (Indices::gasEnabled)
808 fluidState.setPressure(phaseIdx, pressure + (pc[phaseIdx] - pc[gasPhaseIdx]));
809 else if (Indices::waterEnabled)
810 //single (water) phase
811 fluidState.setPressure(phaseIdx, pressure);
812 }
813 if constexpr (energyModuleType != EnergyModules::NoTemperature) {
814 double temperature = initialFluidStates_[globalDofIdx].temperature(0); // we only have one temperature
815 const auto temperature_input = bc.temperature;
816 if(temperature_input)
817 temperature = *temperature_input;
818 fluidState.setTemperature(temperature);
819 }
820
821 if constexpr (enableDissolvedGas) {
822 if (FluidSystem::enableDissolvedGas()) {
823 fluidState.setRs(0.0);
824 fluidState.setRv(0.0);
825 }
826 }
827 if constexpr (enableDisgasInWater) {
828 if (FluidSystem::enableDissolvedGasInWater()) {
829 fluidState.setRsw(0.0);
830 }
831 }
832 if constexpr (enableVapwat) {
833 if (FluidSystem::enableVaporizedWater()) {
834 fluidState.setRvw(0.0);
835 }
836 }
837
838 for (unsigned activePhaseIdx = 0; activePhaseIdx < FluidSystem::numActivePhases(); ++activePhaseIdx) {
839 const auto phaseIdx = FluidSystem::activeToCanonicalPhaseIdx(activePhaseIdx);
840
841 const auto& b = FluidSystem::inverseFormationVolumeFactor(fluidState, phaseIdx, pvtRegionIdx);
842 fluidState.setInvB(phaseIdx, b);
843
844 const auto& rho = FluidSystem::density(fluidState, phaseIdx, pvtRegionIdx);
845 fluidState.setDensity(phaseIdx, rho);
846 if constexpr (energyModuleType == EnergyModules::FullyImplicitThermal) {
847 const auto& h = FluidSystem::enthalpy(fluidState, phaseIdx, pvtRegionIdx);
848 fluidState.setEnthalpy(phaseIdx, h);
849 }
850 }
851 fluidState.checkDefined();
852 return fluidState;
853 }
854 }
855 return initialFluidStates_[globalDofIdx];
856 }
857
858
860 { return *eclWriter_; }
861
863 { return *eclWriter_; }
864
869 Scalar maxGasDissolutionFactor(unsigned timeIdx, unsigned globalDofIdx) const
870 {
871 return this->mixControls_.maxGasDissolutionFactor(timeIdx, globalDofIdx,
872 this->episodeIndex(),
873 this->pvtRegionIndex(globalDofIdx));
874 }
875
880 Scalar maxOilVaporizationFactor(unsigned timeIdx, unsigned globalDofIdx) const
881 {
882 return this->mixControls_.maxOilVaporizationFactor(timeIdx, globalDofIdx,
883 this->episodeIndex(),
884 this->pvtRegionIndex(globalDofIdx));
885 }
886
899 {
900 const auto& rspec = this->simulator().vanguard().eclState().runspec();
901 const bool tpsaActive = rspec.mech() && rspec.mechSolver().tpsa();
902 if (tpsaActive) {
903 return false;
904 }
905
906 int episodeIdx = this->episodeIndex();
907 return !this->mixControls_.drsdtActive(episodeIdx) &&
908 !this->mixControls_.drvdtActive(episodeIdx) &&
909 this->rockCompPoroMultWc_.empty() &&
910 this->rockCompPoroMult_.empty();
911 }
912
919 template <class Context>
920 void initial(PrimaryVariables& values, const Context& context, unsigned spaceIdx, unsigned timeIdx) const
921 {
922 unsigned globalDofIdx = context.globalSpaceIndex(spaceIdx, timeIdx);
923
924 values.setPvtRegionIndex(pvtRegionIndex(context, spaceIdx, timeIdx));
925 values.assignNaive(initialFluidStates_[globalDofIdx]);
926
927 if constexpr (enableSolvent) {
928 SolventModule::assignPrimaryVars(values,
929 this->solventSaturation_[globalDofIdx],
930 this->solventRsw_[globalDofIdx]);
931 }
932
933 if constexpr (enablePolymer) {
934 values[Indices::polymerConcentrationIdx] = this->polymer_.concentration[globalDofIdx];
935 }
936
937 if constexpr (enablePolymerMolarWeight) {
938 values[Indices::polymerMoleWeightIdx]= this->polymer_.moleWeight[globalDofIdx];
939 }
940
941 if constexpr (enableBrine) {
942 if (enableSaltPrecipitation && values.primaryVarsMeaningBrine() == PrimaryVariables::BrineMeaning::Sp) {
943 values[Indices::saltConcentrationIdx] = initialFluidStates_[globalDofIdx].saltSaturation();
944 }
945 else {
946 values[Indices::saltConcentrationIdx] = initialFluidStates_[globalDofIdx].saltConcentration();
947 }
948 }
949
950 if constexpr (enableBioeffects) {
951 values[Indices::microbialConcentrationIdx] = this->bioeffects_.microbialConcentration[globalDofIdx];
952 values[Indices::biofilmVolumeFractionIdx] = this->bioeffects_.biofilmVolumeFraction[globalDofIdx];
953 if constexpr (enableMICP) {
954 values[Indices::oxygenConcentrationIdx] = this->bioeffects_.oxygenConcentration[globalDofIdx];
955 values[Indices::ureaConcentrationIdx] = this->bioeffects_.ureaConcentration[globalDofIdx];
956 values[Indices::calciteVolumeFractionIdx] = this->bioeffects_.calciteVolumeFraction[globalDofIdx];
957 }
958 }
959
960 values.checkDefined();
961 }
962
963
964 Scalar drsdtcon(unsigned elemIdx, int episodeIdx) const
965 {
966 return this->mixControls_.drsdtcon(elemIdx, episodeIdx,
967 this->pvtRegionIndex(elemIdx));
968 }
969
970 bool drsdtconIsActive(unsigned elemIdx, int episodeIdx) const
971 {
972 return this->mixControls_.drsdtConvective(episodeIdx, this->pvtRegionIndex(elemIdx));
973 }
974
980 template <class Context>
981 void boundary(BoundaryRateVector& values,
982 const Context& context,
983 unsigned spaceIdx,
984 unsigned timeIdx) const
985 {
986 OPM_TIMEBLOCK_LOCAL(eclProblemBoundary, Subsystem::Assembly);
987 if (!context.intersection(spaceIdx).boundary())
988 return;
989
990 if constexpr (energyModuleType != EnergyModules::FullyImplicitThermal || !enableThermalFluxBoundaries)
991 values.setNoFlow();
992 else {
993 // in the energy case we need to specify a non-trivial boundary condition
994 // because the geothermal gradient needs to be maintained. for this, we
995 // simply assume the initial temperature at the boundary and specify the
996 // thermal flow accordingly. in this context, "thermal flow" means energy
997 // flow due to a temerature gradient while assuming no-flow for mass
998 unsigned interiorDofIdx = context.interiorScvIndex(spaceIdx, timeIdx);
999 unsigned globalDofIdx = context.globalSpaceIndex(interiorDofIdx, timeIdx);
1000 values.setThermalFlow(context, spaceIdx, timeIdx, this->initialFluidStates_[globalDofIdx] );
1001 }
1002
1003 if (this->nonTrivialBoundaryConditions()) {
1004 unsigned indexInInside = context.intersection(spaceIdx).indexInInside();
1005 unsigned interiorDofIdx = context.interiorScvIndex(spaceIdx, timeIdx);
1006 unsigned globalDofIdx = context.globalSpaceIndex(interiorDofIdx, timeIdx);
1007 unsigned pvtRegionIdx = pvtRegionIndex(context, spaceIdx, timeIdx);
1008 const auto [type, massrate] = this->boundaryCondition(globalDofIdx, indexInInside);
1009 if (type == BCType::THERMAL)
1010 values.setThermalFlow(context, spaceIdx, timeIdx, this->boundaryFluidState(globalDofIdx, indexInInside));
1011 else if (type == BCType::FREE || type == BCType::DIRICHLET)
1012 values.setFreeFlow(context, spaceIdx, timeIdx, this->boundaryFluidState(globalDofIdx, indexInInside));
1013 else if (type == BCType::RATE)
1014 values.setMassRate(massrate, pvtRegionIdx);
1015 }
1016 }
1017
1022 void readSolutionFromOutputModule(const int restart_step, bool fip_init)
1023 {
1024 auto& simulator = this->simulator();
1025 const auto& eclState = simulator.vanguard().eclState();
1026
1027 std::size_t numElems = this->model().numGridDof();
1028 this->initialFluidStates_.resize(numElems);
1029 if constexpr (enableSolvent) {
1030 this->solventSaturation_.resize(numElems, 0.0);
1031 this->solventRsw_.resize(numElems, 0.0);
1032 }
1033
1034 if constexpr (enablePolymer)
1035 this->polymer_.concentration.resize(numElems, 0.0);
1036
1037 if constexpr (enablePolymerMolarWeight) {
1038 const std::string msg {"Support of the RESTART for polymer molecular weight "
1039 "is not implemented yet. The polymer weight value will be "
1040 "zero when RESTART begins"};
1041 OpmLog::warning("NO_POLYMW_RESTART", msg);
1042 this->polymer_.moleWeight.resize(numElems, 0.0);
1043 }
1044
1045 if constexpr (enableBioeffects) {
1046 this->bioeffects_.resize(numElems);
1047 }
1048
1049 // Initialize mixing controls before trying to set any lastRx valuesx
1050 this->mixControls_.init(numElems, restart_step, eclState.runspec().tabdims().getNumPVTTables());
1051
1052 if constexpr (enableBioeffects) {
1053 this->bioeffects_ = this->eclWriter_->outputModule().getBioeffects().getSolution();
1054 }
1055
1056 for (std::size_t elemIdx = 0; elemIdx < numElems; ++elemIdx) {
1057 auto& elemFluidState = this->initialFluidStates_[elemIdx];
1058 elemFluidState.setPvtRegionIndex(pvtRegionIndex(elemIdx));
1059 this->eclWriter_->outputModule().initHysteresisParams(simulator, elemIdx);
1060 this->eclWriter_->outputModule().assignToFluidState(elemFluidState, elemIdx);
1061
1062 // Note: Function processRestartSaturations_() mutates the
1063 // 'ssol' argument--the value from the restart file--if solvent
1064 // is enabled. Then, store the updated solvent saturation into
1065 // 'solventSaturation_'. Otherwise, just pass a dummy value to
1066 // the function and discard the unchanged result. Do not index
1067 // into 'solventSaturation_' unless solvent is enabled.
1068 {
1069 auto ssol = enableSolvent
1070 ? this->eclWriter_->outputModule().getSolventSaturation(elemIdx)
1071 : Scalar(0);
1072
1073 this->processRestartSaturations_(elemFluidState, ssol);
1074
1075 if constexpr (enableSolvent) {
1076 this->solventSaturation_[elemIdx] = ssol;
1077 this->solventRsw_[elemIdx] = this->eclWriter_->outputModule().getSolventRsw(elemIdx);
1078 }
1079 }
1080
1081 // For CO2STORE, H2STORE, CO2SOL and H2SOL we need to set the initial temperature
1082 // for isothermal simulations
1083 if constexpr (energyModuleType != EnergyModules::NoTemperature) {
1084 const auto& rspec = eclState.runspec();
1085 bool needTemperature = rspec.co2Storage() || rspec.h2Storage()
1086 || rspec.co2Sol() || rspec.h2Sol();
1087 if (needTemperature) {
1088 const auto& fp = simulator.vanguard().eclState().fieldProps();
1089 elemFluidState.setTemperature(fp.get_double("TEMPI")[elemIdx]);
1090 }
1091 }
1092
1093 this->mixControls_.updateLastValues(elemIdx, elemFluidState.Rs(), elemFluidState.Rv());
1094
1095 if constexpr (enablePolymer)
1096 this->polymer_.concentration[elemIdx] = this->eclWriter_->outputModule().getPolymerConcentration(elemIdx);
1097 // if we need to restart for polymer molecular weight simulation, we need to add related here
1098 }
1099
1100 const int episodeIdx = this->episodeIndex();
1101 this->mixControls_.updateMaxValues(episodeIdx, simulator.timeStepSize());
1102
1103 // assign the restart solution to the current solution. note that we still need
1104 // to compute real initial solution after this because the initial fluid states
1105 // need to be correct for stuff like boundary conditions.
1106 auto& sol = this->model().solution(/*timeIdx=*/0);
1107 const auto& gridView = this->gridView();
1108 ElementContext elemCtx(simulator);
1109 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
1110 elemCtx.updatePrimaryStencil(elem);
1111 int elemIdx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
1112 this->initial(sol[elemIdx], elemCtx, /*spaceIdx=*/0, /*timeIdx=*/0);
1113 }
1114
1115 // make sure that the ghost and overlap entities exhibit the correct
1116 // solution. alternatively, this could be done in the loop above by also
1117 // considering non-interior elements. Since the initial() method might not work
1118 // 100% correctly for such elements, let's play safe and explicitly synchronize
1119 // using message passing.
1120 this->model().syncOverlap();
1121
1122 if (fip_init) {
1123 this->updateReferencePorosity_();
1124 this->mixControls_.init(this->model().numGridDof(),
1125 this->episodeIndex(),
1126 eclState.runspec().tabdims().getNumPVTTables());
1127 }
1128 }
1129
1130 template<class Serializer>
1131 void serializeOp(Serializer& serializer)
1132 {
1133 serializer(static_cast<FlowProblemType&>(*this));
1134 serializer(mixControls_);
1135 serializer(*eclWriter_);
1136 }
1137
1138protected:
1141 {
1142 FlowProblemType::captureBeginTimeStepState_();
1143 prev_timestep_state_.mixControls = mixControls_;
1144 }
1145
1148 {
1149 FlowProblemType::restoreBeginTimeStepState_();
1150 mixControls_ = prev_timestep_state_.mixControls;
1151 }
1152
1153 void updateExplicitQuantities_(int episodeIdx, int timeStepSize, const bool first_step_after_restart) override
1154 {
1155 this->updateExplicitQuantities_(first_step_after_restart);
1156
1157 if constexpr (getPropValue<TypeTag, Properties::EnablePolymer>())
1158 updateMaxPolymerAdsorption_();
1159
1160 mixControls_.updateExplicitQuantities(episodeIdx, timeStepSize);
1161 }
1162
1164 {
1165 // we need to update the max polymer adsoption data for all elements
1166 this->updateProperty_("FlowProblemBlackoil::updateMaxPolymerAdsorption_() failed:",
1167 [this](unsigned compressedDofIdx, const IntensiveQuantities& iq)
1168 {
1169 this->updateMaxPolymerAdsorption_(compressedDofIdx,iq);
1170 });
1171 }
1172
1173 bool updateMaxPolymerAdsorption_(unsigned compressedDofIdx, const IntensiveQuantities& iq)
1174 {
1175 const Scalar pa = scalarValue(iq.polymerAdsorption());
1176 auto& mpa = this->polymer_.maxAdsorption;
1177 if (mpa[compressedDofIdx] < pa) {
1178 mpa[compressedDofIdx] = pa;
1179 return true;
1180 } else {
1181 return false;
1182 }
1183 }
1184
1186 {
1187 std::vector<Scalar> sumInvB(numPhases, 0.0);
1188 const auto& gridView = this->gridView();
1189 ElementContext elemCtx(this->simulator());
1190 for(const auto& elem: elements(gridView, Dune::Partitions::interior)) {
1191 elemCtx.updatePrimaryStencil(elem);
1192 int elemIdx = elemCtx.globalSpaceIndex(/*spaceIdx=*/0, /*timeIdx=*/0);
1193 const auto& dofFluidState = this->initialFluidStates_[elemIdx];
1194 for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1195 if (!FluidSystem::phaseIsActive(phaseIdx))
1196 continue;
1197
1198 sumInvB[phaseIdx] += dofFluidState.invB(phaseIdx);
1199 }
1200 }
1201
1202 std::size_t numDof = this->model().numGridDof();
1203 const auto& comm = this->simulator().vanguard().grid().comm();
1204 comm.sum(sumInvB.data(),sumInvB.size());
1205 Scalar numTotalDof = comm.sum(numDof);
1206
1207 for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1208 if (!FluidSystem::phaseIsActive(phaseIdx))
1209 continue;
1210
1211 Scalar avgB = numTotalDof / sumInvB[phaseIdx];
1212 const unsigned solventCompIdx = FluidSystem::solventComponentIndex(phaseIdx);
1213 const unsigned activeSolventCompIdx = FluidSystem::canonicalToActiveCompIdx(solventCompIdx);
1214 this->model().setEqWeight(activeSolventCompIdx, avgB);
1215 }
1216 }
1217
1218 // update the parameters needed for DRSDT and DRVDT
1220 {
1221 OPM_TIMEBLOCK(updateCompositionChangeLimits);
1222 // update the "last Rs" values for all elements, including the ones in the ghost
1223 // and overlap regions
1224 int episodeIdx = this->episodeIndex();
1225 std::array<bool,3> active{this->mixControls_.drsdtConvective(episodeIdx),
1226 this->mixControls_.drsdtActive(episodeIdx),
1227 this->mixControls_.drvdtActive(episodeIdx)};
1228 if (!active[0] && !active[1] && !active[2]) {
1229 return false;
1230 }
1231
1232 this->updateProperty_("FlowProblemBlackoil::updateCompositionChangeLimits_()) failed:",
1233 [this,episodeIdx,active](unsigned compressedDofIdx,
1234 const IntensiveQuantities& iq)
1235 {
1236 const DimMatrix& perm = this->intrinsicPermeability(compressedDofIdx);
1237 const Scalar distZ = active[0] ? this->simulator().vanguard().cellThickness(compressedDofIdx) : 0.0;
1238 const int pvtRegionIdx = this->pvtRegionIndex(compressedDofIdx);
1239 this->mixControls_.update(compressedDofIdx,
1240 iq,
1241 episodeIdx,
1242 this->gravity_[dim - 1],
1243 perm[dim - 1][dim - 1],
1244 distZ,
1245 pvtRegionIdx);
1246 }
1247 );
1248
1249 return true;
1250 }
1251
1253 {
1254 // Throw an exception if the grid has LGRs. Refined grid are not supported for restart.
1255 if(this->simulator().vanguard().grid().maxLevel() > 0) {
1256 throw std::invalid_argument("Refined grids are not yet supported for restart ");
1257 }
1258
1259 // Set the start time of the simulation
1260 auto& simulator = this->simulator();
1261 const auto& schedule = simulator.vanguard().schedule();
1262 const auto& eclState = simulator.vanguard().eclState();
1263 const auto& initconfig = eclState.getInitConfig();
1264 const int restart_step = initconfig.getRestartStep();
1265 {
1266 simulator.setTime(schedule.seconds(restart_step));
1267
1268 simulator.startNextEpisode(simulator.startTime() + simulator.time(),
1269 schedule.stepLength(restart_step));
1270 simulator.setEpisodeIndex(restart_step);
1271 }
1272 this->eclWriter_->beginRestart();
1273
1274 Scalar dt = std::min(this->eclWriter_->restartTimeStepSize(), simulator.episodeLength());
1275 simulator.setTimeStepSize(dt);
1276
1277 this->readSolutionFromOutputModule(restart_step, false);
1278
1279 this->eclWriter_->endRestart();
1280 }
1281
1283 {
1284 const auto& simulator = this->simulator();
1285
1286 // initial condition corresponds to hydrostatic conditions.
1287 EquilInitializer<TypeTag> equilInitializer(simulator, *(this->materialLawManager_));
1288
1289 std::size_t numElems = this->model().numGridDof();
1290 this->initialFluidStates_.resize(numElems);
1291 for (std::size_t elemIdx = 0; elemIdx < numElems; ++elemIdx) {
1292 auto& elemFluidState = this->initialFluidStates_[elemIdx];
1293 elemFluidState.assign(equilInitializer.initialFluidState(elemIdx));
1294 }
1295 }
1296
1298 {
1299 const auto& simulator = this->simulator();
1300 const auto& vanguard = simulator.vanguard();
1301 const auto& eclState = vanguard.eclState();
1302 const auto& fp = eclState.fieldProps();
1303 bool has_swat = fp.has_double("SWAT");
1304 bool has_sgas = fp.has_double("SGAS");
1305 bool has_rs = fp.has_double("RS");
1306 bool has_rsw = fp.has_double("RSW");
1307 bool has_rv = fp.has_double("RV");
1308 bool has_rvw = fp.has_double("RVW");
1309 bool has_pressure = fp.has_double("PRESSURE");
1310 bool has_salt = fp.has_double("SALT");
1311 bool has_saltp = fp.has_double("SALTP");
1312
1313 // make sure all required quantities are enables
1314 if (Indices::numPhases > 1) {
1315 if (FluidSystem::phaseIsActive(waterPhaseIdx) && !has_swat)
1316 throw std::runtime_error("The ECL input file requires the presence of the SWAT keyword if "
1317 "the water phase is active");
1318 if (FluidSystem::phaseIsActive(gasPhaseIdx) && !has_sgas && FluidSystem::phaseIsActive(oilPhaseIdx))
1319 throw std::runtime_error("The ECL input file requires the presence of the SGAS keyword if "
1320 "the gas phase is active");
1321 }
1322 if (!has_pressure)
1323 throw std::runtime_error("The ECL input file requires the presence of the PRESSURE "
1324 "keyword if the model is initialized explicitly");
1325 if (FluidSystem::enableDissolvedGas() && !has_rs)
1326 throw std::runtime_error("The ECL input file requires the RS keyword to be present if"
1327 " dissolved gas is enabled and the model is initialized explicitly");
1328 if (FluidSystem::enableDissolvedGasInWater() && !has_rsw)
1329 OpmLog::warning("The model is initialized explicitly and the RSW keyword is not present in the"
1330 " ECL input file. The RSW values are set equal to 0");
1331 if (FluidSystem::enableVaporizedOil() && !has_rv)
1332 throw std::runtime_error("The ECL input file requires the RV keyword to be present if"
1333 " vaporized oil is enabled and the model is initialized explicitly");
1334 if (FluidSystem::enableVaporizedWater() && !has_rvw)
1335 throw std::runtime_error("The ECL input file requires the RVW keyword to be present if"
1336 " vaporized water is enabled and the model is initialized explicitly");
1337 if (enableBrine && !has_salt)
1338 throw std::runtime_error("The ECL input file requires the SALT keyword to be present if"
1339 " brine is enabled and the model is initialized explicitly");
1340 if (enableSaltPrecipitation && !has_saltp)
1341 throw std::runtime_error("The ECL input file requires the SALTP keyword to be present if"
1342 " salt precipitation is enabled and the model is initialized explicitly");
1343
1344 std::size_t numDof = this->model().numGridDof();
1345
1346 initialFluidStates_.resize(numDof);
1347
1348 std::vector<double> waterSaturationData;
1349 std::vector<double> gasSaturationData;
1350 std::vector<double> pressureData;
1351 std::vector<double> rsData;
1352 std::vector<double> rswData;
1353 std::vector<double> rvData;
1354 std::vector<double> rvwData;
1355 std::vector<double> tempiData;
1356 std::vector<double> saltData;
1357 std::vector<double> saltpData;
1358
1359 if (FluidSystem::phaseIsActive(waterPhaseIdx) && Indices::numPhases > 1)
1360 waterSaturationData = fp.get_double("SWAT");
1361 else
1362 waterSaturationData.resize(numDof);
1363
1364 if (FluidSystem::phaseIsActive(gasPhaseIdx) && FluidSystem::phaseIsActive(oilPhaseIdx))
1365 gasSaturationData = fp.get_double("SGAS");
1366 else
1367 gasSaturationData.resize(numDof);
1368
1369 pressureData = fp.get_double("PRESSURE");
1370 if (FluidSystem::enableDissolvedGas())
1371 rsData = fp.get_double("RS");
1372
1373 if (FluidSystem::enableDissolvedGasInWater() && has_rsw)
1374 rswData = fp.get_double("RSW");
1375
1376 if (FluidSystem::enableVaporizedOil())
1377 rvData = fp.get_double("RV");
1378
1379 if (FluidSystem::enableVaporizedWater())
1380 rvwData = fp.get_double("RVW");
1381
1382 // initial reservoir temperature
1383 tempiData = fp.get_double("TEMPI");
1384
1385 // initial salt concentration data
1386 if constexpr (enableBrine)
1387 saltData = fp.get_double("SALT");
1388
1389 // initial precipitated salt saturation data
1390 if constexpr (enableSaltPrecipitation)
1391 saltpData = fp.get_double("SALTP");
1392
1393 // calculate the initial fluid states
1394 for (std::size_t dofIdx = 0; dofIdx < numDof; ++dofIdx) {
1395 auto& dofFluidState = initialFluidStates_[dofIdx];
1396
1397 dofFluidState.setPvtRegionIndex(pvtRegionIndex(dofIdx));
1398
1400 // set temperature
1402 if constexpr (energyModuleType != EnergyModules::NoTemperature) {
1403 Scalar temperatureLoc = tempiData[dofIdx];
1404 if (!std::isfinite(temperatureLoc) || temperatureLoc <= 0)
1405 temperatureLoc = FluidSystem::surfaceTemperature;
1406 dofFluidState.setTemperature(temperatureLoc);
1407 }
1408
1410 // set salt concentration
1412 if constexpr (enableBrine)
1413 dofFluidState.setSaltConcentration(saltData[dofIdx]);
1414
1416 // set precipitated salt saturation
1418 if constexpr (enableSaltPrecipitation)
1419 dofFluidState.setSaltSaturation(saltpData[dofIdx]);
1420
1422 // set saturations
1424 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx))
1425 dofFluidState.setSaturation(FluidSystem::waterPhaseIdx,
1426 waterSaturationData[dofIdx]);
1427
1428 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)){
1429 if (!FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)){
1430 dofFluidState.setSaturation(FluidSystem::gasPhaseIdx,
1431 1.0
1432 - waterSaturationData[dofIdx]);
1433 }
1434 else
1435 dofFluidState.setSaturation(FluidSystem::gasPhaseIdx,
1436 gasSaturationData[dofIdx]);
1437 }
1438 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1439 const Scalar soil = 1.0 - waterSaturationData[dofIdx] - gasSaturationData[dofIdx];
1440 if (soil < smallSaturationTolerance_) {
1441 dofFluidState.setSaturation(FluidSystem::oilPhaseIdx, 0.0);
1442 }
1443 else {
1444 dofFluidState.setSaturation(FluidSystem::oilPhaseIdx, soil);
1445 }
1446 }
1447
1449 // set phase pressures
1451 Scalar pressure = pressureData[dofIdx]; // oil pressure (or gas pressure for water-gas system or water pressure for single phase)
1452
1453 // this assumes that capillary pressures only depend on the phase saturations
1454 // and possibly on temperature. (this is always the case for ECL problems.)
1455 std::array<Scalar, numPhases> pc = {0};
1456 const auto& matParams = this->materialLawParams(dofIdx);
1457 MaterialLaw::capillaryPressures(pc, matParams, dofFluidState);
1458 Valgrind::CheckDefined(pressure);
1459 Valgrind::CheckDefined(pc);
1460 for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1461 if (!FluidSystem::phaseIsActive(phaseIdx))
1462 continue;
1463
1464 if (Indices::oilEnabled)
1465 dofFluidState.setPressure(phaseIdx, pressure + (pc[phaseIdx] - pc[oilPhaseIdx]));
1466 else if (Indices::gasEnabled)
1467 dofFluidState.setPressure(phaseIdx, pressure + (pc[phaseIdx] - pc[gasPhaseIdx]));
1468 else if (Indices::waterEnabled)
1469 //single (water) phase
1470 dofFluidState.setPressure(phaseIdx, pressure);
1471 }
1472
1473 if constexpr (enableDissolvedGas) {
1474 if (FluidSystem::enableDissolvedGas())
1475 dofFluidState.setRs(rsData[dofIdx]);
1476 else if (Indices::gasEnabled && Indices::oilEnabled)
1477 dofFluidState.setRs(0.0);
1478 if (FluidSystem::enableVaporizedOil())
1479 dofFluidState.setRv(rvData[dofIdx]);
1480 else if (Indices::gasEnabled && Indices::oilEnabled)
1481 dofFluidState.setRv(0.0);
1482 }
1483
1484 if constexpr (enableDisgasInWater) {
1485 if (FluidSystem::enableDissolvedGasInWater() && has_rsw)
1486 dofFluidState.setRsw(rswData[dofIdx]);
1487 }
1488
1489 if constexpr (enableVapwat) {
1490 if (FluidSystem::enableVaporizedWater())
1491 dofFluidState.setRvw(rvwData[dofIdx]);
1492 }
1493
1495 // set invB_
1497 for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1498 if (!FluidSystem::phaseIsActive(phaseIdx))
1499 continue;
1500
1501 const auto& b = FluidSystem::inverseFormationVolumeFactor(dofFluidState, phaseIdx, pvtRegionIndex(dofIdx));
1502 dofFluidState.setInvB(phaseIdx, b);
1503
1504 const auto& rho = FluidSystem::density(dofFluidState, phaseIdx, pvtRegionIndex(dofIdx));
1505 dofFluidState.setDensity(phaseIdx, rho);
1506
1507 }
1508 }
1509 }
1510
1511
1512 void processRestartSaturations_(InitialFluidState& elemFluidState, Scalar& solventSaturation)
1513 {
1514 // each phase needs to be above certain value to be claimed to be existing
1515 // this is used to recover some RESTART running with the defaulted single-precision format
1516 Scalar sumSaturation = 0.0;
1517 for (std::size_t phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1518 if (FluidSystem::phaseIsActive(phaseIdx)) {
1519 if (elemFluidState.saturation(phaseIdx) < smallSaturationTolerance_)
1520 elemFluidState.setSaturation(phaseIdx, 0.0);
1521
1522 sumSaturation += elemFluidState.saturation(phaseIdx);
1523 }
1524
1525 }
1526 if constexpr (enableSolvent) {
1527 if (solventSaturation < smallSaturationTolerance_)
1528 solventSaturation = 0.0;
1529
1530 sumSaturation += solventSaturation;
1531 }
1532
1533 assert(sumSaturation > 0.0);
1534
1535 for (std::size_t phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1536 if (FluidSystem::phaseIsActive(phaseIdx)) {
1537 const Scalar saturation = elemFluidState.saturation(phaseIdx) / sumSaturation;
1538 elemFluidState.setSaturation(phaseIdx, saturation);
1539 }
1540 }
1541 if constexpr (enableSolvent) {
1542 solventSaturation = solventSaturation / sumSaturation;
1543 }
1544 }
1545
1547 {
1548 FlowProblemType::readInitialCondition_();
1549
1550 if constexpr (enableSolvent || enablePolymer || enablePolymerMolarWeight || enableBioeffects)
1551 this->readBlackoilExtentionsInitialConditions_(this->model().numGridDof(),
1552 enableSolvent,
1553 enablePolymer,
1554 enablePolymerMolarWeight,
1555 enableBioeffects,
1556 enableMICP);
1557
1558 }
1559
1560 void handleSolventBC(const BCState::BCFace& bc, RateVector& rate) const override
1561 {
1562 if constexpr (!enableSolvent)
1563 throw std::logic_error("solvent is disabled and you're trying to add solvent to BC");
1564
1565 rate[Indices::solventSaturationIdx] = bc.rate;
1566 }
1567
1568 void handlePolymerBC(const BCState::BCFace& bc, RateVector& rate) const override
1569 {
1570 if constexpr (!enablePolymer)
1571 throw std::logic_error("polymer is disabled and you're trying to add polymer to BC");
1572
1573 rate[Indices::polymerConcentrationIdx] = bc.rate;
1574 }
1575
1576 void handleMicrBC(const BCState::BCFace& bc, RateVector& rate) const override
1577 {
1578 if constexpr (!enableMICP)
1579 throw std::logic_error("MICP is disabled and you're trying to add microbes to BC");
1580
1581 rate[Indices::microbialConcentrationIdx] = bc.rate;
1582 }
1583
1584 void handleOxygBC(const BCState::BCFace& bc, RateVector& rate) const override
1585 {
1586 if constexpr (!enableMICP)
1587 throw std::logic_error("MICP is disabled and you're trying to add oxygen to BC");
1588
1589 rate[Indices::oxygenConcentrationIdx] = bc.rate;
1590 }
1591
1592 void handleUreaBC(const BCState::BCFace& bc, RateVector& rate) const override
1593 {
1594 if constexpr (!enableMICP)
1595 throw std::logic_error("MICP is disabled and you're trying to add urea to BC");
1596
1597 rate[Indices::ureaConcentrationIdx] = bc.rate;
1598 // since the urea concentration can be much larger than 1, then we apply a scaling factor
1599 rate[Indices::ureaConcentrationIdx] *= getPropValue<TypeTag, Properties::BlackOilUreaScalingFactor>();
1600 }
1601
1602 void updateExplicitQuantities_(const bool first_step_after_restart)
1603 {
1604 OPM_TIMEBLOCK(updateExplicitQuantities);
1605 const bool invalidateFromMaxWaterSat = this->updateMaxWaterSaturation_();
1606 const bool invalidateFromMinPressure = this->updateMinPressure_();
1607
1608 // update hysteresis and max oil saturation used in vappars
1609 const bool invalidateFromHyst = this->updateHysteresis_();
1610 const bool invalidateFromMaxOilSat = this->updateMaxOilSaturation_();
1611
1612 // deal with DRSDT and DRVDT
1613 const bool invalidateDRDT = !first_step_after_restart && this->updateCompositionChangeLimits_();
1614
1615 // the derivatives may have changed
1616 const bool invalidateIntensiveQuantities
1617 = invalidateFromMaxWaterSat || invalidateFromMinPressure || invalidateFromHyst || invalidateFromMaxOilSat || invalidateDRDT;
1618 if (invalidateIntensiveQuantities) {
1619 OPM_TIMEBLOCK(beginTimeStepInvalidateIntensiveQuantities);
1620 this->model().invalidateAndUpdateIntensiveQuantities(/*timeIdx=*/0);
1621 }
1622
1623 this->updateRockCompTransMultVal_();
1624 }
1625
1626 // Driving pressure difference, from the aquifer cell to the connected
1627 // cell, of largest magnitude among the phases which flow across the
1628 // connection in the initial solution. The pressure differences,
1629 // including threshold pressures, and the (directional) upstream
1630 // mobilities are evaluated as in the flux assembly. A phase which is
1631 // absent in the upstream cell is not considered to flow. Zero if no
1632 // phase flows.
1634 const unsigned aquIdx,
1635 const FaceDir::DirEnum faceDir) const
1636 {
1639
1640 const auto& model = this->model();
1641 const auto& iqCell = model.intensiveQuantities(cellIdx, /*timeIdx=*/0);
1642 const auto& iqAqu = model.intensiveQuantities(aquIdx, /*timeIdx=*/0);
1643
1644 const Scalar distZg = (this->dofCenterDepth(cellIdx) - this->dofCenterDepth(aquIdx))
1645 * this->gravity_[dim - 1];
1646 const Scalar thpresCellToAqu = this->thresholdPressure(cellIdx, aquIdx);
1647 const Scalar thpresAquToCell = this->thresholdPressure(aquIdx, cellIdx);
1648
1649 Scalar largest = 0.0;
1650 for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) {
1651 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1652 continue;
1653 }
1654
1655 constexpr unsigned cellLocalIdx = 0;
1656 constexpr unsigned aquLocalIdx = 1;
1657 short upIdx = cellLocalIdx;
1658 short dnIdx = aquLocalIdx;
1659 Evaluation pressureDifference = 0.0;
1660 ExtensiveQuantities::calculatePhasePressureDiff_(upIdx, dnIdx, pressureDifference,
1661 iqCell, iqAqu, phaseIdx,
1662 cellLocalIdx, aquLocalIdx,
1663 model.dofTotalVolume(cellIdx),
1664 model.dofTotalVolume(aquIdx),
1665 cellIdx, aquIdx, distZg,
1666 thpresCellToAqu, thpresAquToCell,
1667 this->moduleParams());
1668
1669 // pressureDifference is positive for flow from the aquifer cell.
1670 const Scalar dp = getValue(pressureDifference);
1671 const auto& up = (upIdx == static_cast<short>(cellLocalIdx)) ? iqCell : iqAqu;
1672 if (dp != 0.0 &&
1673 getValue(up.fluidState().saturation(phaseIdx)) > 0.0 &&
1674 getValue(up.mobility(phaseIdx, faceDir)) > 0.0 &&
1675 std::abs(dp) > std::abs(largest))
1676 {
1677 largest = dp;
1678 }
1679 }
1680 return largest;
1681 }
1682
1683 // Stops the simulation, unless explicitly allowed, if fluid flows
1684 // initially through numerical aquifers between cells of different
1685 // equilibration regions.
1687 {
1688 const auto& vanguard = this->simulator().vanguard();
1689 const auto& eclState = vanguard.eclState();
1690 if (!eclState.aquifer().hasNumericalAquifer() ||
1691 !eclState.fieldProps().has_int("EQLNUM"))
1692 {
1693 return;
1694 }
1695
1696 std::unordered_map<std::size_t, std::size_t> aquiferOfCell;
1697 for (const auto& [cartIdx, cell] : eclState.aquifer().numericalAquifers().allAquiferCells()) {
1698 aquiferOfCell.emplace(cartIdx, cell->aquifer_id);
1699 }
1700
1701 const auto eqlnum = this->lookUpData_.template
1702 assignFieldPropsIntOnLeaf<int>(eclState.fieldProps(), "EQLNUM", /*needsTranslation=*/false);
1703
1704 // Each connection to an aquifer cell is visited from the interior
1705 // cell on the other side, and connections between two aquifer
1706 // cells from the cell with the lower Cartesian index.
1707 std::vector<NumericalAquiferEquilibrationMismatch> mismatches;
1708 const auto& gridView = this->gridView();
1709 for (const auto& elem : elements(gridView, Dune::Partitions::interior)) {
1710 const unsigned cellIdx = this->elementMapper().index(elem);
1711 const auto cellCart = vanguard.cartesianIndex(cellIdx);
1712 const bool cellIsAquifer = aquiferOfCell.contains(cellCart);
1713 for (const auto& intersection : intersections(gridView, elem)) {
1714 if (!intersection.neighbor()) {
1715 continue;
1716 }
1717 const unsigned aquIdx = this->elementMapper().index(intersection.outside());
1718 const auto aquCart = vanguard.cartesianIndex(aquIdx);
1719 const auto aquifer = aquiferOfCell.find(aquCart);
1720 if (aquifer == aquiferOfCell.end() ||
1721 (cellIsAquifer && cellCart > aquCart) ||
1722 eqlnum[aquIdx] == eqlnum[cellIdx] ||
1723 !(this->transmissibility(cellIdx, aquIdx) > 0.0))
1724 {
1725 continue;
1726 }
1727
1728 // Same face direction as in the flux assembly (ecfvstencil).
1729 const int dirId = intersection.indexInInside();
1730 const auto faceDir = (dirId < 0) ? FaceDir::DirEnum::Unknown
1731 : FaceDir::FromIntersectionIndex(dirId);
1732
1733 const Scalar dp = this->initialFlowPressureDifference_(cellIdx, aquIdx, faceDir);
1734 if (std::abs(dp) > numericalAquiferEquilibrationTolerance) {
1735 mismatches.push_back({aquifer->second, eqlnum[aquIdx], eqlnum[cellIdx], dp});
1736 }
1737 }
1738 }
1739
1740 checkNumericalAquiferEquilibration(mismatches, eclState, vanguard.grid().comm(),
1741 Parameters::Get<Parameters::AllowInconsistentAquiferEquilibration>());
1742 }
1743
1745 {
1746 if (const auto nph = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
1747 + FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)
1748 + FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
1749 nph < 2)
1750 {
1751 // Single phase runs don't need saturation functions and there's
1752 // nothing to do here. Return 'true' to tell caller that the
1753 // consistency requirements are Met.
1754 return true;
1755 }
1756
1757 const auto numSamplePoints = static_cast<std::size_t>
1758 (Parameters::Get<Parameters::NumSatfuncConsistencySamplePoints>());
1759
1760 auto sfuncConsistencyChecks =
1762 numSamplePoints, this->simulator().vanguard().eclState(),
1763 [&cmap = this->simulator().vanguard().cartesianIndexMapper()](const int elemIdx)
1764 { return cmap.cartesianIndex(elemIdx); }
1765 };
1766
1767 const auto ioRank = 0;
1768 const auto isIoRank = this->simulator().vanguard()
1769 .grid().comm().rank() == ioRank;
1770
1771 // Note: Run saturation function consistency checks on main grid
1772 // only (i.e., levelGridView(0)). These checks are not supported
1773 // for LGRs at this time.
1774 sfuncConsistencyChecks.collectFailuresTo(ioRank)
1775 .run(this->simulator().vanguard().grid().levelGridView(0),
1776 [&vg = this->simulator().vanguard(),
1777 &emap = this->simulator().model().elementMapper()]
1778 (const auto& elem)
1779 { return vg.gridIdxToEquilGridIdx(emap.index(elem)); });
1780
1781 using ViolationLevel = typename Satfunc::PhaseChecks::
1783
1784 auto reportFailures = [&sfuncConsistencyChecks]
1785 (const ViolationLevel level)
1786 {
1787 sfuncConsistencyChecks.reportFailures
1788 (level, [](std::string_view record)
1789 { OpmLog::info(std::string { record }); });
1790 };
1791
1792 if (sfuncConsistencyChecks.anyFailedStandardChecks()) {
1793 if (isIoRank) {
1794 OpmLog::warning("Saturation Function "
1795 "End-point Consistency Problems");
1796
1797 reportFailures(ViolationLevel::Standard);
1798 }
1799 }
1800
1801 if (sfuncConsistencyChecks.anyFailedCriticalChecks()) {
1802 if (isIoRank) {
1803 OpmLog::error("Saturation Function "
1804 "End-point Consistency Failures");
1805
1806 reportFailures(ViolationLevel::Critical);
1807 }
1808
1809 // There are "critical" check failures. Report that consistency
1810 // requirements are not Met.
1811 return false;
1812 }
1813
1814 // If we get here then there are no critical failures. Report
1815 // Met = true, i.e., that the consistency requirements ARE met.
1816 return true;
1817 }
1818
1819 std::vector<InitialFluidState> initialFluidStates_;
1820
1822 std::unique_ptr<EclWriterType> eclWriter_;
1823
1824 const Scalar smallSaturationTolerance_ = 1.e-6;
1825#if HAVE_DAMARIS
1826 bool enableDamarisOutput_ = false ;
1827 std::unique_ptr<DamarisWriterType> damarisWriter_;
1828#endif
1830
1831 // Whether to check numerical aquifers for initial flow between
1832 // equilibration regions once the initial solution has been applied.
1833 bool checkAquiferEquilibration_{false};
1834
1838 {
1839 explicit PrevTimestepState(const Schedule& schedule)
1840 : mixControls(schedule)
1841 {}
1842
1844 };
1845
1847
1849
1851
1852private:
1853 void checkGpuAssemblySchedule_() const
1854 {
1855 if constexpr (getPropValue<TypeTag, Properties::RunAssemblyOnGpu>()) {
1856 // Persistent GPU assembly buffers do not refresh these coefficients.
1857 // This restriction also applies when the assembly/solver bridge is off.
1858 const auto& state = this->simulator().vanguard().schedule()[this->episodeIndex()];
1859 if (state.events().hasEvent(ScheduleEvents::GEO_MODIFIER)) {
1860 OPM_THROW(std::runtime_error,
1861 "GPU assembly does not support GEO_MODIFIER schedule events.");
1862 }
1863 if (state.oilvap().getType() == OilVaporizationProperties::OilVaporization::DRSDTCON) {
1864 OPM_THROW(std::runtime_error, "GPU assembly does not support DRSDTCON.");
1865 }
1866 }
1867 }
1868
1879 bool episodeWillBeOver() const override
1880 {
1881 const auto currTime = this->simulator().time()
1882 + this->simulator().timeStepSize();
1883
1884 const auto nextReportStep =
1885 this->simulator().vanguard().schedule()
1886 .seconds(this->simulator().episodeIndex() + 1);
1887
1888 const auto isSubStep = (nextReportStep - currTime)
1889 > (2 * std::numeric_limits<float>::epsilon()) * nextReportStep;
1890
1891 return !isSubStep;
1892 }
1893};
1894
1895} // namespace Opm
1896
1897#endif // OPM_FLOW_PROBLEM_BLACK_HPP
Contains classes extending the black-oil model. \detail This file holds dummy definitions,...
Class handling Action support in simulator.
Definition: ActionHandler.hpp:52
Provides the auxiliary methods required for consideration of the diffusion equation.
Provides the auxiliary methods required for consideration of the dispersion equation.
Hybrid Newton solver extension for the black-oil model.
Definition: HybridNewton.hpp:60
void tryApplyHybridNewton()
Attempt to apply the Hybrid Newton correction at the current timestep.
Definition: HybridNewton.hpp:101
Collects necessary output values and pass it to opm-common's ECL output.
Definition: EclWriter.hpp:124
OutputModule & mutableOutputModule() const
Definition: EclWriter.hpp:775
static void registerParameters()
Definition: EclWriter.hpp:152
Computes the initial condition based on the EQUIL keyword from ECL.
Definition: EquilInitializer.hpp:59
const ScalarFluidState & initialFluidState(unsigned elemIdx) const
Return the initial thermodynamic state which should be used as the initial condition.
Definition: EquilInitializer.hpp:207
BlackOilFluidState< Scalar, FluidSystem, energyModuleType !=EnergyModules::NoTemperature, energyModuleType==EnergyModules::FullyImplicitThermal, enableDissolution, enableVapwat, enableBrine, enableSaltPrecipitation, enableDisgasInWater, enableSolvent, Indices::numPhases > ScalarFluidState
Definition: EquilInitializer.hpp:102
This problem simulates an input file given in the data format used by the commercial ECLiPSE simulato...
Definition: FlowProblemBlackoil.hpp:84
HybridNewton hybridNewton_
Definition: FlowProblemBlackoil.hpp:1850
void updateExplicitQuantities_(int episodeIdx, int timeStepSize, const bool first_step_after_restart) override
Definition: FlowProblemBlackoil.hpp:1153
bool updateMaxPolymerAdsorption_(unsigned compressedDofIdx, const IntensiveQuantities &iq)
Definition: FlowProblemBlackoil.hpp:1173
void writeOutput(const bool verbose) override
Write the requested quantities of the current solution into the output files.
Definition: FlowProblemBlackoil.hpp:538
void readInitialCondition_() override
Definition: FlowProblemBlackoil.hpp:1546
void readEquilInitialCondition_() override
Definition: FlowProblemBlackoil.hpp:1282
void handleSolventBC(const BCState::BCFace &bc, RateVector &rate) const override
Definition: FlowProblemBlackoil.hpp:1560
bool checkAquiferEquilibration_
Definition: FlowProblemBlackoil.hpp:1833
Scalar maxGasDissolutionFactor(unsigned timeIdx, unsigned globalDofIdx) const
Returns the maximum value of the gas dissolution factor at the current time for a given degree of fre...
Definition: FlowProblemBlackoil.hpp:869
const std::vector< InitialFluidState > & initialFluidStates() const
Definition: FlowProblemBlackoil.hpp:733
void processRestartSaturations_(InitialFluidState &elemFluidState, Scalar &solventSaturation)
Definition: FlowProblemBlackoil.hpp:1512
std::vector< InitialFluidState > & initialFluidStates()
Definition: FlowProblemBlackoil.hpp:730
FlowProblemBlackoil(Simulator &simulator)
Definition: FlowProblemBlackoil.hpp:185
bool enableEclOutput_
Definition: FlowProblemBlackoil.hpp:1821
PrevTimestepState prev_timestep_state_
Definition: FlowProblemBlackoil.hpp:1846
Scalar drsdtcon(unsigned elemIdx, int episodeIdx) const
Definition: FlowProblemBlackoil.hpp:964
void endStepApplyAction()
Definition: FlowProblemBlackoil.hpp:456
bool drsdtconIsActive(unsigned elemIdx, int episodeIdx) const
Definition: FlowProblemBlackoil.hpp:970
void handleMicrBC(const BCState::BCFace &bc, RateVector &rate) const override
Definition: FlowProblemBlackoil.hpp:1576
Scalar maxOilVaporizationFactor(unsigned timeIdx, unsigned globalDofIdx) const
Returns the maximum value of the oil vaporization factor at the current time for a given degree of fr...
Definition: FlowProblemBlackoil.hpp:880
std::vector< InitialFluidState > initialFluidStates_
Definition: FlowProblemBlackoil.hpp:1819
void endTimeStep() override
Called by the simulator after each time integration.
Definition: FlowProblemBlackoil.hpp:450
void updateMaxPolymerAdsorption_()
Definition: FlowProblemBlackoil.hpp:1163
const InitialFluidState & initialFluidState(unsigned globalDofIdx) const
Definition: FlowProblemBlackoil.hpp:727
void endEpisode() override
Called by the simulator after the end of an episode.
Definition: FlowProblemBlackoil.hpp:506
void setSubStepReport(const SimulatorReportSingle &report)
Definition: FlowProblemBlackoil.hpp:739
void initial(PrimaryVariables &values, const Context &context, unsigned spaceIdx, unsigned timeIdx) const
Evaluate the initial value for a control volume.
Definition: FlowProblemBlackoil.hpp:920
void checkNumericalAquiferEquilibration_() const
Definition: FlowProblemBlackoil.hpp:1686
Scalar initialFlowPressureDifference_(const unsigned cellIdx, const unsigned aquIdx, const FaceDir::DirEnum faceDir) const
Definition: FlowProblemBlackoil.hpp:1633
void finishInit()
Called by the Opm::Simulator in order to initialize the problem.
Definition: FlowProblemBlackoil.hpp:321
void finalizeOutput()
Definition: FlowProblemBlackoil.hpp:561
void boundary(BoundaryRateVector &values, const Context &context, unsigned spaceIdx, unsigned timeIdx) const
Evaluate the boundary conditions for a boundary segment.
Definition: FlowProblemBlackoil.hpp:981
void handleOxygBC(const BCState::BCFace &bc, RateVector &rate) const override
Definition: FlowProblemBlackoil.hpp:1584
InitialFluidState boundaryFluidState(unsigned globalDofIdx, const int directionId) const
Definition: FlowProblemBlackoil.hpp:745
std::unique_ptr< EclWriterType > eclWriter_
Definition: FlowProblemBlackoil.hpp:1822
void initialSolutionApplied() override
Callback used by the model to indicate that the initial solution has been determined for all degrees ...
Definition: FlowProblemBlackoil.hpp:573
void captureBeginTimeStepState_() override
Snapshot the mixing rate controls before the timestep runs.
Definition: FlowProblemBlackoil.hpp:1140
void readEclRestartSolution_()
Definition: FlowProblemBlackoil.hpp:1252
void readExplicitInitialCondition_() override
Definition: FlowProblemBlackoil.hpp:1297
void beginEpisode() override
Called by the simulator before an episode begins.
Definition: FlowProblemBlackoil.hpp:278
bool recycleFirstIterationStorage() const
Return if the storage term of the first iteration is identical to the storage term for the solution o...
Definition: FlowProblemBlackoil.hpp:898
void handleUreaBC(const BCState::BCFace &bc, RateVector &rate) const override
Definition: FlowProblemBlackoil.hpp:1592
LhsEval permFactTransMultiplier(const IntensiveQuantities &intQuants, unsigned elementIdx, Callback &obtain) const
Calculate the transmissibility multiplier due to porosity reduction.
Definition: FlowProblemBlackoil.hpp:707
void serializeOp(Serializer &serializer)
Definition: FlowProblemBlackoil.hpp:1131
MixingRateControls< FluidSystem > mixControls_
Definition: FlowProblemBlackoil.hpp:1829
void handlePolymerBC(const BCState::BCFace &bc, RateVector &rate) const override
Definition: FlowProblemBlackoil.hpp:1568
void writeReports(const SimulatorTimer &timer)
Definition: FlowProblemBlackoil.hpp:526
const EclWriterType & eclWriter() const
Definition: FlowProblemBlackoil.hpp:859
void setSimulationReport(const SimulatorReport &report)
Definition: FlowProblemBlackoil.hpp:742
void addToSourceDense(RateVector &rate, unsigned globalDofIdx, unsigned timeIdx) const override
Definition: FlowProblemBlackoil.hpp:600
void computeAndSetEqWeights_()
Definition: FlowProblemBlackoil.hpp:1185
void beginTimeStep() override
Called by the simulator before each time integration.
Definition: FlowProblemBlackoil.hpp:312
void updateExplicitQuantities_(const bool first_step_after_restart)
Definition: FlowProblemBlackoil.hpp:1602
static void registerParameters()
Registers all available parameters for the problem and the model.
Definition: FlowProblemBlackoil.hpp:171
ActionHandler< Scalar, IndexTraits > actionHandler_
Definition: FlowProblemBlackoil.hpp:1848
void readSolutionFromOutputModule(const int restart_step, bool fip_init)
Read simulator solution state from the outputmodule (used with restart)
Definition: FlowProblemBlackoil.hpp:1022
const EclipseIO & eclIO() const
Definition: FlowProblemBlackoil.hpp:736
void restoreBeginTimeStepState_() override
Restore mixing rate controls after a failed timestep.
Definition: FlowProblemBlackoil.hpp:1147
EclWriterType & eclWriter()
Definition: FlowProblemBlackoil.hpp:862
bool satfuncConsistencyRequirementsMet() const
Definition: FlowProblemBlackoil.hpp:1744
bool updateCompositionChangeLimits_()
Definition: FlowProblemBlackoil.hpp:1219
This problem simulates an input file given in the data format used by the commercial ECLiPSE simulato...
Definition: FlowProblem.hpp:101
GetPropType< TypeTag, Properties::Evaluation > Evaluation
Definition: FlowProblem.hpp:166
static constexpr bool enableFoam
Definition: FlowProblem.hpp:132
virtual void writeOutput(bool verbose)
Write the requested quantities of the current solution into the output files.
Definition: FlowProblem.hpp:546
unsigned pvtRegionIndex(const Context &context, unsigned spaceIdx, unsigned timeIdx) const
Returns the index of the relevant region for thermodynmic properties.
Definition: FlowProblem.hpp:964
Scalar porosity(const Context &context, unsigned spaceIdx, unsigned timeIdx) const
Definition: FlowProblem.hpp:744
GetPropType< TypeTag, Properties::Vanguard > Vanguard
Definition: FlowProblem.hpp:114
@ numComponents
Definition: FlowProblem.hpp:124
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: FlowProblem.hpp:108
GetPropType< TypeTag, Properties::EqVector > EqVector
Definition: FlowProblem.hpp:113
GetPropType< TypeTag, Properties::ElementContext > ElementContext
Definition: FlowProblem.hpp:158
GlobalEqVector drift_
Definition: FlowProblem.hpp:2122
@ gasCompIdx
Definition: FlowProblem.hpp:150
GetPropType< TypeTag, Properties::RateVector > RateVector
Definition: FlowProblem.hpp:155
Dune::FieldMatrix< Scalar, dimWorld, dimWorld > DimMatrix
Definition: FlowProblem.hpp:172
@ waterPhaseIdx
Definition: FlowProblem.hpp:146
int episodeIndex() const
Definition: FlowProblem.hpp:317
GetPropType< TypeTag, Properties::Indices > Indices
Definition: FlowProblem.hpp:115
GetPropType< TypeTag, Properties::GlobalEqVector > GlobalEqVector
Definition: FlowProblem.hpp:112
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: FlowProblem.hpp:156
@ enableExperiments
Definition: FlowProblem.hpp:139
static constexpr bool enableDiffusion
Definition: FlowProblem.hpp:129
@ dimWorld
Definition: FlowProblem.hpp:119
TracerModel tracerModel_
Definition: FlowProblem.hpp:2128
@ enableThermalFluxBoundaries
Definition: FlowProblem.hpp:142
WellModel wellModel_
Definition: FlowProblem.hpp:2124
virtual void beginEpisode()
Called by the simulator before an episode begins.
Definition: FlowProblem.hpp:325
static constexpr bool enablePolymerMolarWeight
Definition: FlowProblem.hpp:134
virtual void beginTimeStep()
Called by the simulator before each time integration.
Definition: FlowProblem.hpp:384
@ gasPhaseIdx
Definition: FlowProblem.hpp:144
static constexpr bool enableSolvent
Definition: FlowProblem.hpp:135
@ numPhases
Definition: FlowProblem.hpp:123
void finishTransmissibilities_()
Definition: FlowProblem.hpp:1430
static constexpr bool enablePolymer
Definition: FlowProblem.hpp:133
@ numEq
Definition: FlowProblem.hpp:122
@ dim
Definition: FlowProblem.hpp:118
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: FlowProblem.hpp:167
@ enableSaltPrecipitation
Definition: FlowProblem.hpp:141
TemperatureModel temperatureModel_
Definition: FlowProblem.hpp:2129
static constexpr bool enableExtbo
Definition: FlowProblem.hpp:131
static constexpr bool enableConvectiveMixing
Definition: FlowProblem.hpp:128
GetPropType< TypeTag, Properties::GridView > GridView
Definition: FlowProblem.hpp:109
bool prepareTransmissibilityOutput_(EclWriterType &eclWriter, const bool enableEclOutput)
Definition: FlowProblem.hpp:1439
@ oilCompIdx
Definition: FlowProblem.hpp:151
void initializeSimulatorTime_()
Definition: FlowProblem.hpp:1498
static void registerParameters()
Registers all available parameters for the problem and the model.
Definition: FlowProblem.hpp:200
void updatePffDofData_()
Definition: FlowProblem.hpp:1892
static constexpr bool enableDispersion
Definition: FlowProblem.hpp:130
@ oilPhaseIdx
Definition: FlowProblem.hpp:145
GetPropType< TypeTag, Properties::PrimaryVariables > PrimaryVariables
Definition: FlowProblem.hpp:154
void readBoundaryConditions_()
Definition: FlowProblem.hpp:1923
virtual void endTimeStep()
Called by the simulator after each time integration.
Definition: FlowProblem.hpp:464
static constexpr EnergyModules energyModuleType
Definition: FlowProblem.hpp:137
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: FlowProblem.hpp:111
GetPropType< TypeTag, Properties::MaterialLaw > MaterialLaw
Definition: FlowProblem.hpp:164
void initializeModelProperties_()
Definition: FlowProblem.hpp:1522
static constexpr bool enableBioeffects
Definition: FlowProblem.hpp:126
static constexpr bool enableBrine
Definition: FlowProblem.hpp:127
@ waterCompIdx
Definition: FlowProblem.hpp:152
@ enableMICP
Definition: FlowProblem.hpp:140
Class handling mixing rate controls for a FlowProblemBlackoil.
Definition: MixingRateControls.hpp:46
Definition: SatfuncConsistencyCheckManager.hpp:58
SatfuncConsistencyCheckManager & collectFailuresTo(const int root)
Definition: SatfuncConsistencyCheckManager.hpp:99
void run(const GridView &gv, GetCellIndex &&getCellIndex)
Definition: SatfuncConsistencyCheckManager.hpp:128
typename SatfuncConsistencyChecks< Scalar >::ViolationLevel ViolationLevel
Severity level for consistency condition violation.
Definition: SatfuncConsistencyCheckManager.hpp:71
Definition: SimulatorTimer.hpp:38
VTK output module for the tracer model's parameters.
Definition: VtkTracerModule.hpp:58
static void registerParameters()
Register all run-time parameters for the tracer VTK output module.
Definition: VtkTracerModule.hpp:84
@ NONE
Definition: DeferredLogger.hpp:46
static constexpr int dim
Definition: structuredgridvanguard.hh:68
Definition: blackoilbioeffectsmodules.hh:45
constexpr double numericalAquiferEquilibrationTolerance
Definition: NumericalAquiferEquilibrationCheck.hpp:45
std::size_t checkNumericalAquiferEquilibration(const std::vector< NumericalAquiferEquilibrationMismatch > &localMismatches, const EclipseState &eclState, const Parallel::Communication &comm, bool allowMismatch)
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
Struct holding the parameters for the BlackOilBioeffectsModule class.
Definition: blackoilbioeffectsparams.hpp:42
Struct holding the parameters for the BlackoilBrineModule class.
Definition: blackoilbrineparams.hpp:42
Struct holding the parameters for the BlackoilExtboModule class.
Definition: blackoilextboparams.hpp:48
Struct holding the parameters for the BlackoilFoamModule class.
Definition: blackoilfoamparams.hpp:44
Struct holding the parameters for the BlackOilPolymerModule class.
Definition: blackoilpolymerparams.hpp:43
Struct holding the parameters for the BlackOilSolventModule class.
Definition: blackoilsolventparams.hpp:47
Blackoil part of the begin-of-timestep snapshot; see FlowProblem::PrevTimestepState.
Definition: FlowProblemBlackoil.hpp:1838
MixingRateControls< FluidSystem > mixControls
DRSDT / DRVDT.
Definition: FlowProblemBlackoil.hpp:1843
PrevTimestepState(const Schedule &schedule)
Definition: FlowProblemBlackoil.hpp:1839
Definition: SimulatorReport.hpp:202
A struct for returning timing data from a simulator to its caller.
Definition: SimulatorReport.hpp:34