TracerModel.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 OPM_TRACER_MODEL_HPP
29#define OPM_TRACER_MODEL_HPP
30
31#include <opm/common/OpmLog/OpmLog.hpp>
32#include <opm/common/TimingMacros.hpp>
33
34#include <opm/input/eclipse/EclipseState/Aquifer/AquiferConfig.hpp>
35#include <opm/input/eclipse/Schedule/BCState.hpp>
36#include <opm/input/eclipse/Schedule/Schedule.hpp>
37#include <opm/input/eclipse/Schedule/Well/Well.hpp>
38#include <opm/input/eclipse/Schedule/Well/WellConnections.hpp>
39
40#include <opm/grid/utility/ElementChunks.hpp>
41
45
51
52#include <algorithm>
53#include <array>
54#include <cstddef>
55#include <iterator>
56#include <memory>
57#include <set>
58#include <stdexcept>
59#include <string>
60#include <unordered_map>
61#include <utility>
62#include <vector>
63
64#include <fmt/format.h>
65
66namespace Opm::Properties {
67
68template<class TypeTag, class MyTypeTag>
71};
72
73} // namespace Opm::Properties
74
75namespace Opm {
76
82template <class TypeTag>
83class TracerModel : public GenericTracerModel<GetPropType<TypeTag, Properties::Grid>,
84 GetPropType<TypeTag, Properties::GridView>,
85 GetPropType<TypeTag, Properties::DofMapper>,
86 GetPropType<TypeTag, Properties::Stencil>,
87 GetPropType<TypeTag, Properties::FluidSystem>,
88 GetPropType<TypeTag, Properties::Scalar>>
89{
105
106 using TracerEvaluation = DenseAd::Evaluation<Scalar,1>;
107
108 using TracerMatrix = typename BaseType::TracerMatrix;
109 using TracerVector = typename BaseType::TracerVector;
110 using TracerVectorSingle = typename BaseType::TracerVectorSingle;
111
112 enum { numEq = getPropValue<TypeTag, Properties::NumEq>() };
113 enum { numPhases = FluidSystem::numPhases };
114 enum { waterPhaseIdx = FluidSystem::waterPhaseIdx };
115 enum { oilPhaseIdx = FluidSystem::oilPhaseIdx };
116 enum { gasPhaseIdx = FluidSystem::gasPhaseIdx };
117 enum { enableDiffusion = getPropValue<TypeTag, Properties::EnableDiffusion>() };
118 enum { enableDispersion = getPropValue<TypeTag, Properties::EnableDispersion>() };
119
120public:
121 explicit TracerModel(Simulator& simulator)
122 : BaseType(simulator.vanguard().gridView(),
123 simulator.vanguard().eclState(),
124 simulator.vanguard().cartesianIndexMapper(),
125 simulator.model().dofMapper(),
126 simulator.vanguard().cellCentroids())
127 , simulator_(simulator)
128 , dispersionActive_(simulator.vanguard().eclState().getSimulationConfig().rock_config().dispersion())
129 , element_chunks_(simulator.gridView(), Dune::Partitions::all, ThreadManager::maxThreads())
130 { }
131
132
133 /*
134 The initialization of the tracer model is a three step process:
135
136 1. The init() method is called. This will allocate buffers and initialize
137 some phase index stuff. If this is a normal run the initial tracer
138 concentrations will be assigned from the TBLK or TVDPF keywords.
139
140 2. [Restart only:] The tracer concentration are read from the restart
141 file and the concentrations are applied with repeated calls to the
142 setTracerConcentration() method. This is currently done in the
143 eclwriter::beginRestart() method.
144
145 3. Internally the tracer model manages the concentrations in "batches" for
146 the oil, water and gas tracers respectively. The batches should be
147 initialized with the initial concentration, that must be performed
148 after the concentration values have been assigned. This is done in
149 method prepareTracerBatches() called from eclproblem::finishInit().
150 */
151 void init(bool rst)
152 {
153 this->doInit(rst, simulator_.model().numGridDof(),
154 gasPhaseIdx, oilPhaseIdx, waterPhaseIdx);
155
156 const std::string solver = Parameters::Get<Parameters::TracerSolver>();
157 if (solver != "istl" && solver != "reorder") {
158 throw std::invalid_argument("Unknown tracer solver '" + solver +
159 "', use 'istl' or 'reorder'");
160 }
161 this->useReorderSolver_ = solver == "reorder";
162
163 // The reorder solver cannot be used for diffusion/dispersion fluxes
164 if (this->useReorderSolver_) {
165 bool hasDispersion = false;
166 if constexpr (enableDispersion) {
167 hasDispersion = dispersionActive_ && !this->tracerPhaseIdx_.empty();
168 }
169 bool hasDiffusion = false;
170 if constexpr (enableDiffusion) {
171 for (std::size_t tracerIdx = 0; tracerIdx < this->tracerPhaseIdx_.size();
172 ++tracerIdx) {
173 const auto& tracerConfig = this->eclState_.tracer()[tracerIdx];
174 hasDiffusion = hasDiffusion || tracerConfig.free_diffusion_coefficient != 0.0 ||
175 (hasSolutionPart_(this->tracerPhaseIdx_[tracerIdx]) &&
176 tracerConfig.solution_diffusion_coefficient != 0.0);
177 }
178 }
179 if (hasDiffusion || hasDispersion) {
180 const std::string unsupported = hasDiffusion && hasDispersion
181 ? "diffusion (TRDIF) and dispersion (DISPERC)"
182 : (hasDiffusion ? "diffusion (TRDIF)" : "dispersion (DISPERC)");
183 throw std::invalid_argument("The reorder tracer solver does not support " +
184 unsupported + ", use --tracer-solver=istl");
185 }
186 }
187
188 reorderRetrySteps_ = Parameters::Get<Parameters::TracerReorderRetrySteps>();
189 if (reorderRetrySteps_ < 0) {
190 throw std::invalid_argument("The number of tracer reorder retry steps must not be "
191 "negative, got " + std::to_string(reorderRetrySteps_));
192 }
193 }
194
196 {
197 DeferredLogger local_deferredLogger;
198
199 // Tracers of the same phase and with the same diffusion coefficients (TRDIFxxx) are
200 // solved together in a batch, with a common system matrix and separate right-hand
201 // sides. Tracers with different diffusion coefficients get separate batches.
202 for (std::size_t tracerIdx = 0; tracerIdx < this->tracerPhaseIdx_.size(); ++tracerIdx) {
203 const int phaseIdx = this->tracerPhaseIdx_[tracerIdx];
204 if (phaseIdx == FluidSystem::waterPhaseIdx) {
205 if (! FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)){
206 throw std::runtime_error("Water tracer specified for non-water fluid system: " +
207 this->name(tracerIdx));
208 }
209 }
210 else if (phaseIdx == FluidSystem::oilPhaseIdx) {
211 if (! FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)){
212 throw std::runtime_error("Oil tracer specified for non-oil fluid system: " +
213 this->name(tracerIdx));
214 }
215 }
216 else if (phaseIdx == FluidSystem::gasPhaseIdx) {
217 if (! FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)){
218 throw std::runtime_error("Gas tracer specified for non-gas fluid system: " +
219 this->name(tracerIdx));
220 }
221 }
222
223 // Molecular diffusion coefficients of the free tracer and of the tracer in solution
224 // (TRDIFxxx). Tracers without solution part (e.g. water tracers) only have the free one.
225 const auto& tracerConfig = this->eclState_.tracer()[tracerIdx];
226 const Scalar freeD = tracerConfig.free_diffusion_coefficient;
227 const Scalar solutionD = hasSolutionPart_(phaseIdx) ? tracerConfig.solution_diffusion_coefficient
228 : freeD;
229 if (freeD != 0.0 || solutionD != 0.0) {
230 // The diffusion of the tracers needs the diffusivity of the faces, which is only
231 // available if diffusion is compiled in and activated with DIFFUSE.
232 const std::string diffKeyword = "TRDIF" + this->name(tracerIdx);
233 if constexpr (!enableDiffusion) {
234 throw std::runtime_error(diffKeyword + " is given for tracer " + this->name(tracerIdx) +
235 ", but this simulator was built without diffusion");
236 }
237 if (!this->eclState_.getSimulationConfig().isDiffusive()) {
238 throw std::runtime_error(diffKeyword + " is given for tracer " + this->name(tracerIdx) +
239 ", which requires the DIFFUSE keyword");
240 }
241 }
242 auto batch = std::ranges::find_if(this->tbatch,
243 [phaseIdx, freeD, solutionD](const auto& tr)
244 {
245 return tr.phaseIdx_ == phaseIdx &&
246 tr.freeDiffusionCoefficient_ == freeD &&
247 tr.solutionDiffusionCoefficient_ == solutionD;
248 });
249 if (batch == this->tbatch.end()) {
250 this->tbatch.emplace_back(phaseIdx);
251 batch = std::prev(this->tbatch.end());
252 batch->freeDiffusionCoefficient_ = freeD;
253 batch->solutionDiffusionCoefficient_ = solutionD;
254 }
255 batch->addTracer(tracerIdx, this->tracerConcentration_[tracerIdx]);
256
257 // resize free and solution volume storages
258 vol1_[0][phaseIdx].resize(this->freeTracerConcentration_[tracerIdx].size());
259 vol1_[1][phaseIdx].resize(this->freeTracerConcentration_[tracerIdx].size());
260 }
261
262 // will be valid after we move out of tracerMatrix_
263 TracerMatrix* base = this->tracerMatrix_.get();
264 for (auto& tr : this->tbatch) {
265 if (tr.numTracer() != 0) {
266 if (this->tracerMatrix_) {
267 tr.mat = std::move(this->tracerMatrix_);
268 }
269 else {
270 tr.mat = std::make_unique<TracerMatrix>(*base);
271 }
272 }
273 }
274
275 this->buildAquiferTracerConnections_(local_deferredLogger);
276 this->checkBoundaryTracers_(local_deferredLogger);
277
278 const auto& comm = simulator_.vanguard().grid().comm();
279 auto global_logger = gatherDeferredLogger(local_deferredLogger, comm);
280 if (comm.rank() == 0) {
281 global_logger.logMessages();
282 }
283 }
284
286 {
287 if (this->numTracers() == 0) {
288 return;
289 }
290
291 OPM_TIMEBLOCK(tracerUpdateCache);
293 }
294
299 {
300 if (this->numTracers() == 0) {
301 return;
302 }
303
304 OPM_TIMEBLOCK(tracerAdvance);
306 }
307
312 template <class Restarter>
313 void serialize(Restarter&)
314 { /* not implemented */ }
315
322 template <class Restarter>
323 void deserialize(Restarter&)
324 { /* not implemented */ }
325
326 template<class Serializer>
327 void serializeOp(Serializer& serializer)
328 {
329 serializer(static_cast<BaseType&>(*this));
330 serializer(tbatch);
331 }
332
333protected:
335 using BaseType::Free;
336 using BaseType::Solution;
337
338 // compute volume associated with free/solution concentration
339 template<TracerTypeIdx Index>
340 Scalar computeVolume_(const int tracerPhaseIdx,
341 const unsigned globalDofIdx,
342 const unsigned timeIdx) const
343 {
344 const auto& intQuants = simulator_.model().intensiveQuantities(globalDofIdx, timeIdx);
345 const auto& fs = intQuants.fluidState();
346 constexpr Scalar min_volume = 1e-10;
347
348 if constexpr (Index == Free) {
349 return std::max(decay<Scalar>(fs.saturation(tracerPhaseIdx)) *
350 decay<Scalar>(fs.invB(tracerPhaseIdx)) *
351 decay<Scalar>(intQuants.porosity()),
352 min_volume);
353 } else {
354 // vaporized oil
355 if (tracerPhaseIdx == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) {
356 return std::max(decay<Scalar>(fs.saturation(FluidSystem::gasPhaseIdx)) *
357 decay<Scalar>(fs.invB(FluidSystem::gasPhaseIdx)) *
358 decay<Scalar>(fs.Rv()) *
359 decay<Scalar>(intQuants.porosity()),
360 min_volume);
361 }
362
363 // dissolved gas
364 else if (tracerPhaseIdx == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas()) {
365 return std::max(decay<Scalar>(fs.saturation(FluidSystem::oilPhaseIdx)) *
366 decay<Scalar>(fs.invB(FluidSystem::oilPhaseIdx)) *
367 decay<Scalar>(fs.Rs()) *
368 decay<Scalar>(intQuants.porosity()),
369 min_volume);
370 }
371
372 return min_volume;
373 }
374 }
375
376 template<TracerTypeIdx Index>
377 std::pair<TracerEvaluation, bool>
378 computeFlux_(const int tracerPhaseIdx,
379 const ElementContext& elemCtx,
380 const unsigned scvfIdx,
381 const unsigned timeIdx) const
382 {
383 const auto& stencil = elemCtx.stencil(timeIdx);
384 const auto& scvf = stencil.interiorFace(scvfIdx);
385
386 const auto& extQuants = elemCtx.extensiveQuantities(scvfIdx, timeIdx);
387 const unsigned inIdx = extQuants.interiorIndex();
388
389 Scalar v;
390 unsigned upIdx;
391
392 if constexpr (Index == Free) {
393 upIdx = extQuants.upstreamIndex(tracerPhaseIdx);
394 const auto& intQuants = elemCtx.intensiveQuantities(upIdx, timeIdx);
395 const auto& inFs = intQuants.fluidState();
396
397 v = decay<Scalar>(extQuants.volumeFlux(tracerPhaseIdx)) *
398 decay<Scalar>(inFs.invB(tracerPhaseIdx));
399
400 } else {
401 // vaporized oil in gas phase
402 if (tracerPhaseIdx == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) {
403 upIdx = extQuants.upstreamIndex(FluidSystem::gasPhaseIdx);
404
405 const auto& intQuants = elemCtx.intensiveQuantities(upIdx, timeIdx);
406 const auto& fs = intQuants.fluidState();
407 v = decay<Scalar>(fs.invB(FluidSystem::gasPhaseIdx)) *
408 decay<Scalar>(extQuants.volumeFlux(FluidSystem::gasPhaseIdx)) *
409 decay<Scalar>(fs.Rv());
410 }
411 // dissolved gas in oil phase
412 else if (tracerPhaseIdx == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas()) {
413 upIdx = extQuants.upstreamIndex(FluidSystem::oilPhaseIdx);
414
415 const auto& intQuants = elemCtx.intensiveQuantities(upIdx, timeIdx);
416 const auto& fs = intQuants.fluidState();
417 v = decay<Scalar>(fs.invB(FluidSystem::oilPhaseIdx)) *
418 decay<Scalar>(extQuants.volumeFlux(FluidSystem::oilPhaseIdx)) *
419 decay<Scalar>(fs.Rs());
420 }
421 else {
422 upIdx = 0;
423 v = 0.0;
424 }
425 }
426
427 const Scalar A = scvf.area();
428 return inIdx == upIdx
429 ? std::pair{A * v * variable<TracerEvaluation>(1.0, 0), true}
430 : std::pair{A * v, false};
431 }
432
438 template<TracerTypeIdx Index>
439 static int carrierPhaseIdx_(const int tracerPhaseIdx)
440 {
441 if constexpr (Index == Free) {
442 return tracerPhaseIdx;
443 }
444 else {
445 return tracerPhaseIdx == FluidSystem::oilPhaseIdx ? FluidSystem::gasPhaseIdx
446 : FluidSystem::oilPhaseIdx;
447 }
448 }
449
453 static bool hasSolutionPart_(const int tracerPhaseIdx)
454 {
455 return (tracerPhaseIdx == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) ||
456 (tracerPhaseIdx == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas());
457 }
458
464 template<TracerTypeIdx Index, class FluidState>
465 static Scalar carrierSurfaceVolume_(const int tracerPhaseIdx,
466 const FluidState& fs,
467 const bool saturationWeighted)
468 {
469 const int phaseIdx = carrierPhaseIdx_<Index>(tracerPhaseIdx);
470 Scalar w = decay<Scalar>(fs.invB(phaseIdx));
471 if constexpr (Index == Solution) {
472 w *= tracerPhaseIdx == FluidSystem::oilPhaseIdx ? decay<Scalar>(fs.Rv())
473 : decay<Scalar>(fs.Rs());
474 }
475 if (saturationWeighted) {
476 w *= decay<Scalar>(fs.saturation(phaseIdx));
477 }
478 return w;
479 }
480
487 template<TracerTypeIdx Index, class FluidState>
488 static bool carrierPresent_(const int tracerPhaseIdx, const FluidState& fs)
489 {
490 return carrierSurfaceVolume_<Index>(tracerPhaseIdx, fs, /*saturationWeighted=*/true) > 0.0;
491 }
492
501 template<TracerTypeIdx Index>
502 TracerEvaluation
503 computeDiffusivity_(const int tracerPhaseIdx,
504 const ElementContext& elemCtx,
505 const unsigned scvfIdx,
506 const unsigned timeIdx) const
507 {
508 const auto& scvf = elemCtx.stencil(timeIdx).interiorFace(scvfIdx);
509
510 Scalar v = 0.0;
511 if constexpr (enableDiffusion) {
512 const auto& extQuants = elemCtx.extensiveQuantities(scvfIdx, timeIdx);
513 const auto& inFs = elemCtx.intensiveQuantities(extQuants.interiorIndex(), timeIdx).fluidState();
514 const auto& outFs = elemCtx.intensiveQuantities(extQuants.exteriorIndex(), timeIdx).fluidState();
515 if (carrierPresent_<Index>(tracerPhaseIdx, inFs) && carrierPresent_<Index>(tracerPhaseIdx, outFs)) {
516 v = decay<Scalar>(extQuants.diffusivity()) *
517 0.5 * (carrierSurfaceVolume_<Index>(tracerPhaseIdx, inFs, /*saturationWeighted=*/true) +
518 carrierSurfaceVolume_<Index>(tracerPhaseIdx, outFs, /*saturationWeighted=*/true));
519 }
520 }
521
522 return scvf.area() * v * variable<TracerEvaluation>(1.0, 0);
523 }
524
534 template<TracerTypeIdx Index>
535 TracerEvaluation
536 computeDispersivity_(const int tracerPhaseIdx,
537 const ElementContext& elemCtx,
538 const unsigned scvfIdx,
539 const unsigned timeIdx) const
540 {
541 Scalar flux = 0.0;
542 if constexpr (enableDispersion) {
543 if (this->dispersionActive_) {
544 const int phaseIdx = carrierPhaseIdx_<Index>(tracerPhaseIdx);
545 const auto& extQuants = elemCtx.extensiveQuantities(scvfIdx, timeIdx);
546 const unsigned inIdx = extQuants.interiorIndex();
547 const unsigned outIdx = extQuants.exteriorIndex();
548 const auto& inIq = elemCtx.intensiveQuantities(inIdx, timeIdx);
549 const auto& outIq = elemCtx.intensiveQuantities(outIdx, timeIdx);
550
551 if (carrierPresent_<Index>(tracerPhaseIdx, inIq.fluidState()) &&
552 carrierPresent_<Index>(tracerPhaseIdx, outIq.fluidState())) {
553 const Scalar normVelocityAvg = 0.5 * (inIq.normVelocityCell(phaseIdx) +
554 outIq.normVelocityCell(phaseIdx));
555 const Scalar weight =
556 0.5 * (carrierSurfaceVolume_<Index>(tracerPhaseIdx, inIq.fluidState(), /*saturationWeighted=*/false) +
557 carrierSurfaceVolume_<Index>(tracerPhaseIdx, outIq.fluidState(), /*saturationWeighted=*/false));
558 const Scalar dispersivity =
559 simulator_.problem().dispersivity(elemCtx.globalSpaceIndex(inIdx, timeIdx),
560 elemCtx.globalSpaceIndex(outIdx, timeIdx));
561 flux = weight * normVelocityAvg * dispersivity;
562 }
563 }
564 }
565
566 return flux * variable<TracerEvaluation>(1.0, 0);
567 }
568
569 template<TracerTypeIdx Index, class TrRe>
570 Scalar storage1_(const TrRe& tr,
571 const unsigned tIdx,
572 const unsigned I,
573 const unsigned I1,
574 const bool cache)
575 {
576 if (cache) {
577 return tr.storageOfTimeIndex1_[tIdx][I][Index];
578 } else {
579 return computeVolume_<Index>(tr.phaseIdx_, I1, 1) *
580 tr.concentration_[tIdx][I1][Index];
581 }
582 }
583
584 template<class TrRe>
586 const ElementContext& elemCtx,
587 const Scalar scvVolume,
588 const Scalar dt,
589 unsigned I,
590 unsigned I1)
591
592 {
593 if (tr.numTracer() == 0) {
594 return;
595 }
596
597 const TracerEvaluation fVol = computeVolume_<Free>(tr.phaseIdx_, I, 0) * variable<TracerEvaluation>(1.0, 0);
598 const TracerEvaluation sVol = computeVolume_<Solution>(tr.phaseIdx_, I, 0) * variable<TracerEvaluation>(1.0, 0);
599 tr.dVol_[Solution][I] += sVol.value() * scvVolume - vol1_[1][tr.phaseIdx_][I];
600 tr.dVol_[Free][I] += fVol.value() * scvVolume - vol1_[0][tr.phaseIdx_][I];
601 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
602 // Free part
603 const Scalar fStorageOfTimeIndex0 = fVol.value() * tr.concentration_[tIdx][I][Free];
604 const Scalar fLocalStorage = (fStorageOfTimeIndex0 - storage1_<Free>(tr, tIdx, I, I1,
605 elemCtx.enableStorageCache())) * scvVolume / dt;
606 tr.residual_[tIdx][I][Free] += fLocalStorage; // residual + flux
607
608 // Solution part
609 const Scalar sStorageOfTimeIndex0 = sVol.value() * tr.concentration_[tIdx][I][Solution];
610 const Scalar sLocalStorage = (sStorageOfTimeIndex0 - storage1_<Solution>(tr, tIdx, I, I1,
611 elemCtx.enableStorageCache())) * scvVolume / dt;
612 tr.residual_[tIdx][I][Solution] += sLocalStorage; // residual + flux
613 }
614
615 // Derivative matrix
616 (*tr.mat)[I][I][Free][Free] += fVol.derivative(0) * scvVolume/dt;
617 (*tr.mat)[I][I][Solution][Solution] += sVol.derivative(0) * scvVolume/dt;
618 }
619
620 template<class TrRe>
622 const ElementContext& elemCtx,
623 unsigned scvfIdx,
624 unsigned I,
625 unsigned J,
626 const Scalar dt)
627 {
628 if (tr.numTracer() == 0) {
629 return;
630 }
631
632 const auto& [fFlux, isUpF] = computeFlux_<Free>(tr.phaseIdx_, elemCtx, scvfIdx, 0);
633 const auto& [sFlux, isUpS] = computeFlux_<Solution>(tr.phaseIdx_, elemCtx, scvfIdx, 0);
634
635 // Fickian coefficients of the free and the solution tracer: diffusion (the geometric diffusivity
636 // scaled by the molecular diffusion coefficient of the free and the solution tracer of the
637 // batch, TRDIFxxx) plus dispersion (DISPERC). Only evaluated if diffusion or dispersion is
638 // active, as this requires extra quantities for every face.
639 const bool hasSolutionPart = hasSolutionPart_(tr.phaseIdx_);
640 const bool hasDispersion = enableDispersion && this->dispersionActive_;
641 const bool hasDiffusionFree = enableDiffusion && tr.freeDiffusionCoefficient_ != 0.0;
642 const bool hasDiffusionSolution = enableDiffusion && hasSolutionPart &&
643 tr.solutionDiffusionCoefficient_ != 0.0;
644 const bool hasFickianFree = hasDiffusionFree || hasDispersion;
645 const bool hasFickianSolution = hasDiffusionSolution || (hasDispersion && hasSolutionPart);
646 TracerEvaluation fickianFree = 0.0;
647 TracerEvaluation fickianSolution = 0.0;
648 if (hasDiffusionFree) {
649 fickianFree += computeDiffusivity_<Free>(tr.phaseIdx_, elemCtx, scvfIdx, 0) *
650 tr.freeDiffusionCoefficient_;
651 }
652 if (hasDiffusionSolution) {
653 fickianSolution += computeDiffusivity_<Solution>(tr.phaseIdx_, elemCtx, scvfIdx, 0) *
654 tr.solutionDiffusionCoefficient_;
655 }
656 if (hasDispersion) {
657 fickianFree += computeDispersivity_<Free>(tr.phaseIdx_, elemCtx, scvfIdx, 0);
658 if (hasSolutionPart) {
659 fickianSolution += computeDispersivity_<Solution>(tr.phaseIdx_, elemCtx, scvfIdx, 0);
660 }
661 }
662
663 tr.dVol_[Solution][I] += sFlux.value() * dt;
664 tr.dVol_[Free][I] += fFlux.value() * dt;
665 const int fGlobalUpIdx = isUpF ? I : J;
666 const int sGlobalUpIdx = isUpS ? I : J;
667 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
668 // Free and solution fluxes
669 tr.residual_[tIdx][I][Free] += fFlux.value()*tr.concentration_[tIdx][fGlobalUpIdx][Free]; // residual + flux
670 tr.residual_[tIdx][I][Solution] += sFlux.value()*tr.concentration_[tIdx][sGlobalUpIdx][Solution]; // residual + flux
671
672 // Fickian flux J = -(D + D_disp) * grad(c), implicit in the tracer concentration
673 if (hasFickianFree) {
674 const Scalar gradientFree = tr.concentration_[tIdx][J][Free] - tr.concentration_[tIdx][I][Free];
675 tr.residual_[tIdx][I][Free] -= fickianFree.value() * gradientFree;
676 }
677 if (hasFickianSolution) {
678 const Scalar gradientSolution = tr.concentration_[tIdx][J][Solution] - tr.concentration_[tIdx][I][Solution];
679 tr.residual_[tIdx][I][Solution] -= fickianSolution.value() * gradientSolution;
680 }
681 }
682
683 // Derivative matrix, as in the TPFA linearizer of the main simulator: this element (cell I) writes
684 // d(residual_I)/d(c_I) into the diagonal and d(residual_J)/d(c_I) = -d(residual_I)/d(c_I) into the
685 // entry (J, I), i.e. the row of the neighbor J and the column of I. The entry (J, I) is only
686 // written from this element, which makes the assembly thread safe. The coupling of the interior
687 // cell I to a neighboring cell J that is not interior is not assembled (the rows of those
688 // cells are Dirichlet rows), so the matrix is decoupled between the ranks.
689 // The flux is carried by the concentration of the upstream cell.
690 if (isUpF) {
691 (*tr.mat)[I][I][Free][Free] += fFlux.derivative(0);
692 (*tr.mat)[J][I][Free][Free] -= fFlux.derivative(0);
693 }
694 if (isUpS) {
695 (*tr.mat)[I][I][Solution][Solution] += sFlux.derivative(0);
696 (*tr.mat)[J][I][Solution][Solution] -= sFlux.derivative(0);
697 }
698
699 // Diffusion and dispersion: d(residual_I)/d(c_I) = +D and d(residual_J)/d(c_I) = -D,
700 // for every face irrespective of the flow direction.
701 if (hasFickianFree) {
702 (*tr.mat)[I][I][Free][Free] += fickianFree.derivative(0);
703 (*tr.mat)[J][I][Free][Free] -= fickianFree.derivative(0);
704 }
705 if (hasFickianSolution) {
706 (*tr.mat)[I][I][Solution][Solution] += fickianSolution.derivative(0);
707 (*tr.mat)[J][I][Solution][Solution] -= fickianSolution.derivative(0);
708 }
709 }
710
711 template<class TrRe, class Well>
713 const Well& well)
714 {
715 if (tr.numTracer() == 0) {
716 return;
717 }
718
719 const auto& eclWell = well.wellEcl();
720
721 // Init. well output to zero
722 auto& tracerRate = this->wellTracerRate_[eclWell.seqIndex()];
723 auto& solTracerRate = this->wellSolTracerRate_[eclWell.seqIndex()];
724 auto& freeTracerRate = this->wellFreeTracerRate_[eclWell.seqIndex()];
725 auto* mswTracerRate = eclWell.isMultiSegment()
726 ? &this->mSwTracerRate_[eclWell.seqIndex()]
727 : nullptr;
728 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
729 tracerRate[tr.idx_[tIdx]] = {this->name(tr.idx_[tIdx]), 0.0};
730 freeTracerRate[tr.idx_[tIdx]] = {this->wellfname(tr.idx_[tIdx]), 0.0};
731 solTracerRate[tr.idx_[tIdx]] = {this->wellsname(tr.idx_[tIdx]), 0.0};
732 if (eclWell.isMultiSegment()) {
733 auto& wtr = mswTracerRate->at(tr.idx_[tIdx]) = {this->name(tr.idx_[tIdx])};;
734 wtr.rate.reserve(eclWell.getConnections().size());
735 for (std::size_t i = 0; i < eclWell.getConnections().size(); ++i) {
736 wtr.rate.emplace(eclWell.getConnections().get(i).segment(), 0.0);
737 }
738 }
739 }
740
741 std::vector<Scalar> wtracer(tr.numTracer());
742 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
743 wtracer[tIdx] = this->currentConcentration_(eclWell, this->name(tr.idx_[tIdx]),
744 simulator_.problem().wellModel().summaryState());
745 }
746
747 const Scalar dt = simulator_.timeStepSize();
748 const auto& ws = simulator_.problem().wellModel().wellState().well(well.name());
749 const auto well_eff = well.wellEfficiencyFactor(); // Needed to convert ws.perf_data.phase_mixing_rates to effective rates
750 for (std::size_t i = 0; i < ws.perf_data.size(); ++i) {
751 const auto I = ws.perf_data.cell_index[i];
752 const Scalar rate = well.volumetricSurfaceRateForConnection(I, tr.phaseIdx_); // Includes (accumulated) well efficiency factor
753 Scalar rate_s;
754
755 if (tr.phaseIdx_ == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) {
756 rate_s = ws.perf_data.phase_mixing_rates[i][ws.vaporized_oil] * well_eff;
757 }
758 else if (tr.phaseIdx_ == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas()) {
759 rate_s = ws.perf_data.phase_mixing_rates[i][ws.dissolved_gas] * well_eff;
760 }
761 else {
762 rate_s = 0.0;
763 }
764
765 const Scalar rate_f = rate - rate_s;
766 if (rate_f > 0) {
767 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
768 const Scalar delta = rate_f * wtracer[tIdx];
769 // Injection of free tracer only
770 tr.residual_[tIdx][I][Free] -= delta;
771
772 // Store _injector_ tracer rate for reporting
773 // (can be done here since WTRACER is constant)
774 tracerRate[tr.idx_[tIdx]].rate += delta;
775 freeTracerRate[tr.idx_[tIdx]].rate += delta;
776 if (eclWell.isMultiSegment()) {
777 (*mswTracerRate)[tr.idx_[tIdx]].rate[eclWell.getConnections().get(i).segment()] += delta;
778 }
779 }
780 tr.dVol_[Free][I] -= rate_f * dt;
781 }
782 else if (rate_f < 0) {
783 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
784 const Scalar delta = rate_f * wtracer[tIdx];
785 // Store _injector_ tracer rate for cross-flowing well connections
786 // (can be done here since WTRACER is constant)
787 tracerRate[tr.idx_[tIdx]].rate += delta;
788 freeTracerRate[tr.idx_[tIdx]].rate += delta;
789
790 // Production of free tracer
791 tr.residual_[tIdx][I][Free] -= rate_f * tr.concentration_[tIdx][I][Free];
792 }
793 tr.dVol_[Free][I] -= rate_f * dt;
794
795 // Derivative matrix for free tracer producer
796 (*tr.mat)[I][I][Free][Free] -= rate_f * variable<TracerEvaluation>(1.0, 0).derivative(0);
797 }
798 if (rate_s < 0) {
799 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
800 // Production of solution tracer
801 tr.residual_[tIdx][I][Solution] -= rate_s * tr.concentration_[tIdx][I][Solution];
802 }
803 tr.dVol_[Solution][I] -= rate_s * dt;
804
805 // Derivative matrix for solution tracer producer
806 (*tr.mat)[I][I][Solution][Solution] -= rate_s * variable<TracerEvaluation>(1.0, 0).derivative(0);
807 }
808 }
809 }
810
825 template<class TrRe>
827 const ElementContext& elemCtx,
828 const unsigned I,
829 const Scalar dt)
830 {
831 if (tr.numTracer() == 0) {
832 return;
833 }
834
835 const auto& problem = simulator_.problem();
836 if (!problem.nonTrivialBoundaryConditions()) {
837 return;
838 }
839
840 if (!elemCtx.onBoundary()) {
841 return;
842 }
843
844 // The boundary flux of the flow equations, per unit area, is obtained from the
845 // problem for each boundary face, as done when assembling the flow equations.
848 BoundaryContext boundaryCtx(elemCtx);
849 if (boundaryCtx.intersection(0).neighbor()) {
850 // move the iterator to the first boundary
851 boundaryCtx.increment();
852 }
853
854 const auto& stencil = elemCtx.stencil(/*timeIdx=*/0);
855 const auto& bcstate = simulator_.vanguard().schedule()[problem.episodeIndex()].bcstate;
856 const unsigned numBoundaryFaces = boundaryCtx.numBoundaryFaces(/*timeIdx=*/0);
857 for (unsigned bfIdx = 0; bfIdx < numBoundaryFaces; ++bfIdx, boundaryCtx.increment()) {
858 const auto& bf = stencil.boundaryFace(bfIdx);
859 const int dirId = bf.dirId();
860 if (dirId < 0) { // not for NNCs
861 continue;
862 }
863
864 const int bcIndex = problem.boundaryConditionIndex(I, dirId);
865 if (bcIndex == 0) {
866 continue;
867 }
868
869 const BCType type = problem.boundaryCondition(I, dirId).first;
870 if (type != BCType::RATE && type != BCType::FREE && type != BCType::DIRICHLET) {
871 continue;
872 }
873
874 BoundaryRateVector bdyFlux;
875 problem.boundary(bdyFlux, boundaryCtx, bfIdx, /*timeIdx=*/0);
876 const unsigned pvtRegionIdx = problem.pvtRegionIndex(I);
877 const Scalar boundaryArea = bf.area() * decay<Scalar>(elemCtx.intensiveQuantities(0, 0).extrusionFactor());
878
879 // Surface volume rate out of the cell of the main component of a phase (water in the
880 // water phase etc.), converted with the reference density of that phase if the flux
881 // is a mass flux. The rate of the tracer phase is zero if the BCPROP component is
882 // not the phase of the tracer.
883 const auto phaseFlux = [&](const int phaseIdx)
884 {
885 const int compIdx = phaseIdx == FluidSystem::waterPhaseIdx ? FluidSystem::waterCompIdx
886 : phaseIdx == FluidSystem::oilPhaseIdx ? FluidSystem::oilCompIdx
887 : FluidSystem::gasCompIdx;
888 Scalar flux = decay<Scalar>(bdyFlux[FluidSystem::canonicalToActiveCompIdx(compIdx)]) * boundaryArea;
889 if constexpr (!getPropValue<TypeTag, Properties::BlackoilConserveSurfaceVolume>()) {
890 flux /= FluidSystem::referenceDensity(phaseIdx, pvtRegionIdx);
891 }
892 return flux;
893 };
894 const Scalar rateOut = phaseFlux(tr.phaseIdx_);
895 if (rateOut == Scalar{0}) {
896 continue;
897 }
898
899 // Outflow is split in a free part and a solution part (vaporized oil in the gas
900 // phase for oil tracers, dissolved gas in the oil phase for gas tracers), as for
901 // producer wells. The component fluxes are F_o + Rv F_g (oil) and F_g + Rs F_o
902 // (gas) in terms of the free phase fluxes F_o and F_g. Inflow is free only.
903 Scalar rateFree = rateOut;
904 Scalar rateSol = 0.0;
905 const bool oilSolution = tr.phaseIdx_ == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil();
906 const bool gasSolution = tr.phaseIdx_ == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas();
907 if (rateOut > 0 && (oilSolution || gasSolution)) {
908 // Bind the intensive quantities, as the model may return them by value.
909 const auto& intQuants = simulator_.model().intensiveQuantities(I, /*timeIdx=*/0);
910 const auto& fs = intQuants.fluidState();
911 const Scalar Rs = FluidSystem::enableDissolvedGas() ? decay<Scalar>(fs.Rs()) : Scalar{0};
912 const Scalar Rv = FluidSystem::enableVaporizedOil() ? decay<Scalar>(fs.Rv()) : Scalar{0};
913 const Scalar Qo = phaseFlux(FluidSystem::oilPhaseIdx);
914 const Scalar Qg = phaseFlux(FluidSystem::gasPhaseIdx);
915 const Scalar det = 1.0 - Rs * Rv;
916 const Scalar Fo = (Qo - Rv * Qg) / det;
917 const Scalar Fg = (Qg - Rs * Qo) / det;
918 if (oilSolution) {
919 rateFree = Fo;
920 rateSol = Rv * Fg;
921 }
922 else {
923 rateFree = Fg;
924 rateSol = Rs * Fo;
925 }
926 }
927
928 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
929 if (rateOut < 0) {
930 // Inflow: concentration from BCTRACER, no tracer if not specified
931 const auto bcConc = bcstate.tracerConcentration(bcIndex,
932 this->name(tr.idx_[tIdx]));
933 tr.residual_[tIdx][I][Free] += rateOut * bcConc.value_or(0.0);
934 }
935 else {
936 // Outflow: tracer leaves with the concentrations of the cell
937 tr.residual_[tIdx][I][Free] += rateFree * tr.concentration_[tIdx][I][Free];
938 tr.residual_[tIdx][I][Solution] += rateSol * tr.concentration_[tIdx][I][Solution];
939 }
940 }
941 tr.dVol_[Free][I] += rateFree * dt;
942 tr.dVol_[Solution][I] += rateSol * dt;
943
944 if (rateOut > 0) {
945 // Derivative matrix for outflow
946 (*tr.mat)[I][I][Free][Free] += rateFree * variable<TracerEvaluation>(1.0, 0).derivative(0);
947 (*tr.mat)[I][I][Solution][Solution] += rateSol * variable<TracerEvaluation>(1.0, 0).derivative(0);
948 }
949 }
950 }
951
952 template<class TrRe>
954 const Scalar dt,
955 unsigned I)
956 {
957 if (tr.numTracer() == 0) {
958 return;
959 }
960
961 // Skip if solution tracers do not exist
962 if (tr.phaseIdx_ == FluidSystem::waterPhaseIdx ||
963 (tr.phaseIdx_ == FluidSystem::gasPhaseIdx && !FluidSystem::enableDissolvedGas()) ||
964 (tr.phaseIdx_ == FluidSystem::oilPhaseIdx && !FluidSystem::enableVaporizedOil()))
965 {
966 return;
967 }
968
969 const Scalar& dsVol = tr.dVol_[Solution][I];
970 const Scalar& dfVol = tr.dVol_[Free][I];
971
972 // Source term determined by sign of dsVol: if dsVol > 0 then ms -> mf, else mf -> ms
973 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
974 if (dsVol >= 0) {
975 const auto delta = (dfVol / dt) * tr.concentration_[tIdx][I][Free];
976 tr.residual_[tIdx][I][Free] -= delta;
977 tr.residual_[tIdx][I][Solution] += delta;
978 }
979 else {
980 const auto delta = (dsVol / dt) * tr.concentration_[tIdx][I][Solution];
981 tr.residual_[tIdx][I][Free] += delta;
982 tr.residual_[tIdx][I][Solution] -= delta;
983 }
984 }
985
986 // Derivative matrix
987 if (dsVol >= 0) {
988 const auto delta = (dfVol / dt) * variable<TracerEvaluation>(1.0, 0).derivative(0);
989 (*tr.mat)[I][I][Free][Free] -= delta;
990 (*tr.mat)[I][I][Solution][Free] += delta;
991 }
992 else {
993 const auto delta = (dsVol / dt) * variable<TracerEvaluation>(1.0, 0).derivative(0);
994 (*tr.mat)[I][I][Free][Solution] += delta;
995 (*tr.mat)[I][I][Solution][Solution] -= delta;
996 }
997 }
998
1000 {
1001 // Note that we formulate the equations in terms of a concentration update
1002 // (compared to previous time step) and not absolute concentration.
1003 // This implies that current concentration (tr.concentration_[][]) contributes
1004 // to the rhs both through storage and flux terms.
1005 // Compare also advanceTracerFields(...) below.
1006
1007 DeferredLogger local_deferredLogger{};
1009 {
1010 OPM_TIMEBLOCK(tracerAssemble);
1011 for (auto& tr : tbatch) {
1012 if (tr.numTracer() != 0) {
1013 (*tr.mat) = 0.0;
1014 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1015 tr.residual_[tIdx] = 0.0;
1016 }
1017 }
1018 }
1019
1020 this->wellTracerRate_.clear();
1021 this->wellFreeTracerRate_.clear();
1022 this->wellSolTracerRate_.clear();
1023
1024 // educated guess for new container size
1025 const auto num_msw = this->mSwTracerRate_.size();
1026 this->mSwTracerRate_.clear();
1027
1028 // Well terms
1029 const auto& wellPtrs = simulator_.problem().wellModel().localNonshutWells();
1030 this->wellTracerRate_.reserve(wellPtrs.size());
1031 this->wellFreeTracerRate_.reserve(wellPtrs.size());
1032 this->wellSolTracerRate_.reserve(wellPtrs.size());
1033 this->mSwTracerRate_.reserve(num_msw);
1034 for (const auto& wellPtr : wellPtrs) {
1035 // Resize vectors of well tracer rates to total number of tracers
1036 const auto& eclWell = wellPtr->wellEcl();
1037 this->wellTracerRate_[eclWell.seqIndex()].resize(this->numTracers());
1038 this->wellFreeTracerRate_[eclWell.seqIndex()].resize(this->numTracers());
1039 this->wellSolTracerRate_[eclWell.seqIndex()].resize(this->numTracers());
1040 auto* mswTracerRate = eclWell.isMultiSegment()
1041 ? &this->mSwTracerRate_[eclWell.seqIndex()]
1042 : nullptr;
1043 if (mswTracerRate) {
1044 mswTracerRate->resize(this->numTracers());
1045 }
1046 for (auto& tr : tbatch) {
1047 this->assembleTracerEquationWell(tr, *wellPtr);
1048 }
1049 }
1050
1051 for (auto& tr : tbatch) {
1053 }
1054
1055 // Parallel loop over element chunks
1056 #ifdef _OPENMP
1057 #pragma omp parallel for
1058 #endif
1059 for (std::size_t ci = 0; ci < element_chunks_.size(); ++ci) {
1060 const auto& chunk = element_chunks_[ci];
1061 ElementContext elemCtx(simulator_);
1062 const Scalar dt = elemCtx.simulator().timeStepSize();
1063
1064 for (const auto& elem : chunk) {
1065 elemCtx.updateStencil(elem);
1066 const std::size_t I = elemCtx.globalSpaceIndex(/*dofIdx=*/ 0, /*timeIdx=*/0);
1067
1068 if (elem.partitionType() != Dune::InteriorEntity) {
1069 // Dirichlet boundary conditions for parallel matrix
1070 // This is safe as each element has a unique I. So each thread
1071 // always writes to different memory locations in the shared arrays.
1072 for (const auto& tr : tbatch) {
1073 if (tr.numTracer() != 0) {
1074 (*tr.mat)[I][I][0][0] = 1.;
1075 (*tr.mat)[I][I][1][1] = 1.;
1076 }
1077 }
1078 continue;
1079 }
1080 elemCtx.updateAllIntensiveQuantities();
1081 elemCtx.updateAllExtensiveQuantities();
1082
1083 const Scalar extrusionFactor =
1084 elemCtx.intensiveQuantities(/*dofIdx=*/ 0, /*timeIdx=*/0).extrusionFactor();
1085 Valgrind::CheckDefined(extrusionFactor);
1086 assert(isfinite(extrusionFactor));
1087 assert(extrusionFactor > 0.0);
1088 const Scalar scvVolume =
1089 elemCtx.stencil(/*timeIdx=*/0).subControlVolume(/*dofIdx=*/ 0).volume() * extrusionFactor;
1090 const std::size_t I1 = elemCtx.globalSpaceIndex(/*dofIdx=*/ 0, /*timeIdx=*/1);
1091
1092 // This is safe as each element has a unique I. So each thread
1093 // always writes to different memory locations in the shared arrays.
1094 for (auto& tr : tbatch) {
1095 if (tr.numTracer() == 0) {
1096 continue;
1097 }
1098 this->assembleTracerEquationVolume(tr, elemCtx, scvVolume, dt, I, I1);
1099 }
1100
1101 const std::size_t numInteriorFaces = elemCtx.numInteriorFaces(/*timIdx=*/0);
1102 for (unsigned scvfIdx = 0; scvfIdx < numInteriorFaces; scvfIdx++) {
1103 const auto& face = elemCtx.stencil(0).interiorFace(scvfIdx);
1104 const unsigned j = face.exteriorIndex();
1105 const unsigned J = elemCtx.globalSpaceIndex(/*dofIdx=*/ j, /*timIdx=*/0);
1106 for (auto& tr : tbatch) {
1107 if (tr.numTracer() == 0) {
1108 continue;
1109 }
1110 this->assembleTracerEquationFlux(tr, elemCtx, scvfIdx, I, J, dt);
1111 }
1112 }
1113
1114 // Boundary conditions (BCCON + BCPROP + BCTRACER)
1115 for (auto& tr : tbatch) {
1116 this->assembleTracerEquationBoundary(tr, elemCtx, I, dt);
1117 }
1118
1119 // Source terms (mass transfer between free and solution tracer)
1120 for (auto& tr : tbatch) {
1121 if (tr.numTracer() == 0) {
1122 continue;
1123 }
1124 this->assembleTracerEquationSource(tr, dt, I);
1125 }
1126 }
1127 }
1128 }
1129 OPM_END_PARALLEL_TRY_CATCH_LOG(local_deferredLogger,
1130 "assembleTracerEquations() failed: ",
1131 true, simulator_.gridView().comm())
1132
1133 // Communicate overlap using grid Communication
1134 for (auto& tr : tbatch) {
1135 if (tr.numTracer() == 0) {
1136 continue;
1137 }
1139 simulator_.gridView());
1140 simulator_.gridView().communicate(handle, Dune::InteriorBorder_All_Interface,
1141 Dune::ForwardCommunication);
1142 }
1143 }
1144
1145 template<TracerTypeIdx Index, class TrRe>
1146 void updateElem(TrRe& tr,
1147 const Scalar scvVolume,
1148 const unsigned globalDofIdx)
1149 {
1150 const Scalar vol1 = computeVolume_<Index>(tr.phaseIdx_, globalDofIdx, 0);
1151 vol1_[Index][tr.phaseIdx_][globalDofIdx] = vol1 * scvVolume;
1152 tr.dVol_[Index][globalDofIdx] = 0.0;
1153 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1154 tr.storageOfTimeIndex1_[tIdx][globalDofIdx][Index] =
1155 vol1 * tr.concentrationInitial_[tIdx][globalDofIdx][Index];
1156 }
1157 }
1158
1160 {
1161 for (auto& tr : tbatch) {
1162 if (tr.numTracer() != 0) {
1163 tr.concentrationInitial_ = tr.concentration_;
1164 }
1165 }
1166
1167 // Parallel loop over element chunks
1168 #ifdef _OPENMP
1169 #pragma omp parallel for
1170 #endif
1171 for (std::size_t ci = 0; ci < element_chunks_.size(); ++ci) {
1172 const auto& chunk = element_chunks_[ci];
1173 ElementContext elemCtx(simulator_);
1174
1175 for (const auto& elem : chunk) {
1176 elemCtx.updatePrimaryStencil(elem);
1177 elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0);
1178 const Scalar extrusionFactor = elemCtx.intensiveQuantities(/*dofIdx=*/ 0, /*timeIdx=*/0).extrusionFactor();
1179 const Scalar scvVolume = elemCtx.stencil(/*timeIdx=*/0).subControlVolume(/*dofIdx=*/ 0).volume() * extrusionFactor;
1180 const unsigned globalDofIdx = elemCtx.globalSpaceIndex(0, /*timeIdx=*/0);
1181
1182 for (auto& tr : tbatch) {
1183 if (tr.numTracer() == 0) {
1184 continue;
1185 }
1186 // This is safe as each element has a unique globalDofIdx. So each thread
1187 // always writes to different memory locations in the shared arrays.
1188 updateElem<Free>(tr, scvVolume, globalDofIdx);
1189 updateElem<Solution>(tr, scvVolume, globalDofIdx);
1190 }
1191 }
1192 }
1193 }
1194
1195 template<TracerTypeIdx Index, class TrRe>
1196 void copyForOutput(TrRe& tr,
1197 const std::vector<TracerVector>& dx,
1198 const Scalar S,
1199 const unsigned tIdx,
1200 const unsigned globalDofIdx,
1201 std::vector<TracerVectorSingle>& sc)
1202 {
1203 constexpr Scalar tol_gas_sat = 1e-6;
1204 tr.concentration_[tIdx][globalDofIdx][Index] -= dx[tIdx][globalDofIdx][Index];
1205 if (tr.concentration_[tIdx][globalDofIdx][Index] < 0.0 || S < tol_gas_sat) {
1206 tr.concentration_[tIdx][globalDofIdx][Index] = 0.0;
1207 }
1208 sc[tr.idx_[tIdx]][globalDofIdx] = tr.concentration_[tIdx][globalDofIdx][Index];
1209 }
1210
1211 template<TracerTypeIdx Index, class TrRe>
1212 void assignRates(const TrRe& tr,
1213 const Well& eclWell,
1214 const std::size_t i,
1215 const std::size_t I,
1216 const Scalar rate,
1217 std::vector<WellTracerRate<Scalar>>& tracerRate,
1218 std::vector<MSWellTracerRate<Scalar>>* mswTracerRate,
1219 std::vector<WellTracerRate<Scalar>>& splitRate)
1220 {
1221 if (rate < 0) {
1222 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1223 // Store _producer_ free tracer rate for reporting
1224 const Scalar delta = rate * tr.concentration_[tIdx][I][Index];
1225 tracerRate[tr.idx_[tIdx]].rate += delta;
1226 splitRate[tr.idx_[tIdx]].rate += delta;
1227 if (eclWell.isMultiSegment()) {
1228 (*mswTracerRate)[tr.idx_[tIdx]].rate[eclWell.getConnections().get(i).segment()] += delta;
1229 }
1230 }
1231 }
1232 }
1233
1235 const auto& wellPtrs = simulator_.problem().wellModel().localNonshutWells();
1236 for (const auto& wellPtr : wellPtrs) {
1237 const auto& eclWell = wellPtr->wellEcl();
1238 const auto well_seq_index = eclWell.seqIndex();
1239 const auto inv_well_eff_factor = 1.0 / std::max(Scalar{1.0e-10}, wellPtr->wellEfficiencyFactor());
1240
1241 std::ranges::for_each(this->wellTracerRate_[well_seq_index], [&](WellTracerRate<Scalar>& wtr) {
1242 wtr.rate *= inv_well_eff_factor;
1243 });
1244 std::ranges::for_each(this->wellFreeTracerRate_[well_seq_index], [&](WellTracerRate<Scalar>& wtr) {
1245 wtr.rate *= inv_well_eff_factor;
1246 });
1247 std::ranges::for_each(this->wellSolTracerRate_[well_seq_index], [&](WellTracerRate<Scalar>& wtr) {
1248 wtr.rate *= inv_well_eff_factor;
1249 });
1250 if (eclWell.isMultiSegment()) {
1251 std::ranges::for_each(this->mSwTracerRate_[well_seq_index], [&](MSWellTracerRate<Scalar>& wtr) {
1252 std::ranges::for_each(wtr.rate, [&](auto& item) {
1253 item.second *= inv_well_eff_factor;
1254 });
1255 });
1256 }
1257 }
1258 }
1259
1272 void checkBoundaryTracers_(DeferredLogger& deferredLogger) const
1273 {
1274 std::unordered_map<std::string, int> tracer_name_to_idx;
1275 for (int tracerIdx = 0; tracerIdx < this->numTracers(); ++tracerIdx) {
1276 tracer_name_to_idx.emplace(this->name(tracerIdx), tracerIdx);
1277 }
1278
1279 const bool logging = simulator_.vanguard().grid().comm().rank() == 0;
1280 const auto& schedule = simulator_.vanguard().schedule();
1281 std::set<std::pair<int, std::string>> warned;
1282 std::set<int> flowIndices; // RATE, FREE or DIRICHLET
1283 std::set<int> tracerIndices;
1284 for (std::size_t step = 0; step < schedule.size(); ++step) {
1285 for (const auto& face : schedule[step].bcstate) {
1286 if (face.bctype == BCType::RATE || face.bctype == BCType::FREE ||
1287 face.bctype == BCType::DIRICHLET) {
1288 flowIndices.insert(face.index);
1289 }
1290
1291 for (const auto& tracerbc : face.tracerbcvalues) {
1292 tracerIndices.insert(face.index);
1293 const auto pos = tracer_name_to_idx.find(tracerbc.tracer);
1294 if (pos == tracer_name_to_idx.end()) {
1295 throw std::runtime_error(fmt::format("BCTRACER: tracer {} (INDEX {}) is not declared in TRACER",
1296 tracerbc.tracer, face.index));
1297 }
1298
1299 const int phaseIdx = this->tracerPhaseIdx_[pos->second];
1300 const bool samePhase =
1301 (face.component == BCComponent::WATER && phaseIdx == FluidSystem::waterPhaseIdx) ||
1302 (face.component == BCComponent::OIL && phaseIdx == FluidSystem::oilPhaseIdx) ||
1303 (face.component == BCComponent::GAS && phaseIdx == FluidSystem::gasPhaseIdx);
1304 // Faces without a BCPROP component (yet), or with a non-phase component, are not checked
1305 const bool isPhaseComponent = face.component == BCComponent::WATER ||
1306 face.component == BCComponent::OIL ||
1307 face.component == BCComponent::GAS;
1308 if (isPhaseComponent && !samePhase &&
1309 warned.emplace(face.index, tracerbc.tracer).second && logging)
1310 {
1311 deferredLogger.warning(fmt::format("BCTRACER: the BCPROP component of INDEX {} is not the phase "
1312 "of tracer {}, so the tracer will not enter through this "
1313 "boundary", face.index, tracerbc.tracer));
1314 }
1315 }
1316 }
1317 }
1318
1319 for (const int index : tracerIndices) {
1320 if (!flowIndices.contains(index) && logging) {
1321 deferredLogger.warning(fmt::format("BCTRACER: INDEX {} has no BCPROP of type RATE, FREE or DIRICHLET. "
1322 "BCTRACER is only used for boundaries with a flow and is ignored.",
1323 index));
1324 }
1325 }
1326 }
1327
1329 {
1330 aquifer_tracer_cells_.clear();
1331
1332 const auto& aquifer_cfg = this->eclState_.aquifer();
1333 if (!aquifer_cfg.active()) {
1334 return;
1335 }
1336
1337 const auto& specs = aquifer_cfg.aquiferTracers();
1338 if (specs.empty()) {
1339 return;
1340 }
1341
1342 std::unordered_map<std::string, int> tracer_name_to_idx;
1343 for (int tracerIdx = 0; tracerIdx < this->numTracers(); ++tracerIdx) {
1344 tracer_name_to_idx.emplace(this->name(tracerIdx), tracerIdx);
1345 }
1346
1347 const auto& vanguard = simulator_.vanguard();
1348 for (const auto& spec : specs) {
1349 if (!aquifer_cfg.hasAnalyticalAquifer(spec.aquifer_id)) {
1350 continue;
1351 }
1352
1353 const auto tracer_pos = tracer_name_to_idx.find(spec.tracer_name);
1354 if (tracer_pos == tracer_name_to_idx.end()) {
1355 if (simulator_.vanguard().grid().comm().rank() == 0) {
1356 deferredLogger.warning(fmt::format("AQANTRC tracer '{}' is not declared in TRACER",
1357 spec.tracer_name));
1358 }
1359 continue;
1360 }
1361
1362 if (!aquifer_cfg.connections().hasAquiferConnections(spec.aquifer_id)) {
1363 continue;
1364 }
1365
1366 const int tracerIdx = tracer_pos->second;
1367 const int phaseIdx = this->tracerPhaseIdx_[tracerIdx];
1368
1369 for (const auto& conn : aquifer_cfg.connections().getConnections(spec.aquifer_id)) {
1370 const int cellIdx = vanguard.compressedIndex(conn.global_index);
1371 if (cellIdx < 0) {
1372 continue;
1373 }
1374
1375 aquifer_tracer_cells_[cellIdx].push_back(
1376 AquiferTracerCellSpec { tracerIdx, phaseIdx, static_cast<Scalar>(spec.concentration) });
1377 }
1378 }
1379 }
1380
1381 template<class TrRe>
1383 {
1384 if (tr.numTracer() == 0 || aquifer_tracer_cells_.empty()) {
1385 return;
1386 }
1387
1388 const auto& aquiferModel = simulator_.problem().aquiferModel();
1389 const Scalar dt = simulator_.timeStepSize();
1390
1391 for (const auto& [cellIdx, specs] : aquifer_tracer_cells_) {
1392 // Scalar influx from converged Qai_; do not recalculate or use getValue()
1393 // in the flow Newton path (see AquiferAnalytical::addToSource).
1394 const Scalar rate = aquiferModel.cachedConnectionInfluxRate(cellIdx);
1395 if (rate == Scalar{0}) {
1396 continue;
1397 }
1398
1399 const unsigned I = cellIdx;
1400 const Scalar rate_f = rate;
1401
1402 for (const auto& spec : specs) {
1403 if (spec.phaseIdx != tr.phaseIdx_) {
1404 continue;
1405 }
1406
1407 int localTIdx = -1;
1408 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1409 if (tr.idx_[tIdx] == spec.tracerIdx) {
1410 localTIdx = tIdx;
1411 break;
1412 }
1413 }
1414 if (localTIdx < 0) {
1415 continue;
1416 }
1417
1418 if (rate_f > 0) {
1419 const Scalar delta = rate_f * spec.concentration;
1420 tr.residual_[localTIdx][I][Free] -= delta;
1421 tr.dVol_[Free][I] -= rate_f * dt;
1422 }
1423 else if (rate_f < 0) {
1424 tr.residual_[localTIdx][I][Free] -= rate_f * tr.concentration_[localTIdx][I][Free];
1425 tr.dVol_[Free][I] -= rate_f * dt;
1426 (*tr.mat)[I][I][Free][Free] -= rate_f * variable<TracerEvaluation>(1.0, 0).derivative(0);
1427 }
1428 }
1429 }
1430 }
1431
1432 template<class TrRe>
1433 bool solveBatch_(TrRe& tr, std::vector<TracerVector>& dx)
1434 {
1435 // Istl solver
1436 if (!this->useReorderSolver_) {
1437 return this->linearSolveBatchwise_(*tr.mat, dx, tr.residual_);
1438 }
1439
1440 // Run istl solver fallback for some number of time steps before retrying reorder
1441 if (tr.reorderSkipSteps_ > 0) {
1442 --tr.reorderSkipSteps_;
1443 if (tr.reorderSkipSteps_ == 0) {
1444 OpmLog::info(fmt::format("Tracer model: retrying the reorder solver for the {} "
1445 "tracers in the next time step",
1446 FluidSystem::phaseName(tr.phaseIdx_)));
1447 }
1448 return this->linearSolveBatchwise_(*tr.mat, dx, tr.residual_);
1449 }
1450
1451 // Reorder solver
1452 if (this->linearSolveReorder_(*tr.mat, dx, tr.residual_)) {
1453 return true;
1454 }
1455
1456 // Initiate fallback istl solver, which will be done for some number of future time steps
1457 // as well
1458 tr.reorderSkipSteps_ = reorderRetrySteps_;
1459 OpmLog::warning(fmt::format("Tracer model: the reorder solver failed for the {} tracers. "
1460 "Using the ISTL solver for this and the next {} time steps.",
1461 FluidSystem::phaseName(tr.phaseIdx_), reorderRetrySteps_));
1462 return this->linearSolveBatchwise_(*tr.mat, dx, tr.residual_);
1463 }
1464
1466 {
1468
1469 for (auto& tr : tbatch) {
1470 if (tr.numTracer() == 0) {
1471 continue;
1472 }
1473
1474 // Note that we solve for a concentration update (compared to previous time step)
1475 // Confer also assembleTracerEquations_(...) above.
1476 std::vector<TracerVector> dx(tr.concentration_);
1477 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1478 dx[tIdx] = 0.0;
1479 }
1480
1481 const bool converged = solveBatch_(tr, dx);
1482 if (!converged) {
1483 OpmLog::warning("### Tracer model: Linear solver did not converge. ###");
1484 }
1485
1486 OPM_TIMEBLOCK(tracerPost);
1487
1488 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1489 for (std::size_t globalDofIdx = 0; globalDofIdx < tr.concentration_[tIdx].size(); ++globalDofIdx) {
1490 // New concetration. Concentrations that are negative or where free/solution phase is not
1491 // present are set to zero
1492 const auto& intQuants = simulator_.model().intensiveQuantities(globalDofIdx, 0);
1493 const auto& fs = intQuants.fluidState();
1494 const Scalar Sf = decay<Scalar>(fs.saturation(tr.phaseIdx_));
1495 Scalar Ss = 0.0;
1496
1497 if (tr.phaseIdx_ == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas()) {
1498 Ss = decay<Scalar>(fs.saturation(FluidSystem::oilPhaseIdx));
1499 }
1500 else if (tr.phaseIdx_ == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) {
1501 Ss = decay<Scalar>(fs.saturation(FluidSystem::gasPhaseIdx));
1502 }
1503
1504 copyForOutput<Free>(tr, dx, Sf, tIdx, globalDofIdx, this->freeTracerConcentration_);
1505 copyForOutput<Solution>(tr, dx, Ss, tIdx, globalDofIdx, this->solTracerConcentration_);
1506 }
1507 }
1508
1509 // Store _producer_ tracer rate for reporting
1510 const auto& wellPtrs = simulator_.problem().wellModel().localNonshutWells();
1511 for (const auto& wellPtr : wellPtrs) {
1512 const auto& eclWell = wellPtr->wellEcl();
1513
1514 // Injection rates already reported during assembly
1515 if (!eclWell.isProducer()) {
1516 continue;
1517 }
1518
1519 Scalar rateWellPos = 0.0;
1520 Scalar rateWellNeg = 0.0;
1521 const std::size_t well_index = simulator_.problem().wellModel().wellState().index(eclWell.name()).value();
1522 const auto& ws = simulator_.problem().wellModel().wellState().well(well_index);
1523 auto& tracerRate = this->wellTracerRate_[eclWell.seqIndex()];
1524 auto& freeTracerRate = this->wellFreeTracerRate_[eclWell.seqIndex()];
1525 auto& solTracerRate = this->wellSolTracerRate_[eclWell.seqIndex()];
1526 auto* mswTracerRate = eclWell.isMultiSegment() ? &this->mSwTracerRate_[eclWell.seqIndex()] : nullptr;
1527 const auto well_eff = wellPtr->wellEfficiencyFactor(); // Needed to convert ws.perf_data.phase_mixing_rates to effective rates
1528 for (std::size_t i = 0; i < ws.perf_data.size(); ++i) {
1529 const auto I = ws.perf_data.cell_index[i];
1530 const Scalar rate = wellPtr->volumetricSurfaceRateForConnection(I, tr.phaseIdx_); // Includes (accumulated) well efficiency factor
1531
1532 Scalar rate_s;
1533 if (tr.phaseIdx_ == FluidSystem::oilPhaseIdx && FluidSystem::enableVaporizedOil()) {
1534 rate_s = ws.perf_data.phase_mixing_rates[i][ws.vaporized_oil]*well_eff;
1535 }
1536 else if (tr.phaseIdx_ == FluidSystem::gasPhaseIdx && FluidSystem::enableDissolvedGas()) {
1537 rate_s = ws.perf_data.phase_mixing_rates[i][ws.dissolved_gas]*well_eff;
1538 }
1539 else {
1540 rate_s = 0.0;
1541 }
1542
1543 const Scalar rate_f = rate - rate_s;
1544 assignRates<Free>(tr, eclWell, i, I, rate_f,
1545 tracerRate, mswTracerRate, freeTracerRate);
1546 assignRates<Solution>(tr, eclWell, i, I, rate_s,
1547 tracerRate, mswTracerRate, solTracerRate);
1548
1549 if (rate < 0) {
1550 rateWellNeg += rate;
1551 }
1552 else {
1553 rateWellPos += rate;
1554 }
1555 }
1556
1557 // TODO: Some inconsistencies here that perhaps should be clarified.
1558 // The "offical" rate as reported below is occasionally significant
1559 // different from the sum over connections (as calculated above). Only observed
1560 // for small values, neglible for the rate itself, but matters when used to
1561 // calculate tracer concentrations.
1562 const Scalar official_well_rate_total =
1563 simulator_.problem().wellModel().wellState().well(well_index).surface_rates[tr.phaseIdx_];
1564
1565 const Scalar rateWellTotal = official_well_rate_total;
1566
1567 if (rateWellTotal > rateWellNeg) { // Cross flow
1568 constexpr Scalar bucketPrDay = 10.0 / (1000. * 3600. * 24.); // ... keeps (some) trouble away
1569 const Scalar factor = (rateWellTotal < -bucketPrDay) ? rateWellTotal / rateWellNeg : 0.0;
1570 for (int tIdx = 0; tIdx < tr.numTracer(); ++tIdx) {
1571 tracerRate[tr.idx_[tIdx]].rate *= factor;
1572 }
1573 }
1574 }
1575 }
1577 }
1578
1579 Simulator& simulator_;
1580
1581 // True if DISPERC is given in the deck
1583
1584 // This struct collects tracers of the same type (i.e, transported in same phase).
1585 // The idea being that, under the assumption of linearity, tracers of same type can
1586 // be solved in concert, having a common system matrix but separate right-hand-sides.
1587
1588 // Since oil or gas tracers appears in dual compositions when VAPOIL respectively DISGAS
1589 // is active, the template argument is intended to support future extension to these
1590 // scenarios by supplying an extended vector type.
1591
1592 template <typename TV>
1594 {
1595 std::vector<int> idx_;
1596 const int phaseIdx_;
1597 std::vector<TV> concentrationInitial_;
1598 std::vector<TV> concentration_;
1599 std::vector<TV> storageOfTimeIndex1_;
1600 std::vector<TV> residual_;
1601 std::unique_ptr<TracerMatrix> mat;
1603 // Molecular diffusion coefficients [m2/s] of the free tracer and of the tracer in solution
1604 // (TRDIFxxx), common to all tracers in the batch
1607 // Change of the free and solution volume of the phase of the batch in the current time step
1608 std::array<std::vector<Scalar>, 2> dVol_;
1609
1610 bool operator==(const TracerBatch& rhs) const
1611 {
1612 return this->concentrationInitial_ == rhs.concentrationInitial_ &&
1613 this->concentration_ == rhs.concentration_;
1614 }
1615
1617 {
1618 TracerBatch<TV> result(4);
1619 result.idx_ = {1,2,3};
1620 result.concentrationInitial_ = {5.0, 6.0};
1621 result.concentration_ = {7.0, 8.0};
1622 result.storageOfTimeIndex1_ = {9.0, 10.0, 11.0};
1623 result.residual_ = {12.0, 13.0};
1624
1625 return result;
1626 }
1627
1628 template<class Serializer>
1629 void serializeOp(Serializer& serializer)
1630 {
1631 serializer(concentrationInitial_);
1632 serializer(concentration_);
1633 }
1634
1635 TracerBatch(int phaseIdx = 0) : phaseIdx_(phaseIdx) {}
1636
1637 int numTracer() const
1638 { return idx_.size(); }
1639
1640 void addTracer(const int idx, const TV& concentration)
1641 {
1642 const int numGridDof = concentration.size();
1643 idx_.emplace_back(idx);
1644 concentrationInitial_.emplace_back(concentration);
1645 concentration_.emplace_back(concentration);
1646 residual_.emplace_back(numGridDof);
1647 storageOfTimeIndex1_.emplace_back(numGridDof);
1648 for (auto& dVol : dVol_) {
1649 dVol.resize(numGridDof);
1650 }
1651 }
1652 };
1653
1654 std::vector<TracerBatch<TracerVector>> tbatch;
1655 std::array<std::array<std::vector<Scalar>,numPhases>,2> vol1_;
1656 ElementChunks<GridView, Dune::Partitions::All> element_chunks_;
1657
1662 };
1663
1664 std::unordered_map<unsigned, std::vector<AquiferTracerCellSpec>> aquifer_tracer_cells_;
1665
1667};
1668
1669} // namespace Opm
1670
1671#endif // OPM_TRACER_MODEL_HPP
#define OPM_END_PARALLEL_TRY_CATCH_LOG(obptc_logger, obptc_prefix, obptc_output, comm)
Catch exception, log, and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:207
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
A datahandle sending data located in multiple vectors.
Definition: DeferredLogger.hpp:57
void warning(const std::string &tag, const std::string &message)
Definition: GenericTracerModel.hpp:56
void doInit(bool rst, std::size_t numGridDof, std::size_t gasPhaseIdx, std::size_t oilPhaseIdx, std::size_t waterPhaseIdx)
Initialize all internal data structures needed by the tracer module.
Definition: GenericTracerModel_impl.hpp:229
bool linearSolveReorder_(const TracerMatrix &M, std::vector< TracerVector > &x, std::vector< TracerVector > &b)
Solve the tracer equations cell by cell in the order of the flow.
Definition: GenericTracerModel_impl.hpp:510
Simplifies multi-threaded capabilities.
Definition: threadmanager.hpp:36
A class which handles tracers as specified in by ECL.
Definition: TracerModel.hpp:89
static Scalar carrierSurfaceVolume_(const int tracerPhaseIdx, const FluidState &fs, const bool saturationWeighted)
Surface volume of the tracer carrier per unit pore volume of a cell: the inverse formation volume fac...
Definition: TracerModel.hpp:465
void updateStorageCache()
Definition: TracerModel.hpp:1159
std::array< std::array< std::vector< Scalar >, numPhases >, 2 > vol1_
Definition: TracerModel.hpp:1655
void convertEffectiveRatesToRawRates()
Definition: TracerModel.hpp:1234
static bool carrierPresent_(const int tracerPhaseIdx, const FluidState &fs)
Whether the carrier of the tracer is present in a cell, i.e. there is carrier phase (and,...
Definition: TracerModel.hpp:488
void assembleTracerEquationBoundary(TrRe &tr, const ElementContext &elemCtx, const unsigned I, const Scalar dt)
Boundary conditions for the tracer equations.
Definition: TracerModel.hpp:826
void advanceTracerFields()
Definition: TracerModel.hpp:1465
void init(bool rst)
Definition: TracerModel.hpp:151
TracerEvaluation computeDispersivity_(const int tracerPhaseIdx, const ElementContext &elemCtx, const unsigned scvfIdx, const unsigned timeIdx) const
Dispersive coefficient of a face for the Fickian flux J = -(w * |u| * disp) * (c_J - c_I),...
Definition: TracerModel.hpp:536
void checkBoundaryTracers_(DeferredLogger &deferredLogger) const
Cross-reference the boundary conditions of the schedule with the tracers.
Definition: TracerModel.hpp:1272
std::vector< TracerBatch< TracerVector > > tbatch
Definition: TracerModel.hpp:1654
void assembleTracerEquationSource(TrRe &tr, const Scalar dt, unsigned I)
Definition: TracerModel.hpp:953
TracerModel(Simulator &simulator)
Definition: TracerModel.hpp:121
void assignRates(const TrRe &tr, const Well &eclWell, const std::size_t i, const std::size_t I, const Scalar rate, std::vector< WellTracerRate< Scalar > > &tracerRate, std::vector< MSWellTracerRate< Scalar > > *mswTracerRate, std::vector< WellTracerRate< Scalar > > &splitRate)
Definition: TracerModel.hpp:1212
void copyForOutput(TrRe &tr, const std::vector< TracerVector > &dx, const Scalar S, const unsigned tIdx, const unsigned globalDofIdx, std::vector< TracerVectorSingle > &sc)
Definition: TracerModel.hpp:1196
void assembleTracerEquationFlux(TrRe &tr, const ElementContext &elemCtx, unsigned scvfIdx, unsigned I, unsigned J, const Scalar dt)
Definition: TracerModel.hpp:621
bool solveBatch_(TrRe &tr, std::vector< TracerVector > &dx)
Definition: TracerModel.hpp:1433
void assembleTracerEquationWell(TrRe &tr, const Well &well)
Definition: TracerModel.hpp:712
void updateElem(TrRe &tr, const Scalar scvVolume, const unsigned globalDofIdx)
Definition: TracerModel.hpp:1146
Scalar computeVolume_(const int tracerPhaseIdx, const unsigned globalDofIdx, const unsigned timeIdx) const
Definition: TracerModel.hpp:340
void assembleTracerEquationAquifer_(TrRe &tr)
Definition: TracerModel.hpp:1382
typename BaseType::TracerTypeIdx TracerTypeIdx
Definition: TracerModel.hpp:334
void assembleTracerEquationVolume(TrRe &tr, const ElementContext &elemCtx, const Scalar scvVolume, const Scalar dt, unsigned I, unsigned I1)
Definition: TracerModel.hpp:585
Scalar storage1_(const TrRe &tr, const unsigned tIdx, const unsigned I, const unsigned I1, const bool cache)
Definition: TracerModel.hpp:570
void serialize(Restarter &)
This method writes the complete state of all tracer to the hard disk.
Definition: TracerModel.hpp:313
void assembleTracerEquations_()
Definition: TracerModel.hpp:999
static bool hasSolutionPart_(const int tracerPhaseIdx)
Whether the tracers of the phase have a solution part (vaporized oil, dissolved gas)
Definition: TracerModel.hpp:453
void buildAquiferTracerConnections_(DeferredLogger &deferredLogger)
Definition: TracerModel.hpp:1328
bool dispersionActive_
Definition: TracerModel.hpp:1582
std::pair< TracerEvaluation, bool > computeFlux_(const int tracerPhaseIdx, const ElementContext &elemCtx, const unsigned scvfIdx, const unsigned timeIdx) const
Definition: TracerModel.hpp:378
void beginTimeStep()
Definition: TracerModel.hpp:285
TracerEvaluation computeDiffusivity_(const int tracerPhaseIdx, const ElementContext &elemCtx, const unsigned scvfIdx, const unsigned timeIdx) const
Diffusive coefficient of a face for the Fickian flux J = -D_mol * A * diffusivity * w * (c_J - c_I)....
Definition: TracerModel.hpp:503
void serializeOp(Serializer &serializer)
Definition: TracerModel.hpp:327
int reorderRetrySteps_
Definition: TracerModel.hpp:1666
void prepareTracerBatches()
Definition: TracerModel.hpp:195
std::unordered_map< unsigned, std::vector< AquiferTracerCellSpec > > aquifer_tracer_cells_
Definition: TracerModel.hpp:1664
ElementChunks< GridView, Dune::Partitions::All > element_chunks_
Definition: TracerModel.hpp:1656
void endTimeStep()
Informs the tracer model that a time step has just been finished.
Definition: TracerModel.hpp:298
Simulator & simulator_
Definition: TracerModel.hpp:1579
static int carrierPhaseIdx_(const int tracerPhaseIdx)
Phase that carries the tracer of the given type: the phase of the tracer for the free tracer,...
Definition: TracerModel.hpp:439
void deserialize(Restarter &)
This method restores the complete state of the tracer from disk.
Definition: TracerModel.hpp:323
A data handle sending multiple data store in vectors attached to cells.
Definition: VectorVectorDataHandle.hpp:52
Definition: fvbaseprimaryvariables.hh:161
int Index
The type of an index of a degree of freedom.
Definition: overlaptypes.hh:44
Definition: blackoilmodel.hh:74
Definition: blackoilbioeffectsmodules.hh:45
Opm::DeferredLogger gatherDeferredLogger(const Opm::DeferredLogger &local_deferredlogger, Parallel::Communication communicator)
Create a global log combining local logs.
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
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
This file provides the infrastructure to retrieve run-time parameters.
The Opm property system, traits with inheritance.
Definition: WellTracerRate.hpp:60
std::unordered_map< int, Scalar > rate
Definition: WellTracerRate.hpp:62
Definition: TracerModel.hpp:69
a tag to mark properties as undefined
Definition: propertysystem.hh:38
Definition: TracerModel.hpp:1658
int phaseIdx
Definition: TracerModel.hpp:1660
Scalar concentration
Definition: TracerModel.hpp:1661
int tracerIdx
Definition: TracerModel.hpp:1659
Definition: TracerModel.hpp:1594
const int phaseIdx_
Definition: TracerModel.hpp:1596
void addTracer(const int idx, const TV &concentration)
Definition: TracerModel.hpp:1640
int reorderSkipSteps_
Definition: TracerModel.hpp:1602
bool operator==(const TracerBatch &rhs) const
Definition: TracerModel.hpp:1610
static TracerBatch serializationTestObject()
Definition: TracerModel.hpp:1616
std::vector< TV > concentrationInitial_
Definition: TracerModel.hpp:1597
void serializeOp(Serializer &serializer)
Definition: TracerModel.hpp:1629
TracerBatch(int phaseIdx=0)
Definition: TracerModel.hpp:1635
Scalar solutionDiffusionCoefficient_
Definition: TracerModel.hpp:1606
int numTracer() const
Definition: TracerModel.hpp:1637
std::vector< int > idx_
Definition: TracerModel.hpp:1595
std::unique_ptr< TracerMatrix > mat
Definition: TracerModel.hpp:1601
std::vector< TV > storageOfTimeIndex1_
Definition: TracerModel.hpp:1599
std::vector< TV > residual_
Definition: TracerModel.hpp:1600
Scalar freeDiffusionCoefficient_
Definition: TracerModel.hpp:1605
std::vector< TV > concentration_
Definition: TracerModel.hpp:1598
std::array< std::vector< Scalar >, 2 > dVol_
Definition: TracerModel.hpp:1608
Definition: WellTracerRate.hpp:33
Scalar rate
Definition: WellTracerRate.hpp:35