FIBlackoilModel.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 This file is part of the Open Porous Media project (OPM).
5
6 OPM is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 2 of the License, or
9 (at your option) any later version.
10
11 OPM is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with OPM. If not, see <http://www.gnu.org/licenses/>.
18
19 Consult the COPYING file in the top-level source directory of this
20 module for the precise wording of the license and the list of
21 copyright holders.
22*/
28#ifndef FI_BLACK_OIL_MODEL_HPP
29#define FI_BLACK_OIL_MODEL_HPP
30
33
34#include <opm/common/ErrorMacros.hpp>
36
37#include <opm/grid/CpGrid.hpp>
38#include <opm/grid/utility/ElementChunks.hpp>
39
42
43#include <opm/material/fluidmatrixinteractions/EclMultiplexerMaterialParams.hpp>
44
45#if HAVE_CUDA
47#include <memory>
48#include <variant>
49#include <vector>
50#endif
51
52#include <chrono>
53#include <cstddef>
54#include <stdexcept>
55#include <type_traits>
56
57namespace Opm {
58
59template <typename TypeTag>
60class FIBlackOilModel : public BlackOilModel<TypeTag>
61{
68 using Element = typename GridView::template Codim<0>::Entity;
69 using ElementIterator = typename GridView::template Codim<0>::Iterator;
70 enum {
71 numEq = getPropValue<TypeTag, Properties::NumEq>(),
72 historySize = getPropValue<TypeTag, Properties::TimeDiscHistorySize>(),
73 };
74
75 // The chunked and threaded iteration over elements in this class assumes that the number
76 // and order of elements is fixed, and is therefore constrained to only work with CpGrid.
77 // For example, ALUGrid supports refinement and can not assume that.
78 static constexpr bool gridIsUnchanging =
79 std::is_same_v<GetPropType<TypeTag, Properties::Grid>, Dune::CpGrid>;
80
81 static constexpr bool avoidElementContext = getPropValue<TypeTag, Properties::AvoidElementContext>();
82
83public:
84 explicit FIBlackOilModel(Simulator& simulator)
85 : BlackOilModel<TypeTag>(simulator)
86 , element_chunks_(this->gridView_,
87 Dune::Partitions::all,
88 ThreadManager::maxThreads())
89 {
90#if HAVE_CUDA
91 if constexpr (gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
92 useGpuIntensiveQuantitiesDispatcher_ =
93 Parameters::Get<Parameters::ExperimentalComputePropertiesOnGpu>();
94 }
95#endif
96 }
97
98 static void registerParameters()
99 {
101#if HAVE_CUDA
102 if constexpr (gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
103 Parameters::Register<Parameters::ExperimentalComputePropertiesOnGpu>
104 ("Experimental: compute BlackOilIntensiveQuantities on the GPU "
105 "via the GpuBlackoilIntensiveQuantitiesDispatcher.");
106 }
107#endif
108 }
109
110 void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx) const
111 {
112 this->invalidateIntensiveQuantitiesCache(timeIdx);
113 if constexpr (gridIsUnchanging) {
114 if constexpr (avoidElementContext) {
115 updateCachedIntQuants(timeIdx);
116 return;
117 }
118#if HAVE_CUDA
119 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value)
120 {
121 if (useGpuIntensiveQuantitiesDispatcher_) {
122 if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()
123 || getPropValue<TypeTag, Properties::EnableDispersion>()) {
124 OPM_THROW(std::logic_error,
125 "GPU intensive quantities dispatcher does not support diffusion or dispersion");
126 }
127 runGpuIntensiveQuantitiesDispatcher_(timeIdx);
128 const std::size_t numCells = this->intensiveQuantityCache_[timeIdx].size();
129 for (std::size_t i = 0; i < numCells; ++i) {
130 this->setIntensiveQuantitiesCacheEntryValidity(i, timeIdx, true);
131 }
132 return;
133 }
134 }
135#endif
137#ifdef _OPENMP
138#pragma omp parallel for
139#endif
140 for (const auto& chunk : element_chunks_) {
141 ElementContext elemCtx(this->simulator_);
142 for (const auto& elem : chunk) {
143 elemCtx.updatePrimaryStencil(elem);
144 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
145 }
146 }
147 OPM_END_PARALLEL_TRY_CATCH("invalidateAndUpdateIntensiveQuantities: state error",
148 this->simulator_.vanguard().grid().comm());
149 } else {
150 // Grid is possibly refined or otherwise changed between calls.
151 ElementContext elemCtx(this->simulator_);
152 for (const auto& elem : elements(this->gridView_)) {
153 elemCtx.updatePrimaryStencil(elem);
154 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
155 }
156 }
157 }
158
160 {
161 // loop over all elements
162 ThreadedEntityIterator<GridView, /*codim=*/0> threadedElemIt(this->gridView_);
164#ifdef _OPENMP
165#pragma omp parallel
166#endif
167 {
168 ElementContext elemCtx(this->simulator_);
169 auto elemIt = threadedElemIt.beginParallel();
170 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
171 if (elemIt->partitionType() != Dune::OverlapEntity) {
172 continue;
173 }
174 const Element& elem = *elemIt;
175 elemCtx.updatePrimaryStencil(elem);
176 // Mark cache for this element as invalid.
177 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
178 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
179 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
180 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
181 }
182 // Update for this element.
183 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
184 }
185 }
186 OPM_END_PARALLEL_TRY_CATCH("InvalideAndUpdateIntensiveQuantitiesOverlap: state error",
187 this->simulator_.vanguard().grid().comm());
188 }
189
190 template <class GridSubDomain>
191 void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain& gridSubDomain) const
192 {
193 // loop over all elements in the subdomain
194 using GridViewType = decltype(gridSubDomain.view);
195 ThreadedEntityIterator<GridViewType, /*codim=*/0> threadedElemIt(gridSubDomain.view);
196#ifdef _OPENMP
197#pragma omp parallel
198#endif
199 {
200 ElementContext elemCtx(this->simulator_);
201 auto elemIt = threadedElemIt.beginParallel();
202 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
203 if (elemIt->partitionType() != Dune::InteriorEntity) {
204 continue;
205 }
206 const Element& elem = *elemIt;
207 elemCtx.updatePrimaryStencil(elem);
208 // Mark cache for this element as invalid.
209 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
210 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
211 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
212 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
213 }
214 // Update for this element.
215 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
216 }
217 }
218 }
219
226 {
227 // Reset the current solution to the one of the
228 // previous time step so that we can start the next
229 // update at a physically meaningful solution.
230 // this->solution(/*timeIdx=*/0) = this->solution(/*timeIdx=*/1);
231 ParentType::updateFailed();
233 }
234
235 // standard flow
236 const IntensiveQuantities& intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
237 {
238 if (!this->enableIntensiveQuantityCache_) {
239 OPM_THROW(std::logic_error,
240 "Run without intensive quantites not enabled: "
241 "Use --enable-intensive-quantity=true");
242 }
243
244 assert(timeIdx < this->cachedIntensiveQuantityHistorySize());
245 const auto* intquant = this->cachedIntensiveQuantities(globalIdx, timeIdx);
246 if (!intquant) {
247 OPM_THROW(std::logic_error, "Intensive quantites need to be updated in code");
248 }
249 return *intquant;
250 }
251
252protected:
253
254 template <EclMultiplexerApproach ApproachArg>
255 using EMD = EclMultiplexerDispatch<ApproachArg>;
256
257 void updateCachedIntQuants(const unsigned timeIdx) const
258 {
259 // Runtime dispatch on three-phase approach to compile-time fixed approach.
260 switch (this->simulator_.problem().materialLawManager()->threePhaseApproach()) {
261 case EclMultiplexerApproach::Stone1:
262 updateCachedIntQuants1<EclMultiplexerDispatch<EclMultiplexerApproach::Stone1>>(timeIdx);
263 break;
264
265 case EclMultiplexerApproach::Stone2:
266 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Stone2>>(timeIdx);
267 break;
268
269 case EclMultiplexerApproach::Default:
270 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Default>>(timeIdx);
271 break;
272
273 case EclMultiplexerApproach::TwoPhase:
274 updateCachedIntQuants1<EMD<EclMultiplexerApproach::TwoPhase>>(timeIdx);
275 break;
276
277 case EclMultiplexerApproach::OnePhase:
278 updateCachedIntQuants1<EMD<EclMultiplexerApproach::OnePhase>>(timeIdx);
279 break;
280 }
281 }
282
283 template <class EMDArg>
284 void updateCachedIntQuants1(const unsigned timeIdx) const
285 {
286 // Runtime dispatch on using piecewise linear saturation curves to compile-time fixed approach.
287 if (this->simulator_.problem().materialLawManager()->satCurveIsAllPiecewiseLinear()) {
288 using PL = SatCurveMultiplexerDispatch<SatCurveMultiplexerApproach::PiecewiseLinear>;
289 updateCachedIntQuantsLoop<EMDArg, PL>(timeIdx);
290 } else {
291 // TODO: Might want to set LET here, but need to check if partial use of LET is possible.
292 updateCachedIntQuantsLoop<EMDArg>(timeIdx);
293 }
294 }
295
296
297 template <class ...Args>
298 void updateCachedIntQuantsLoop(const unsigned timeIdx) const
299 {
300 const auto& elementMapper = this->simulator_.model().elementMapper();
301#ifdef _OPENMP
302#pragma omp parallel for
303#endif
304 for (const auto& chunk : element_chunks_) {
305 for (const auto& elem : chunk) {
306 this->template updateSingleCachedIntQuantUnchecked<Args...>(elementMapper.index(elem), timeIdx);
307 }
308 }
309 }
310
311 template <class ...Args>
312 void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
313 {
314 // Get the cached data.
315 auto& intquant = this->intensiveQuantityCache_[timeIdx][globalIdx];
316 // Update it.
317 intquant.template update<Args...>(this->simulator_.problem(), this->solution(timeIdx)[globalIdx], globalIdx, timeIdx);
318 // Set the up-to-date flag.
319 this->intensiveQuantityCacheUpToDate_[timeIdx][globalIdx] = 1;
320 }
321
322 ElementChunks<GridView, Dune::Partitions::All> element_chunks_;
323
324#if HAVE_CUDA
325 bool useGpuIntensiveQuantitiesDispatcher_{false};
326 using GpuDispatcherStorage = std::conditional_t<
327 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value,
328 std::unique_ptr<Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>,
329 std::monostate>;
330 mutable GpuDispatcherStorage gpuIntensiveQuantitiesDispatcher_{};
331
332 void runGpuIntensiveQuantitiesDispatcher_(const unsigned timeIdx) const
333 {
334 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
335 if (!gpuIntensiveQuantitiesDispatcher_) {
336 gpuIntensiveQuantitiesDispatcher_ =
337 std::make_unique<
338 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>();
339 }
340 using PV = GetPropType<TypeTag, Properties::PrimaryVariables>;
341 const auto& sol = this->solution(timeIdx);
342 const std::size_t numCells = this->intensiveQuantityCache_[timeIdx].size();
343 std::vector<const PV*> priVarsPtrs(numCells);
344 std::vector<IntensiveQuantities*> outIqPtrs(numCells);
345 for (std::size_t i = 0; i < numCells; ++i) {
346 priVarsPtrs[i] = &sol[i];
347 outIqPtrs[i] = &this->intensiveQuantityCache_[timeIdx][i];
348 }
349 gpuIntensiveQuantitiesDispatcher_->update(
350 this->simulator_.problem(),
351 priVarsPtrs.data(),
352 outIqPtrs.data(),
353 numCells);
354 }
355 }
356#endif
357};
358
359} // namespace Opm
360
361#endif // FI_BLACK_OIL_MODEL_HPP
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
A fully-implicit black-oil flow model.
Definition: blackoilmodel.hh:329
static void registerParameters()
Register all run-time parameters for the immiscible model.
Definition: blackoilmodel.hh:379
Definition: FIBlackoilModel.hpp:61
static void registerParameters()
Definition: FIBlackoilModel.hpp:98
void updateCachedIntQuantsLoop(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:298
void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain &gridSubDomain) const
Definition: FIBlackoilModel.hpp:191
void updateCachedIntQuants(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:257
void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:312
void invalidateAndUpdateIntensiveQuantitiesOverlap(unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:159
void updateFailed()
Called by the update() method if it was unsuccessful. This is primary a hook which the actual model c...
Definition: FIBlackoilModel.hpp:225
const IntensiveQuantities & intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:236
void updateCachedIntQuants1(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:284
EclMultiplexerDispatch< ApproachArg > EMD
Definition: FIBlackoilModel.hpp:255
void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:110
FIBlackOilModel(Simulator &simulator)
Definition: FIBlackoilModel.hpp:84
ElementChunks< GridView, Dune::Partitions::All > element_chunks_
Definition: FIBlackoilModel.hpp:322
A base class for fully-implicit multi-phase porous-media flow models which assume multiple fluid phas...
Definition: multiphasebasemodel.hh:161
Provides an STL-iterator like interface to iterate over the enties of a GridView in OpenMP threaded a...
Definition: threadedentityiterator.hh:42
bool isFinished(const EntityIterator &it) const
Definition: threadedentityiterator.hh:67
EntityIterator increment()
Definition: threadedentityiterator.hh:80
EntityIterator beginParallel()
Definition: threadedentityiterator.hh:54
Definition: fvbaseprimaryvariables.hh:161
Definition: blackoilbioeffectsmodules.hh:45
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
The Opm property system, traits with inheritance.