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#include <utility>
57
58namespace Opm {
59
60template <typename TypeTag>
61class FIBlackOilModel : public BlackOilModel<TypeTag>
62{
69 using Element = typename GridView::template Codim<0>::Entity;
70 using ElementIterator = typename GridView::template Codim<0>::Iterator;
71 enum {
72 numEq = getPropValue<TypeTag, Properties::NumEq>(),
73 historySize = getPropValue<TypeTag, Properties::TimeDiscHistorySize>(),
74 };
75
76 // The chunked and threaded iteration over elements in this class assumes that the number
77 // and order of elements is fixed, and is therefore constrained to only work with CpGrid.
78 // For example, ALUGrid supports refinement and can not assume that.
79 static constexpr bool gridIsUnchanging =
80 std::is_same_v<GetPropType<TypeTag, Properties::Grid>, Dune::CpGrid>;
81
82 static constexpr bool avoidElementContext = getPropValue<TypeTag, Properties::AvoidElementContext>();
83
84public:
85 explicit FIBlackOilModel(Simulator& simulator)
86 : BlackOilModel<TypeTag>(simulator)
87 , element_chunks_(this->gridView_,
88 Dune::Partitions::all,
89 ThreadManager::maxThreads())
90 {
91#if HAVE_CUDA
92 if constexpr (gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
93 useGpuIntensiveQuantitiesDispatcher_ =
94 Parameters::Get<Parameters::ExperimentalComputePropertiesOnGpu>();
95 }
96#endif
97
98 // Without the cache, only a model whose intensiveQuantities() returns by value works.
100 using Result = decltype(std::declval<const Model&>().intensiveQuantities(0u, 0u));
101 if (std::is_reference_v<Result> && !this->enableIntensiveQuantityCache_) {
102 OPM_THROW(std::invalid_argument,
103 "--enable-intensive-quantity-cache=false is not supported "
104 "by this simulator.");
105 }
106 }
107
108 static void registerParameters()
109 {
111#if HAVE_CUDA
112 if constexpr (gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
113 Parameters::Register<Parameters::ExperimentalComputePropertiesOnGpu>
114 ("Experimental: compute BlackOilIntensiveQuantities on the GPU "
115 "via the GpuBlackoilIntensiveQuantitiesDispatcher.");
116 }
117#endif
118 }
119
120 void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx) const
121 {
122 if (!this->enableIntensiveQuantityCache_) {
123 return;
124 }
125 this->invalidateIntensiveQuantitiesCache(timeIdx);
126 if constexpr (gridIsUnchanging) {
127 if constexpr (avoidElementContext) {
128 updateCachedIntQuants(timeIdx);
129 return;
130 }
131#if HAVE_CUDA
132 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value)
133 {
134 if (useGpuIntensiveQuantitiesDispatcher_) {
135 if constexpr (getPropValue<TypeTag, Properties::EnableDiffusion>()
136 || getPropValue<TypeTag, Properties::EnableDispersion>()) {
137 OPM_THROW(std::logic_error,
138 "GPU intensive quantities dispatcher does not support diffusion or dispersion");
139 }
140 runGpuIntensiveQuantitiesDispatcher_(timeIdx);
141 const std::size_t numCells = this->intensiveQuantityCache_[timeIdx].size();
142 for (std::size_t i = 0; i < numCells; ++i) {
143 this->setIntensiveQuantitiesCacheEntryValidity(i, timeIdx, true);
144 }
145 return;
146 }
147 }
148#endif
150#ifdef _OPENMP
151#pragma omp parallel for
152#endif
153 for (const auto& chunk : element_chunks_) {
154 ElementContext elemCtx(this->simulator_);
155 for (const auto& elem : chunk) {
156 elemCtx.updatePrimaryStencil(elem);
157 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
158 }
159 }
160 OPM_END_PARALLEL_TRY_CATCH("invalidateAndUpdateIntensiveQuantities: state error",
161 this->simulator_.vanguard().grid().comm());
162 } else {
163 // Grid is possibly refined or otherwise changed between calls.
164 ElementContext elemCtx(this->simulator_);
165 for (const auto& elem : elements(this->gridView_)) {
166 elemCtx.updatePrimaryStencil(elem);
167 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
168 }
169 }
170 }
171
173 {
174 if (!this->enableIntensiveQuantityCache_) {
175 return;
176 }
177 // loop over all elements
178 ThreadedEntityIterator<GridView, /*codim=*/0> threadedElemIt(this->gridView_);
180#ifdef _OPENMP
181#pragma omp parallel
182#endif
183 {
184 ElementContext elemCtx(this->simulator_);
185 auto elemIt = threadedElemIt.beginParallel();
186 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
187 if (elemIt->partitionType() != Dune::OverlapEntity) {
188 continue;
189 }
190 const Element& elem = *elemIt;
191 elemCtx.updatePrimaryStencil(elem);
192 // Mark cache for this element as invalid.
193 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
194 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
195 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
196 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
197 }
198 // Update for this element.
199 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
200 }
201 }
202 OPM_END_PARALLEL_TRY_CATCH("InvalideAndUpdateIntensiveQuantitiesOverlap: state error",
203 this->simulator_.vanguard().grid().comm());
204 }
205
206 template <class GridSubDomain>
207 void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain& gridSubDomain) const
208 {
209 if (!this->enableIntensiveQuantityCache_) {
210 return;
211 }
212 // loop over all elements in the subdomain
213 using GridViewType = decltype(gridSubDomain.view);
214 ThreadedEntityIterator<GridViewType, /*codim=*/0> threadedElemIt(gridSubDomain.view);
215#ifdef _OPENMP
216#pragma omp parallel
217#endif
218 {
219 ElementContext elemCtx(this->simulator_);
220 auto elemIt = threadedElemIt.beginParallel();
221 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
222 if (elemIt->partitionType() != Dune::InteriorEntity) {
223 continue;
224 }
225 const Element& elem = *elemIt;
226 elemCtx.updatePrimaryStencil(elem);
227 // Mark cache for this element as invalid.
228 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
229 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
230 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
231 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
232 }
233 // Update for this element.
234 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
235 }
236 }
237 }
238
245 {
246 // Reset the current solution to the one of the
247 // previous time step so that we can start the next
248 // update at a physically meaningful solution.
249 // this->solution(/*timeIdx=*/0) = this->solution(/*timeIdx=*/1);
250 ParentType::updateFailed();
252 }
253
254 // standard flow
255 const IntensiveQuantities& intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
256 {
257 if (!this->enableIntensiveQuantityCache_) [[unlikely]] {
258 throwIntensiveQuantityError_(true);
259 }
260
261 assert(timeIdx < this->cachedIntensiveQuantityHistorySize());
262 const auto* intquant = this->cachedIntensiveQuantities(globalIdx, timeIdx);
263 if (!intquant) [[unlikely]] {
264 throwIntensiveQuantityError_(false);
265 }
266 return *intquant;
267 }
268
269private:
270 // Out of line so the accessor above stays small enough to inline in the assembly loop.
271 [[noreturn]] static void throwIntensiveQuantityError_(bool cacheDisabled)
272 {
273 if (cacheDisabled) {
274 OPM_THROW(std::logic_error,
275 "Intensive quantity cache is disabled; "
276 "use --enable-intensive-quantity-cache=true");
277 }
278 OPM_THROW(std::logic_error, "Intensive quantites need to be updated in code");
279 }
280
281public:
282
283protected:
284
285 template <EclMultiplexerApproach ApproachArg>
286 using EMD = EclMultiplexerDispatch<ApproachArg>;
287
288 void updateCachedIntQuants(const unsigned timeIdx) const
289 {
290 // Runtime dispatch on three-phase approach to compile-time fixed approach.
291 switch (this->simulator_.problem().materialLawManager().threePhaseApproach()) {
292 case EclMultiplexerApproach::Stone1:
293 updateCachedIntQuants1<EclMultiplexerDispatch<EclMultiplexerApproach::Stone1>>(timeIdx);
294 break;
295
296 case EclMultiplexerApproach::Stone2:
297 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Stone2>>(timeIdx);
298 break;
299
300 case EclMultiplexerApproach::Default:
301 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Default>>(timeIdx);
302 break;
303
304 case EclMultiplexerApproach::TwoPhase:
305 updateCachedIntQuants1<EMD<EclMultiplexerApproach::TwoPhase>>(timeIdx);
306 break;
307
308 case EclMultiplexerApproach::OnePhase:
309 updateCachedIntQuants1<EMD<EclMultiplexerApproach::OnePhase>>(timeIdx);
310 break;
311 }
312 }
313
314 template <class EMDArg>
315 void updateCachedIntQuants1(const unsigned timeIdx) const
316 {
317 // Runtime dispatch on using piecewise linear saturation curves to compile-time fixed approach.
318 if (this->simulator_.problem().materialLawManager().satCurveIsAllPiecewiseLinear()) {
319 using PL = SatCurveMultiplexerDispatch<SatCurveMultiplexerApproach::PiecewiseLinear>;
320 updateCachedIntQuantsLoop<EMDArg, PL>(timeIdx);
321 } else {
322 // TODO: Might want to set LET here, but need to check if partial use of LET is possible.
323 updateCachedIntQuantsLoop<EMDArg>(timeIdx);
324 }
325 }
326
327
328 template <class ...Args>
329 void updateCachedIntQuantsLoop(const unsigned timeIdx) const
330 {
331 const auto& elementMapper = this->simulator_.model().elementMapper();
332#ifdef _OPENMP
333#pragma omp parallel for
334#endif
335 for (const auto& chunk : element_chunks_) {
336 for (const auto& elem : chunk) {
337 this->template updateSingleCachedIntQuantUnchecked<Args...>(elementMapper.index(elem), timeIdx);
338 }
339 }
340 }
341
342 template <class ...Args>
343 void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
344 {
345 // Get the cached data.
346 auto& intquant = this->intensiveQuantityCache_[timeIdx][globalIdx];
347 // Update it.
348 intquant.template update<Args...>(this->simulator_.problem(), this->solution(timeIdx)[globalIdx], globalIdx, timeIdx);
349 // Set the up-to-date flag.
350 this->intensiveQuantityCacheUpToDate_[timeIdx][globalIdx] = 1;
351 }
352
353 ElementChunks<GridView, Dune::Partitions::All> element_chunks_;
354
355#if HAVE_CUDA
356 bool useGpuIntensiveQuantitiesDispatcher_{false};
357 using GpuDispatcherStorage = std::conditional_t<
358 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value,
359 std::unique_ptr<Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>,
360 std::monostate>;
361 mutable GpuDispatcherStorage gpuIntensiveQuantitiesDispatcher_{};
362
363 void runGpuIntensiveQuantitiesDispatcher_(const unsigned timeIdx) const
364 {
365 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
366 if (!gpuIntensiveQuantitiesDispatcher_) {
367 gpuIntensiveQuantitiesDispatcher_ =
368 std::make_unique<
369 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>();
370 }
371 using PV = GetPropType<TypeTag, Properties::PrimaryVariables>;
372 const auto& sol = this->solution(timeIdx);
373 const std::size_t numCells = this->intensiveQuantityCache_[timeIdx].size();
374 std::vector<const PV*> priVarsPtrs(numCells);
375 std::vector<IntensiveQuantities*> outIqPtrs(numCells);
376 for (std::size_t i = 0; i < numCells; ++i) {
377 priVarsPtrs[i] = &sol[i];
378 outIqPtrs[i] = &this->intensiveQuantityCache_[timeIdx][i];
379 }
380 gpuIntensiveQuantitiesDispatcher_->update(
381 this->simulator_.problem(),
382 priVarsPtrs.data(),
383 outIqPtrs.data(),
384 numCells);
385 }
386 }
387#endif
388};
389
390} // namespace Opm
391
392#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:62
static void registerParameters()
Definition: FIBlackoilModel.hpp:108
void updateCachedIntQuantsLoop(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:329
void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain &gridSubDomain) const
Definition: FIBlackoilModel.hpp:207
void updateCachedIntQuants(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:288
void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:343
void invalidateAndUpdateIntensiveQuantitiesOverlap(unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:172
void updateFailed()
Called by the update() method if it was unsuccessful. This is primary a hook which the actual model c...
Definition: FIBlackoilModel.hpp:244
const IntensiveQuantities & intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:255
void updateCachedIntQuants1(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:315
EclMultiplexerDispatch< ApproachArg > EMD
Definition: FIBlackoilModel.hpp:286
void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:120
FIBlackOilModel(Simulator &simulator)
Definition: FIBlackoilModel.hpp:85
ElementChunks< GridView, Dune::Partitions::All > element_chunks_
Definition: FIBlackoilModel.hpp:353
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.