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 // Retain the full CPU cache for existing host consumers.
142 // Assembly borrows the device IQs independently of this mirror.
143 const std::size_t numCells = this->intensiveQuantityCache_[timeIdx].size();
144 std::vector<IntensiveQuantities*> outIqPtrs(numCells);
145 for (std::size_t i = 0; i < numCells; ++i) {
146 outIqPtrs[i] = &this->intensiveQuantityCache_[timeIdx][i];
147 }
148 gpuIntensiveQuantitiesDispatcher_->materializeHostIntensiveQuantities(
149 timeIdx, outIqPtrs.data(), numCells);
150 for (std::size_t i = 0; i < numCells; ++i) {
151 this->setIntensiveQuantitiesCacheEntryValidity(i, timeIdx, true);
152 }
153 return;
154 }
155 }
156#endif
158#ifdef _OPENMP
159#pragma omp parallel for
160#endif
161 for (std::size_t ci = 0; ci < element_chunks_.size(); ++ci) {
162 const auto& chunk = element_chunks_[ci];
163 ElementContext elemCtx(this->simulator_);
164 for (const auto& elem : chunk) {
165 elemCtx.updatePrimaryStencil(elem);
166 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
167 }
168 }
169 OPM_END_PARALLEL_TRY_CATCH("invalidateAndUpdateIntensiveQuantities: state error",
170 this->simulator_.vanguard().grid().comm());
171 } else {
172 // Grid is possibly refined or otherwise changed between calls.
173 ElementContext elemCtx(this->simulator_);
174 for (const auto& elem : elements(this->gridView_)) {
175 elemCtx.updatePrimaryStencil(elem);
176 elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
177 }
178 }
179 }
180
182 {
183 if (!this->enableIntensiveQuantityCache_) {
184 return;
185 }
186 // loop over all elements
187 ThreadedEntityIterator<GridView, /*codim=*/0> threadedElemIt(this->gridView_);
189#ifdef _OPENMP
190#pragma omp parallel
191#endif
192 {
193 ElementContext elemCtx(this->simulator_);
194 auto elemIt = threadedElemIt.beginParallel();
195 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
196 if (elemIt->partitionType() != Dune::OverlapEntity) {
197 continue;
198 }
199 const Element& elem = *elemIt;
200 elemCtx.updatePrimaryStencil(elem);
201 // Mark cache for this element as invalid.
202 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
203 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
204 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
205 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
206 }
207 // Update for this element.
208 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
209 }
210 }
211 OPM_END_PARALLEL_TRY_CATCH("InvalideAndUpdateIntensiveQuantitiesOverlap: state error",
212 this->simulator_.vanguard().grid().comm());
213 }
214
215 template <class GridSubDomain>
216 void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain& gridSubDomain) const
217 {
218 if (!this->enableIntensiveQuantityCache_) {
219 return;
220 }
221 // loop over all elements in the subdomain
222 using GridViewType = decltype(gridSubDomain.view);
223 ThreadedEntityIterator<GridViewType, /*codim=*/0> threadedElemIt(gridSubDomain.view);
224#ifdef _OPENMP
225#pragma omp parallel
226#endif
227 {
228 ElementContext elemCtx(this->simulator_);
229 auto elemIt = threadedElemIt.beginParallel();
230 for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
231 if (elemIt->partitionType() != Dune::InteriorEntity) {
232 continue;
233 }
234 const Element& elem = *elemIt;
235 elemCtx.updatePrimaryStencil(elem);
236 // Mark cache for this element as invalid.
237 const std::size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
238 for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
239 const unsigned globalIndex = elemCtx.globalSpaceIndex(dofIdx, timeIdx);
240 this->setIntensiveQuantitiesCacheEntryValidity(globalIndex, timeIdx, false);
241 }
242 // Update for this element.
243 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
244 }
245 }
246 }
247
254 {
255 // Reset the current solution to the one of the
256 // previous time step so that we can start the next
257 // update at a physically meaningful solution.
258 // this->solution(/*timeIdx=*/0) = this->solution(/*timeIdx=*/1);
259 ParentType::updateFailed();
261 }
262
263 // standard flow
264 const IntensiveQuantities& intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
265 {
266 if (!this->enableIntensiveQuantityCache_) [[unlikely]] {
267 throwIntensiveQuantityError_(true);
268 }
269
270 assert(timeIdx < this->cachedIntensiveQuantityHistorySize());
271 const auto* intquant = this->cachedIntensiveQuantities(globalIdx, timeIdx);
272 if (!intquant) [[unlikely]] {
273 throwIntensiveQuantityError_(false);
274 }
275 return *intquant;
276 }
277
278private:
279 // Out of line so the accessor above stays small enough to inline in the assembly loop.
280 [[noreturn]] static void throwIntensiveQuantityError_(bool cacheDisabled)
281 {
282 if (cacheDisabled) {
283 OPM_THROW(std::logic_error,
284 "Intensive quantity cache is disabled; "
285 "use --enable-intensive-quantity-cache=true");
286 }
287 OPM_THROW(std::logic_error, "Intensive quantites need to be updated in code");
288 }
289
290public:
291#if HAVE_CUDA
292 bool hasGpuPropertyAssemblyBridge() const
293 {
294 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
295 return useGpuIntensiveQuantitiesDispatcher_ && gpuIntensiveQuantitiesDispatcher_
296 && gpuIntensiveQuantitiesDispatcher_->hasDeviceModelView();
297 }
298 return false;
299 }
300
301 template <class T = TypeTag>
302 std::enable_if_t<Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<T>::value,
303 const typename Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<T>::Bridge&>
304 gpuPropertyAssemblyBridge() const
305 {
306 if (!hasGpuPropertyAssemblyBridge()) {
307 OPM_THROW(std::logic_error, "GPU property/assembly bridge has no valid device IQ model");
308 }
309 return gpuIntensiveQuantitiesDispatcher_->bridge();
310 }
311#endif
312
314 {
315 ParentType::advanceTimeLevel();
316#if HAVE_CUDA
317 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
318 if (gpuIntensiveQuantitiesDispatcher_) {
319 gpuIntensiveQuantitiesDispatcher_->advanceTimeLevel();
320 }
321 }
322#endif
323 }
324
325protected:
326
327 template <EclMultiplexerApproach ApproachArg>
328 using EMD = EclMultiplexerDispatch<ApproachArg>;
329
330 void updateCachedIntQuants(const unsigned timeIdx) const
331 {
332 // Runtime dispatch on three-phase approach to compile-time fixed approach.
333 switch (this->simulator_.problem().materialLawManager().threePhaseApproach()) {
334 case EclMultiplexerApproach::Stone1:
335 updateCachedIntQuants1<EclMultiplexerDispatch<EclMultiplexerApproach::Stone1>>(timeIdx);
336 break;
337
338 case EclMultiplexerApproach::Stone2:
339 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Stone2>>(timeIdx);
340 break;
341
342 case EclMultiplexerApproach::Default:
343 updateCachedIntQuants1<EMD<EclMultiplexerApproach::Default>>(timeIdx);
344 break;
345
346 case EclMultiplexerApproach::TwoPhase:
347 updateCachedIntQuants1<EMD<EclMultiplexerApproach::TwoPhase>>(timeIdx);
348 break;
349
350 case EclMultiplexerApproach::OnePhase:
351 updateCachedIntQuants1<EMD<EclMultiplexerApproach::OnePhase>>(timeIdx);
352 break;
353 }
354 }
355
356 template <class EMDArg>
357 void updateCachedIntQuants1(const unsigned timeIdx) const
358 {
359 // Runtime dispatch on using piecewise linear saturation curves to compile-time fixed approach.
360 if (this->simulator_.problem().materialLawManager().satCurveIsAllPiecewiseLinear()) {
361 using PL = SatCurveMultiplexerDispatch<SatCurveMultiplexerApproach::PiecewiseLinear>;
362 updateCachedIntQuantsLoop<EMDArg, PL>(timeIdx);
363 } else {
364 // TODO: Might want to set LET here, but need to check if partial use of LET is possible.
365 updateCachedIntQuantsLoop<EMDArg>(timeIdx);
366 }
367 }
368
369
370 template <class ...Args>
371 void updateCachedIntQuantsLoop(const unsigned timeIdx) const
372 {
373 const auto& elementMapper = this->simulator_.model().elementMapper();
374#ifdef _OPENMP
375#pragma omp parallel for
376#endif
377 for (std::size_t ci = 0; ci < element_chunks_.size(); ++ci) {
378 const auto& chunk = element_chunks_[ci];
379 for (const auto& elem : chunk) {
380 this->template updateSingleCachedIntQuantUnchecked<Args...>(elementMapper.index(elem), timeIdx);
381 }
382 }
383 }
384
385 template <class ...Args>
386 void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
387 {
388 // Get the cached data.
389 auto& intquant = this->intensiveQuantityCache_[timeIdx][globalIdx];
390 // Update it.
391 intquant.template update<Args...>(this->simulator_.problem(), this->solution(timeIdx)[globalIdx], globalIdx, timeIdx);
392 // Set the up-to-date flag.
393 this->intensiveQuantityCacheUpToDate_[timeIdx][globalIdx] = 1;
394 }
395
396 ElementChunks<GridView, Dune::Partitions::All> element_chunks_;
397
398#if HAVE_CUDA
399 bool useGpuIntensiveQuantitiesDispatcher_{false};
400 using GpuDispatcherStorage = std::conditional_t<
401 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value,
402 std::unique_ptr<Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>,
403 std::monostate>;
404 mutable GpuDispatcherStorage gpuIntensiveQuantitiesDispatcher_{};
405
406 void runGpuIntensiveQuantitiesDispatcher_(const unsigned timeIdx) const
407 {
408 if constexpr (Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcherSupport<TypeTag>::value) {
409 if (!gpuIntensiveQuantitiesDispatcher_) {
410 gpuIntensiveQuantitiesDispatcher_ =
411 std::make_unique<
412 Opm::gpuistl::GpuBlackoilIntensiveQuantitiesDispatcher<TypeTag>>();
413 }
414 const auto& sol = this->solution(timeIdx);
415 gpuIntensiveQuantitiesDispatcher_->update(this->simulator_.problem(), sol, timeIdx);
416 }
417 }
418#endif
419};
420
421} // namespace Opm
422
423#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:371
void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx, const GridSubDomain &gridSubDomain) const
Definition: FIBlackoilModel.hpp:216
void updateCachedIntQuants(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:330
void updateSingleCachedIntQuantUnchecked(const unsigned globalIdx, const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:386
void advanceTimeLevel()
Definition: FIBlackoilModel.hpp:313
void invalidateAndUpdateIntensiveQuantitiesOverlap(unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:181
void updateFailed()
Called by the update() method if it was unsuccessful. This is primary a hook which the actual model c...
Definition: FIBlackoilModel.hpp:253
const IntensiveQuantities & intensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:264
void updateCachedIntQuants1(const unsigned timeIdx) const
Definition: FIBlackoilModel.hpp:357
EclMultiplexerDispatch< ApproachArg > EMD
Definition: FIBlackoilModel.hpp:328
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:396
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.