OutputCompositionalModule.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*/
27#ifndef OPM_OUTPUT_COMPOSITIONAL_MODULE_HPP
28#define OPM_OUTPUT_COMPOSITIONAL_MODULE_HPP
29
30#include <dune/grid/common/gridenums.hh>
31
33
34#include <opm/common/Exceptions.hpp>
35#include <opm/common/ErrorMacros.hpp>
36#include <opm/common/TimingMacros.hpp>
37#include <opm/common/OpmLog/OpmLog.hpp>
38
39#include <opm/input/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
40
41#include <opm/material/common/Valgrind.hpp>
42
48
53
54#include <algorithm>
55#include <array>
56#include <cstddef>
57#include <fstream>
58#include <memory>
59#include <sstream>
60#include <stdexcept>
61#include <string>
62#include <type_traits>
63#include <utility>
64#include <vector>
65
66#include <fmt/format.h>
67
68namespace Opm {
69
70// forward declaration
71template <class TypeTag>
72class EcfvDiscretization;
73
80template <class TypeTag>
81class OutputCompositionalModule : public GenericOutputModule<GetPropType<TypeTag, Properties::FluidSystem>>
82{
90 using RestartOutput = typename CompositionalContainer<FluidSystem>::RestartOutput;
93
94 enum { numPhases = FluidSystem::numPhases };
95 enum { numComponents = FluidSystem::numComponents };
96 enum { oilPhaseIdx = FluidSystem::oilPhaseIdx };
97 enum { gasPhaseIdx = FluidSystem::gasPhaseIdx };
98 enum { waterPhaseIdx = FluidSystem::waterPhaseIdx };
99
100public:
101 static void registerParameters()
102 {
105 }
106
107 template <class CollectDataToIORankType>
108 OutputCompositionalModule(const Simulator& simulator,
109 const SummaryConfig& smryCfg,
110 const CollectDataToIORankType& collectToIORank)
111 : BaseType(simulator.vanguard().eclState(),
112 simulator.vanguard().schedule(),
113 smryCfg,
114 simulator.vanguard().summaryState(),
116 [this](const int idx)
117 { return simulator_.problem().eclWriter().collectOnIORank().localIdxToGlobalIdx(idx); },
118 [&collectToIORank](const int idx)
119 { return collectToIORank.isCartIdxOnThisRank(idx); },
120 simulator.vanguard().grid().comm(),
121 getPropValue<TypeTag, Properties::EnergyModuleType>() == EnergyModules::FullyImplicitThermal,
122 getPropValue<TypeTag, Properties::EnergyModuleType>() == EnergyModules::ConstantTemperature,
123 getPropValue<TypeTag, Properties::EnableMech>(),
124 getPropValue<TypeTag, Properties::EnableSolvent>(),
125 getPropValue<TypeTag, Properties::EnablePolymer>(),
126 getPropValue<TypeTag, Properties::EnableFoam>(),
127 getPropValue<TypeTag, Properties::EnableBrine>(),
128 getPropValue<TypeTag, Properties::EnableSaltPrecipitation>(),
129 getPropValue<TypeTag, Properties::EnableExtbo>(),
130 getPropValue<TypeTag, Properties::EnableBioeffects>(),
131 getPropValue<TypeTag, Properties::EnableGeochemistry>())
132 , simulator_(simulator)
133 {
134 for (auto& region_pair : this->regions_) {
135 this->createLocalRegion_(region_pair.second);
136 }
137
138 auto isCartIdxOnThisRank = [&collectToIORank](const int idx) {
139 return collectToIORank.isCartIdxOnThisRank(idx);
140 };
141
142 this->setupBlockData(isCartIdxOnThisRank);
143
144 // Compositional runs currently fill block data on the global grid only.
145 // The empty level map intentionally leaves LB* values unallocated.
146 if (! collectToIORank.isParallel()) {
147 this->setupLgrBlockData({}, [](const int, const int) { return true; });
148 }
149
150 if (! Parameters::Get<Parameters::OwnerCellsFirst>()) {
151 const std::string msg = "The output code does not support --owner-cells-first=false.";
152 if (collectToIORank.isIORank()) {
153 OpmLog::error(msg);
154 }
155 OPM_THROW_NOLOG(std::runtime_error, msg);
156 }
157
158 if (smryCfg.match("[FB]PP[OGW]") || smryCfg.match("RPP[OGW]*")) {
159 auto rset = this->eclState_.fieldProps().fip_regions();
160 rset.push_back("PVTNUM");
161
162 // Note: We explicitly use decltype(auto) here because the
163 // default scheme (-> auto) will deduce an undesirable type. We
164 // need the "reference to vector" semantics in this instance.
166 .emplace(this->simulator_.gridView().comm(),
167 FluidSystem::numPhases, rset,
168 [fp = std::cref(this->eclState_.fieldProps())]
169 (const std::string& rsetName) -> decltype(auto)
170 { return fp.get().get_int(rsetName); });
171 }
172 }
173
178 void
179 allocBuffers(const unsigned bufferSize,
180 const unsigned reportStepNum,
181 const bool substep,
182 const bool log,
183 const bool forceRestartFieldAllocation)
184 {
185 if (! std::is_same<Discretization, EcfvDiscretization<TypeTag>>::value) {
186 return;
187 }
188
189 auto rstKeywords = this->schedule_.rst_keywords(reportStepNum);
190 const bool isRestartOutput = forceRestartFieldAllocation ||
191 (!substep && this->schedule_.write_rst_file(reportStepNum));
192 const auto restartOutput = isRestartOutput
193 ? RestartOutput::Enabled
194 : RestartOutput::Disabled;
195 this->compC_.allocate(bufferSize, rstKeywords, restartOutput);
196 this->numUnresolvedSaturationPressures_ = 0;
197
198 this->doAllocBuffers(bufferSize, reportStepNum, substep, log,
199 forceRestartFieldAllocation,
200 /* hysteresisConfig = */ nullptr,
201 /* numOutputNnc =*/ 0,
202 std::move(rstKeywords));
203 }
204
205 void assignToSolution(data::Solution& sol) override
206 {
207 this->compC_.outputRestart(sol, this->saturation_[oilPhaseIdx]);
209
210 // Use the compositional restart names for phase densities and viscosities.
212 .oilDensity = "DENO",
213 .gasDensity = "DENG",
214 .waterDensity = "DENW",
215 .oilViscosity = "VOIL",
216 .gasViscosity = "VGAS",
217 .waterViscosity = "VWAT",
218 });
219
220 // Report compositional relative permeabilities under their restart names.
221 using M = UnitSystem::measure;
222 this->assignBuffer(sol, "KRO", M::identity,
223 relativePermeability_[oilPhaseIdx], oilPhaseIdx);
224 this->assignBuffer(sol, "KRG", M::identity,
225 relativePermeability_[gasPhaseIdx], gasPhaseIdx);
226 if constexpr (numPhases > 2) {
227 this->assignBuffer(sol, "KRW", M::identity,
228 relativePermeability_[waterPhaseIdx], waterPhaseIdx);
229 }
230 }
231
232 void outputFipAndResvLog(const Inplace& inplace,
233 const std::size_t reportStepNum,
234 double elapsed,
235 boost::posix_time::ptime currentDate,
236 const bool substep,
237 const Parallel::Communication& comm)
238 {
239 if (comm.rank() != 0) {
240 return;
241 }
242
243 std::unique_ptr<FIPConfig> fipSched;
244 if (reportStepNum > 0) {
245 const auto& rpt = this->schedule_[reportStepNum - 1].rpt_config.get();
246 fipSched = std::make_unique<FIPConfig>(rpt);
247 }
248
249 const FIPConfig& fipc = reportStepNum == 0
250 ? this->eclState_.getEclipseConfig().fip()
251 : *fipSched;
252
253 if (!substep && !this->forceDisableFipOutput_ && fipc.output(FIPConfig::OutputField::FIELD)) {
254 this->logOutput_.timeStamp("BALANCE", elapsed, reportStepNum, currentDate);
255
256 const auto& initial_inplace = *this->initialInplace();
257 this->logOutput_.fip(inplace, initial_inplace, "");
258
259 if (fipc.output(FIPConfig::OutputField::FIPNUM)) {
260 this->logOutput_.fip(inplace, initial_inplace, "FIPNUM");
261
262 if (fipc.output(FIPConfig::OutputField::RESV)) {
263 this->logOutput_.fipResv(inplace, "FIPNUM");
264 }
265 }
266
267 if (fipc.output(FIPConfig::OutputField::FIP)) {
268 for (const auto& reg : this->regions_) {
269 if (reg.first != "FIPNUM") {
270 std::ostringstream ss;
271 ss << "BAL" << reg.first.substr(3);
272 this->logOutput_.timeStamp(ss.str(), elapsed, reportStepNum, currentDate);
273 this->logOutput_.fip(inplace, initial_inplace, reg.first);
274
275 if (fipc.output(FIPConfig::OutputField::RESV)) {
276 this->logOutput_.fipResv(inplace, reg.first);
277 }
278 }
279 }
280 }
281 }
282 }
283
284 void outputFipAndResvLogToCSV(const std::size_t reportStepNum,
285 const bool substep,
286 const Parallel::Communication& comm)
287 {
288 if (comm.rank() != 0) {
289 return;
290 }
291
292 if ((reportStepNum == 0) && (!substep) &&
293 (this->schedule_.initialReportConfiguration().has_value()) &&
294 (this->schedule_.initialReportConfiguration()->contains("CSVFIP"))) {
295
296 std::ostringstream csv_stream;
297
298 this->logOutput_.csv_header(csv_stream);
299
300 const auto& initial_inplace = *this->initialInplace();
301
302 this->logOutput_.fip_csv(csv_stream, initial_inplace, "FIPNUM");
303
304 for (const auto& reg : this->regions_) {
305 if (reg.first != "FIPNUM") {
306 this->logOutput_.fip_csv(csv_stream, initial_inplace, reg.first);
307 }
308 }
309
310 const IOConfig& io = this->eclState_.getIOConfig();
311 auto csv_fname = io.getOutputDir() + "/" + io.getBaseName() + ".CSV";
312
313 std::ofstream outputFile(csv_fname);
314 outputFile << csv_stream.str();
315 }
316 }
317
319 void setupExtractors(const bool /*isSubStep*/,
320 const std::size_t /*reportStepNum*/)
321 {
322 using Entry = typename Extractor::Entry;
323 using ExtractContext = typename Extractor::Context;
324 using ScalarEntry = typename Extractor::ScalarEntry;
325 using PhaseEntry = typename Extractor::PhaseEntry;
326
327 auto extractors = std::array{
328 Entry{PhaseEntry{&this->saturation_,
329 [](const unsigned phase, const ExtractContext& ectx)
330 { return ectx.intQuants.saturationForOutput(phase); }}
331 },
332 Entry{ScalarEntry{&this->fluidPressure_,
333 [](const ExtractContext& ectx)
334 {
335 if (FluidSystem::phaseIsActive(oilPhaseIdx)) {
336 // Output oil pressure as default
337 return getValue(ectx.fs.pressure(oilPhaseIdx));
338 }
339 else if (FluidSystem::phaseIsActive(gasPhaseIdx)) {
340 // Output gas if oil is not present
341 return getValue(ectx.fs.pressure(gasPhaseIdx));
342 }
343 else {
344 // Output water if neither oil nor gas is present
345 return getValue(ectx.fs.pressure(waterPhaseIdx));
346 }
347 }}
348 },
349 Entry{ScalarEntry{&this->temperature_,
350 [](const ExtractContext& ectx)
351 { return getValue(ectx.fs.temperature(oilPhaseIdx)); }}
352 },
353 Entry{[&compC = this->compC_](const ExtractContext& ectx)
354 {
355 compC.assignMoleFractions(ectx.globalDofIdx,
356 [&ectx](const unsigned compIdx)
357 {
358 return ectx.intQuants.hasHydrocarbon()
359 ? getValue(ectx.fs.moleFraction(compIdx))
360 : Scalar{0};
361 });
362 }, this->compC_.moleFractionsAllocated()
363 },
364
365 // Use presence before regularization so the numerical hydrocarbon
366 // floor does not create reported phase properties in a water-only cell.
367 Entry{[&compC = this->compC_](const ExtractContext& ectx)
368 {
369 const bool hasGas =
370 ectx.intQuants.phaseIsPresent(gasPhaseIdx);
371 compC.assignGasFractions(ectx.globalDofIdx,
372 [&fs = ectx.fs, hasGas](const unsigned compIdx)
373 {
374 return hasGas
375 ? getValue(fs.moleFraction(gasPhaseIdx, compIdx))
376 : Scalar{0};
377 });
378 }, FluidSystem::phaseIsActive(gasPhaseIdx) &&
379 this->compC_.gasFractionsAllocated()
380 },
381 Entry{[&compC = this->compC_](const ExtractContext& ectx)
382 {
383 const bool hasOil =
384 ectx.intQuants.phaseIsPresent(oilPhaseIdx);
385 compC.assignOilFractions(ectx.globalDofIdx,
386 [&fs = ectx.fs, hasOil](const unsigned compIdx)
387 {
388 return hasOil
389 ? getValue(fs.moleFraction(oilPhaseIdx, compIdx))
390 : Scalar{0};
391 });
392 }, FluidSystem::phaseIsActive(oilPhaseIdx) &&
393 this->compC_.oilFractionsAllocated()
394 },
395 Entry{[&compC = this->compC_](const ExtractContext& ectx)
396 {
397 compC.assignPhasePressures(ectx.globalDofIdx,
398 getValue(ectx.fs.pressure(oilPhaseIdx)),
399 getValue(ectx.fs.pressure(gasPhaseIdx)));
400 }, this->compC_.phasePressuresAllocated()
401 },
402 // The reference convention for a water-only cell is VMF = 1.
403 // Otherwise use the hydrocarbon flash's vapour mole fraction.
404 Entry{[&compC = this->compC_](const ExtractContext& ectx)
405 {
406 const Scalar liquidFraction = getValue(ectx.fs.L());
407 compC.assignVaporFraction(ectx.globalDofIdx,
408 ectx.intQuants.hasHydrocarbon()
409 ? std::clamp(Scalar{1} - liquidFraction,
410 Scalar{0}, Scalar{1})
411 : Scalar{1});
412 }, this->compC_.vaporFractionAllocated()
413 },
414 // The phase densities and viscosities, reported where the phase is present.
415 Entry{PhaseEntry{&this->relativePermeability_,
416 [](const unsigned phaseIdx, const ExtractContext& ectx)
417 {
418 return ectx.intQuants.phaseIsPresent(phaseIdx)
419 ? getValue(ectx.intQuants.relativePermeability(phaseIdx))
420 : Scalar{0};
421 }}
422 },
423 Entry{PhaseEntry{&this->density_,
424 [](const unsigned phaseIdx, const ExtractContext& ectx)
425 {
426 return ectx.intQuants.phaseIsPresent(phaseIdx)
427 ? getValue(ectx.fs.density(phaseIdx))
428 : Scalar{0};
429 }}
430 },
431 Entry{PhaseEntry{&this->viscosity_,
432 [](const unsigned phaseIdx, const ExtractContext& ectx)
433 {
434 return ectx.intQuants.phaseIsPresent(phaseIdx)
435 ? getValue(ectx.fs.viscosity(phaseIdx))
436 : Scalar{0};
437 }}
438 },
439 };
440
441 this->extractors_ = Extractor::removeInactive(extractors);
442
443 this->setupBlockExtractors_();
444 }
445
455 {
456 using Entry = typename BlockExtractor::Entry;
457 using Context = typename BlockExtractor::Context;
458 using ScalarEntry = typename BlockExtractor::ScalarEntry;
459
460 using namespace std::string_view_literals;
461
462 const auto densityIfPresent = [](const unsigned phaseIdx) {
463 return [phaseIdx](const Context& ectx) -> Scalar {
464 if (!ectx.intQuants.phaseIsPresent(phaseIdx)) {
465 return Scalar{0};
466 }
467
468 return getValue(ectx.fs.density(phaseIdx));
469 };
470 };
471
472 const auto viscosityIfPresent = [](const unsigned phaseIdx) {
473 return [phaseIdx](const Context& ectx) -> Scalar {
474 if (!ectx.intQuants.phaseIsPresent(phaseIdx)) {
475 return Scalar{0};
476 }
477
478 return getValue(ectx.fs.viscosity(phaseIdx));
479 };
480 };
481
482 const auto reservoirPoreVolume = [&model = this->simulator_.model()]
483 (const Context& ectx) -> Scalar
484 {
485 return getValue(ectx.intQuants.porosity()) *
486 model.dofTotalVolume(ectx.globalDofIdx);
487 };
488
489 const auto phasePoreVolume = [reservoirPoreVolume](const unsigned phaseIdx) {
490 return [phaseIdx, reservoirPoreVolume](const Context& ectx) -> Scalar {
491 return ectx.intQuants.saturationForOutput(phaseIdx) * reservoirPoreVolume(ectx);
492 };
493 };
494
495 const auto handlers = std::array{
496 Entry{ScalarEntry{std::vector{"BPR"sv, "BPRESSUR"sv},
497 [](const Context& ectx)
498 {
499 return FluidSystem::phaseIsActive(oilPhaseIdx)
500 ? getValue(ectx.fs.pressure(oilPhaseIdx))
501 : getValue(ectx.fs.pressure(gasPhaseIdx));
502 }
503 }
504 },
505 Entry{ScalarEntry{"BGPR"sv,
506 [](const Context& ectx)
507 { return getValue(ectx.fs.pressure(gasPhaseIdx)); }
508 }
509 },
510 Entry{ScalarEntry{"BWPR"sv,
511 [](const Context& ectx)
512 {
513 return FluidSystem::phaseIsActive(waterPhaseIdx)
514 ? getValue(ectx.fs.pressure(waterPhaseIdx))
515 : Scalar{0};
516 }
517 }
518 },
519 Entry{ScalarEntry{"BRPV"sv, reservoirPoreVolume}},
520 Entry{ScalarEntry{"BWPV"sv, phasePoreVolume(waterPhaseIdx)}},
521 Entry{ScalarEntry{"BOPV"sv, phasePoreVolume(oilPhaseIdx)}},
522 Entry{ScalarEntry{"BGPV"sv, phasePoreVolume(gasPhaseIdx)}},
523 Entry{ScalarEntry{std::vector{"BSOIL"sv, "BOSAT"sv},
524 [](const Context& ectx)
525 { return ectx.intQuants.saturationForOutput(oilPhaseIdx); }
526 }
527 },
528 Entry{ScalarEntry{std::vector{"BSGAS"sv, "BGSAT"sv},
529 [](const Context& ectx)
530 { return ectx.intQuants.saturationForOutput(gasPhaseIdx); }
531 }
532 },
533 Entry{ScalarEntry{std::vector{"BSWAT"sv, "BWSAT"sv},
534 [](const Context& ectx)
535 {
536 return ectx.intQuants.saturationForOutput(waterPhaseIdx);
537 }
538 }
539 },
540 Entry{ScalarEntry{std::vector{"BDENO"sv, "BODEN"sv},
541 densityIfPresent(oilPhaseIdx)
542 }
543 },
544 Entry{ScalarEntry{std::vector{"BDENG"sv, "BGDEN"sv},
545 densityIfPresent(gasPhaseIdx)
546 }
547 },
548 Entry{ScalarEntry{std::vector{"BDENW"sv, "BWDEN"sv},
549 densityIfPresent(waterPhaseIdx)
550 }
551 },
552 Entry{ScalarEntry{std::vector{"BVOIL"sv, "BOVIS"sv},
553 viscosityIfPresent(oilPhaseIdx)
554 }
555 },
556 Entry{ScalarEntry{std::vector{"BVGAS"sv, "BGVIS"sv},
557 viscosityIfPresent(gasPhaseIdx)
558 }
559 },
560 Entry{ScalarEntry{std::vector{"BVWAT"sv, "BWVIS"sv},
561 viscosityIfPresent(waterPhaseIdx)
562 }
563 },
564 Entry{ScalarEntry{std::vector{"BTEMP"sv, "BTCNFHEA"sv},
565 [](const Context& ectx)
566 {
567 return FluidSystem::phaseIsActive(oilPhaseIdx)
568 ? getValue(ectx.fs.temperature(oilPhaseIdx))
569 : getValue(ectx.fs.temperature(gasPhaseIdx));
570 }
571 }
572 },
573 };
574
575 this->blockExtractors_ = BlockExtractor::setupExecMap(this->blockData_, handlers);
576 }
577
580 {
581 this->extractors_.clear();
582 this->blockExtractors_.clear();
583 }
584
589 void processElement(const ElementContext& elemCtx)
590 {
591 OPM_TIMEBLOCK_LOCAL(processElement, Subsystem::Output);
592 if (!std::is_same<Discretization, EcfvDiscretization<TypeTag>>::value) {
593 return;
594 }
595
596 typename Extractor::HysteresisParams hysterParams{};
597 for (unsigned dofIdx = 0; dofIdx < elemCtx.numPrimaryDof(/*timeIdx=*/0); ++dofIdx) {
598 const auto& intQuants = elemCtx.intensiveQuantities(dofIdx, /*timeIdx=*/0);
599 const auto& fs = intQuants.fluidState();
600
601 const typename Extractor::Context ectx{
602 elemCtx.globalSpaceIndex(dofIdx, /*timeIdx=*/0),
603 0, // elemCtx.primaryVars(dofIdx, /*timeIdx=*/0).pvtRegionIndex(),
604 elemCtx.simulator().episodeIndex(),
605 fs,
606 intQuants,
607 hysterParams
608 };
609
610 Extractor::process(ectx, extractors_);
611 }
612 }
613
614 void processElementFlows(const ElementContext& /* elemCtx */)
615 {
616 OPM_TIMEBLOCK_LOCAL(processElementBlockData, Subsystem::Output);
617 if (!std::is_same_v<Discretization, EcfvDiscretization<TypeTag>>)
618 return;
619 }
620
621 void processElementBlockData(const ElementContext& elemCtx)
622 {
623 OPM_TIMEBLOCK_LOCAL(processElementBlockData, Subsystem::Output);
624 if (!std::is_same<Discretization, EcfvDiscretization<TypeTag>>::value)
625 return;
626
627 if (this->blockExtractors_.empty() || elemCtx.element().level() != 0) {
628 return;
629 }
630
631 for (unsigned dofIdx = 0; dofIdx < elemCtx.numPrimaryDof(/*timeIdx=*/0); ++dofIdx) {
632 const auto globalDofIdx = elemCtx.globalSpaceIndex(dofIdx, /*timeIdx=*/0);
633 const auto cartesianIdx = elemCtx.simulator().vanguard().cartesianIndex(globalDofIdx);
634
635 const auto be_it = this->blockExtractors_.find(cartesianIdx);
636 if (be_it == this->blockExtractors_.end()) {
637 continue;
638 }
639
640 const auto& intQuants = elemCtx.intensiveQuantities(dofIdx, /*timeIdx=*/0);
641
642 const typename BlockExtractor::Context ectx{
643 globalDofIdx,
644 dofIdx,
645 intQuants.fluidState(),
646 intQuants,
647 elemCtx,
648 };
649
650 BlockExtractor::process(be_it->second, ectx);
651 }
652 }
653
682 template <class ActiveIndex, class CartesianIndex>
683 void processFluxes(const ElementContext& /* elemCtx */,
684 ActiveIndex&& /* activeIndex*/,
685 CartesianIndex&& /* cartesianIndex */)
686 {
687 }
688
694 {
695 // Inter-region flow rates. Note: ".clear()" prepares to accumulate
696 // contributions per bulk connection between FIP regions.
697 this->interRegionFlows_.clear();
698 }
699
704 {
706 }
707
712 {
713 return this->interRegionFlows_;
714 }
715
716 void updateFluidInPlace(const unsigned globalDofIdx,
717 const IntensiveQuantities& intQuants,
718 const double totVolume)
719 {
720 // Pressure and pore-volume summaries do not require a surface-condition
721 // flash. Phase in-place volumes do, so those remain unavailable here.
722 const auto referencePorosity =
723 this->simulator_.problem().referencePorosity(globalDofIdx, /*timeIdx=*/0);
724 this->updateTotalVolumesAndPressures_(globalDofIdx,
725 intQuants,
726 totVolume,
727 referencePorosity);
728
729 // Run the nonlinear PSAT solve in the caller's OpenMP loop. The
730 // assignment is a no-op unless a PSAT restart buffer is allocated.
731 this->assignSaturationPressure_(globalDofIdx, intQuants);
732 }
733
736 void validateLocalData() override
737 {
738 if (this->compC_.saturationPressureRequested()) {
739 const auto& comm = this->simulator_.gridView().comm();
740 const auto totalUnresolved = comm.sum(this->numUnresolvedSaturationPressures_);
741 if (totalUnresolved > 0 && comm.rank() == 0) {
742 const std::string_view cell = totalUnresolved == 1 ? "cell" : "cells";
743 // Some unresolved searches correspond to states with no saturation
744 // boundary at this composition and temperature, so report the aggregate
745 // informationally rather than treating every result as a solver failure.
746 OpmLog::info(fmt::format("No saturation pressure was resolved in {} {}; "
747 "PSAT is written as zero there. This includes "
748 "mixtures that have none.",
749 totalUnresolved,
750 cell));
751 }
752 }
753 this->numUnresolvedSaturationPressures_ = 0;
755 }
756
757protected:
759 void allocFormulationBuffers(std::map<std::string, int>& rstKeywords,
760 const unsigned bufferSize) override
761 {
762 // Name each phase explicitly: the compositional phase ordering is not
763 // the one the black-oil keyword names assume.
764 const auto named = std::array{
765 std::pair{static_cast<unsigned>(oilPhaseIdx), std::string_view{"KRO"}},
766 std::pair{static_cast<unsigned>(gasPhaseIdx), std::string_view{"KRG"}},
767 std::pair{static_cast<unsigned>(waterPhaseIdx), std::string_view{"KRW"}},
768 };
769 for (const auto& [phase, kw] : named) {
770 if (phase >= numPhases || !FluidSystem::phaseIsActive(phase)) {
771 continue;
772 }
773 BaseType::allocBufferIfRequested(rstKeywords, bufferSize,
774 relativePermeability_[phase], kw, true);
775 }
776 }
777
778private:
779 using ScalarBuffer = typename BaseType::ScalarBuffer;
780 std::array<ScalarBuffer, numPhases> relativePermeability_;
781
782 bool isDefunctParallelWell(const std::string& wname) const override
783 {
784 if (simulator_.gridView().comm().size() == 1)
785 return false;
786 const auto& parallelWells = simulator_.vanguard().parallelWells();
787 std::pair<std::string, bool> value {wname, true};
788 auto candidate = std::lower_bound(parallelWells.begin(), parallelWells.end(), value);
789 return candidate == parallelWells.end() || *candidate != value;
790 }
791
792 bool isOwnedByCurrentRank(const std::string& wname) const override
793 {
794 // Note: This statement is not correct for distributed wells and
795 // will need additional logic once those are supported for
796 // compositional flows.
797 return ! this->isDefunctParallelWell(wname);
798 }
799
800 bool isOnCurrentRank(const std::string& wname) const override
801 {
802 // Note: This statement is not correct for distributed wells and
803 // will need additional logic once those are supported for
804 // compositional flows.
805 return ! this->isDefunctParallelWell(wname);
806 }
807
808 void createLocalRegion_(std::vector<int>& region)
809 {
810 std::size_t elemIdx = 0;
811 for (const auto& elem : elements(simulator_.gridView())) {
812 if (elem.partitionType() != Dune::InteriorEntity) {
813 region[elemIdx] = 0;
814 }
815
816 ++elemIdx;
817 }
818 }
819
823 void assignSaturationPressure_(const unsigned globalDofIdx,
824 const IntensiveQuantities& intQuants)
825 {
826 if (!this->compC_.saturationPressureAllocated()) {
827 return;
828 }
829
830 const auto& fluidState = intQuants.fluidState();
831 if (!intQuants.hasHydrocarbon()) {
832 this->compC_.assignSaturationPressure(globalDofIdx,
833 getValue(fluidState.pressure(oilPhaseIdx)));
834 return;
835 }
836
837 std::array<Scalar, numComponents> moleFractions{};
838 for (int c = 0; c < numComponents; ++c) {
839 moleFractions[c] = getValue(fluidState.moleFraction(c));
840 }
842 getValue(fluidState.L()),
843 getValue(fluidState.pressure(oilPhaseIdx)),
844 moleFractions,
845 getValue(fluidState.temperature(oilPhaseIdx)),
846 this->simulator_.problem().eosRegionIndex(globalDofIdx));
847 if (!psat) {
848 // A false result means only that no saturation pressure was resolved;
849 // it does not distinguish a physically absent boundary from numerical
850 // nonconvergence.
851#ifdef _OPENMP
852#pragma omp atomic
853#endif
854 ++this->numUnresolvedSaturationPressures_;
855 }
856
857 this->compC_.assignSaturationPressure(globalDofIdx, psat.value_or(Scalar{0}));
858 }
859
860 const Simulator& simulator_;
861 CompositionalContainer<FluidSystem> compC_;
862 std::size_t numUnresolvedSaturationPressures_{};
863 std::vector<typename Extractor::Entry> extractors_;
864 typename BlockExtractor::ExecMap blockExtractors_;
865};
866
867} // namespace Opm
868
869#endif // OPM_OUTPUT_COMPOSITIONAL_MODULE_HPP
Restart-output buffers specific to compositional simulations.
Common output functionality shared by simulator formulations.
Declares the properties required by the black oil model.
RestartOutput
Definition: CompositionalContainer.hpp:54
static std::optional< Scalar > cellSaturationPressure(const Scalar liquidFraction, const Scalar oilPressure, const std::array< Scalar, numComponents > &moleFractions, const Scalar temperature, const unsigned eosRegionIdx)
The base class for the element-centered finite-volume discretization scheme.
Definition: ecfvdiscretization.hh:160
Definition: GenericOutputModule.hpp:91
const Schedule & schedule_
Definition: GenericOutputModule.hpp:537
bool forceDisableFipOutput_
Definition: GenericOutputModule.hpp:558
virtual void validateLocalData()
Definition: GenericOutputModule.hpp:291
void doAllocBuffers(unsigned bufferSize, unsigned reportStepNum, const bool substep, const bool log, const bool forceRestartFieldAllocation, const EclHysteresisConfig *hysteresisConfig, unsigned numOutputNnc=0, std::map< std::string, int > rstKeywords={})
void setupBlockData(std::function< bool(int)> isCartIdxOnThisRank)
ScalarBuffer temperature_
Definition: GenericOutputModule.hpp:592
std::optional< RegionPhasePoreVolAverage > regionAvgDensity_
Definition: GenericOutputModule.hpp:661
std::array< ScalarBuffer, numPhases > viscosity_
Definition: GenericOutputModule.hpp:633
void setupLgrBlockData(const std::map< std::string, int > &lgrNameToLevel, const std::function< bool(int, int)> &isLgrCellOnThisRank)
void assignBuffer(data::Solution &sol, std::string_view name, UnitSystem::measure measure, std::vector< Scalar > &buffer)
static bool allocBufferIfRequested(std::map< std::string, int > &rstKeywords, unsigned bufferSize, std::vector< Scalar > &buffer, std::string_view kw, bool supported, bool required=false)
std::unordered_map< std::string, std::vector< int > > regions_
Definition: GenericOutputModule.hpp:572
std::map< std::pair< std::string, int >, double > blockData_
Definition: GenericOutputModule.hpp:646
LogOutputHelper< Scalar > logOutput_
Definition: GenericOutputModule.hpp:543
void assignPhaseProperties(data::Solution &sol, const PhasePropertyNames &names)
Move the phase density and viscosity buffers to sol under names.
std::vector< Scalar > ScalarBuffer
Definition: GenericOutputModule.hpp:325
void updateTotalVolumesAndPressures_(const unsigned globalDofIdx, const IntensiveQuantities &intQuants, const double totVolume, const Scalar referencePorosity)
Definition: GenericOutputModule.hpp:362
InterRegFlowMap interRegionFlows_
Definition: GenericOutputModule.hpp:542
std::array< ScalarBuffer, numPhases > density_
Definition: GenericOutputModule.hpp:632
std::array< ScalarBuffer, numPhases > saturation_
Definition: GenericOutputModule.hpp:631
const EclipseState & eclState_
Definition: GenericOutputModule.hpp:536
virtual void assignToSolution(data::Solution &sol)
Move all buffers to data::Solution.
const Inplace * initialInplace() const
Definition: GenericOutputModule.hpp:274
static void registerParameters()
Register all run-time parameters for the Vtk output module.
ScalarBuffer fluidPressure_
Definition: GenericOutputModule.hpp:591
Inter-region flow accumulation maps for all region definition arrays.
Definition: InterRegFlows.hpp:179
void clear()
Clear all internal buffers, but preserve allocated capacity.
Output module for compositional-model results written in ECL binary format.
Definition: OutputCompositionalModule.hpp:82
void processElementFlows(const ElementContext &)
Definition: OutputCompositionalModule.hpp:614
void clearExtractors()
Clear the active element and block extractors.
Definition: OutputCompositionalModule.hpp:579
static void registerParameters()
Definition: OutputCompositionalModule.hpp:101
void initializeFluxData()
Prepare for capturing connection fluxes, particularly to account for inter-region flows.
Definition: OutputCompositionalModule.hpp:693
void setupBlockExtractors_()
Setup the block (B*) summary extractors.
Definition: OutputCompositionalModule.hpp:454
void setupExtractors(const bool, const std::size_t)
Setup list of active element-level data extractors.
Definition: OutputCompositionalModule.hpp:319
void updateFluidInPlace(const unsigned globalDofIdx, const IntensiveQuantities &intQuants, const double totVolume)
Definition: OutputCompositionalModule.hpp:716
void allocFormulationBuffers(std::map< std::string, int > &rstKeywords, const unsigned bufferSize) override
Allocate compositional relative-permeability buffers.
Definition: OutputCompositionalModule.hpp:759
void outputFipAndResvLogToCSV(const std::size_t reportStepNum, const bool substep, const Parallel::Communication &comm)
Definition: OutputCompositionalModule.hpp:284
void allocBuffers(const unsigned bufferSize, const unsigned reportStepNum, const bool substep, const bool log, const bool forceRestartFieldAllocation)
Allocate memory for the scalar fields we would like to write to ECL output files.
Definition: OutputCompositionalModule.hpp:179
void finalizeFluxData()
Finalize capturing connection fluxes.
Definition: OutputCompositionalModule.hpp:703
void processElement(const ElementContext &elemCtx)
Modify the internal buffers according to the intensive quanties relevant for an element.
Definition: OutputCompositionalModule.hpp:589
OutputCompositionalModule(const Simulator &simulator, const SummaryConfig &smryCfg, const CollectDataToIORankType &collectToIORank)
Definition: OutputCompositionalModule.hpp:108
void processElementBlockData(const ElementContext &elemCtx)
Definition: OutputCompositionalModule.hpp:621
void validateLocalData() override
Definition: OutputCompositionalModule.hpp:736
void assignToSolution(data::Solution &sol) override
Move all buffers to data::Solution.
Definition: OutputCompositionalModule.hpp:205
void processFluxes(const ElementContext &, ActiveIndex &&, CartesianIndex &&)
Capture connection fluxes, particularly to account for inter-region flows.
Definition: OutputCompositionalModule.hpp:683
const InterRegFlowMap & getInterRegFlows() const
Get read-only access to collection of inter-region flows.
Definition: OutputCompositionalModule.hpp:711
void outputFipAndResvLog(const Inplace &inplace, const std::size_t reportStepNum, double elapsed, boost::posix_time::ptime currentDate, const bool substep, const Parallel::Communication &comm)
Definition: OutputCompositionalModule.hpp:232
Defines the common properties required by the porous medium multi-phase models.
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Definition: blackoilbioeffectsmodules.hh:45
std::string moduleVersionName()
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
This file provides the infrastructure to retrieve run-time parameters.
The Opm property system, traits with inheritance.
Definition: GenericOutputModule.hpp:410
std::string_view oilDensity
Definition: GenericOutputModule.hpp:411
static void registerParameters()
Registers the parameters in parameter system.
Context passed to element extractor functions.
Definition: OutputExtractor.hpp:208
Definition: OutputExtractor.hpp:228
Wrapping struct holding types used for block-level data extraction.
Definition: OutputExtractor.hpp:195
std::variant< ScalarEntry, PhaseEntry, TensorEntry > Entry
Descriptor for extractors.
Definition: OutputExtractor.hpp:262
std::unordered_map< int, std::vector< Exec > > ExecMap
A map of extraction executors, keyed by cartesian cell index.
Definition: OutputExtractor.hpp:277
static ExecMap setupExecMap(std::map< std::pair< std::string, int >, double > &blockData, const std::span< const Entry > handlers)
Setup an extractor executor map from a map of evaluations to perform.
Definition: OutputExtractor.hpp:410
static void process(const std::vector< Exec > &blockExtractors, const Context &ectx)
Process a list of block extractors.
Definition: OutputExtractor.hpp:435
Context passed to extractor functions.
Definition: OutputExtractor.hpp:77
int episodeIndex
Current report step.
Definition: OutputExtractor.hpp:80
Descriptor for extractors.
Definition: OutputExtractor.hpp:116
Struct holding hysteresis parameters.
Definition: OutputExtractor.hpp:66
A phase buffer extractor descriptor.
Definition: OutputExtractor.hpp:109
A scalar extractor descriptor.
Definition: OutputExtractor.hpp:102
Wrapping struct holding types used for element-level data extraction.
Definition: OutputExtractor.hpp:57
static void process(const Context &ectx, const std::vector< Entry > &extractors)
Process the given extractor entries.
Definition: OutputExtractor.hpp:160
static std::vector< Entry > removeInactive(std::array< Entry, size > &input)
Obtain vector of active extractors from an array of extractors.
Definition: OutputExtractor.hpp:123