InitStateEquilComp.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 Copyright 2026 SINTEF Digital
5
6 This file is part of the Open Porous Media project (OPM).
7
8 OPM is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 OPM is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with OPM. If not, see <http://www.gnu.org/licenses/>.
20
21 Consult the COPYING file in the top-level source directory of this
22 module for the precise wording of the license and the list of
23 copyright holders.
24*/
31#ifndef OPM_INIT_STATE_EQUIL_COMP_HPP
32#define OPM_INIT_STATE_EQUIL_COMP_HPP
33
34#include <opm/common/ErrorMacros.hpp>
35#include <opm/common/OpmLog/OpmLog.hpp>
36
37#include <opm/material/common/Tabulated1DFunction.hpp>
38#include <opm/material/constraintsolvers/SaturationPressure.hpp>
39#include <opm/material/fluidstates/CompositionalFluidState.hpp>
40
41#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
42#include <opm/input/eclipse/EclipseState/InitConfig/Equil.hpp>
43#include <opm/input/eclipse/EclipseState/Tables/CompvdTable.hpp>
44#include <opm/input/eclipse/EclipseState/Tables/RtempvdTable.hpp>
45#include <opm/input/eclipse/EclipseState/Tables/SwfnTable.hpp>
46#include <opm/input/eclipse/EclipseState/Tables/TableContainer.hpp>
47#include <opm/input/eclipse/EclipseState/Tables/TableManager.hpp>
48#include <opm/input/eclipse/EclipseState/Tables/ZmfvdTable.hpp>
49#include <opm/input/eclipse/Units/Units.hpp>
50
55
56#include <fmt/format.h>
57#include <fmt/ranges.h>
58
59#include <algorithm>
60#include <array>
61#include <cmath>
62#include <cstddef>
63#include <functional>
64#include <iterator>
65#include <limits>
66#include <map>
67#include <numeric>
68#include <optional>
69#include <stdexcept>
70#include <string>
71#include <string_view>
72#include <utility>
73#include <vector>
74
75
76namespace Opm::EQUIL::Comp {
77
78namespace Details {
79
83template <class Scalar>
84Scalar evalDepthTable(const Tabulated1DFunction<Scalar>& table, const Scalar depth)
85{
86 return table.eval(std::clamp(depth, table.xMin(), table.xMax()));
87}
88
93template <class FluidSystem>
95{
96public:
97 using Scalar = typename FluidSystem::Scalar;
98 using CompVec = std::array<Scalar, FluidSystem::numComponents>;
99 using CompositionFunction = std::function<CompVec(Scalar)>;
100 using TabulatedFunction = Tabulated1DFunction<Scalar>;
101
103 const TabulatedFunction& tempVdTable,
104 const unsigned phaseIdx,
105 const unsigned eosRegion,
106 const Scalar normGrav)
107 : composition_(std::move(composition))
108 , tempVdTable_(tempVdTable)
109 , phaseIdx_(phaseIdx)
110 , eosRegion_(eosRegion)
111 , g_(normGrav)
112 {}
113
115 const Scalar press) const
116 {
117 const CompVec z = composition_(depth);
118 const Scalar temp = evalDepthTable(tempVdTable_, depth);
119
120 CompositionalFluidState<Scalar, FluidSystem> fs;
121 fs.setTemperature(temp);
122 fs.setPressure(FluidSystem::oilPhaseIdx, press);
123 fs.setPressure(FluidSystem::gasPhaseIdx, press);
124 for (unsigned compIdx = 0; compIdx < FluidSystem::numComponents; ++compIdx) {
125 fs.setMoleFraction(phaseIdx_, compIdx, z[compIdx]);
126 }
127
128 typename FluidSystem::template ParameterCache<Scalar> paramCache(eosRegion_);
129 paramCache.updatePhase(fs, phaseIdx_);
130
131 return FluidSystem::density(fs, paramCache, phaseIdx_) * g_;
132 }
133
134private:
135 CompositionFunction composition_;
136 const TabulatedFunction& tempVdTable_;
137 unsigned phaseIdx_;
138 unsigned eosRegion_;
139 Scalar g_;
140};
141
144template <class FluidSystem>
146{
147public:
148 using Scalar = typename FluidSystem::Scalar;
149 using TabulatedFunction = Tabulated1DFunction<Scalar>;
150
152 const unsigned eosRegion,
153 const unsigned pvtRegion,
154 const Scalar normGrav)
155 : tempVdTable_(tempVdTable)
156 , eosRegion_(eosRegion)
157 , pvtRegion_(pvtRegion)
158 , g_(normGrav)
159 {}
160
162 const Scalar press) const
163 {
164 CompositionalFluidState<Scalar, FluidSystem> fs;
165 fs.setTemperature(evalDepthTable(tempVdTable_, depth));
166 fs.setPressure(FluidSystem::waterPhaseIdx, press);
167
168 typename FluidSystem::template ParameterCache<Scalar> paramCache(eosRegion_);
169 paramCache.setPvtRegionIndex(pvtRegion_);
170
171 return FluidSystem::density(fs, paramCache, FluidSystem::waterPhaseIdx) * g_;
172 }
173
174private:
175 const TabulatedFunction& tempVdTable_;
176 unsigned eosRegion_;
177 unsigned pvtRegion_;
178 Scalar g_;
179};
180
181} // namespace Details
182
241template <class FluidSystem>
243{
244public:
245 using Scalar = typename FluidSystem::Scalar;
246 using FluidState = CompositionalFluidState<Scalar, FluidSystem>;
247
263 InitialStateComputer(const EclipseState& inputState,
264 const std::vector<int>& eosnum,
265 const std::vector<Scalar>& cellCenterDepth,
266 const std::vector<int>& eqlnum,
267 const std::vector<int>& pvtnum,
268 const Parallel::Communication& comm,
269 const Scalar gravity,
270 const int numSamplePoints,
271 const std::vector<Scalar>& connateWater = {},
272 const std::vector<Scalar>& maxWater = {})
273 : gravity_(gravity)
274 , numSamplePoints_(numSamplePoints)
275 , connateWater_(connateWater)
276 , maxWater_(maxWater)
277 {
278 const auto& records = inputState.getInitConfig().getEquil();
279 const auto& tables = inputState.getTableManager();
280
281 if (!tables.hasTables("ZMFVD") && !tables.hasTables("COMPVD")) {
282 OPM_THROW(std::runtime_error,
283 "Equilibration of a compositional model requires the composition "
284 "versus depth from the ZMFVD or the COMPVD keyword.");
285 }
286
287 const auto numPvtRegions = tables.getTabdims().getNumPVTTables();
289 if (eqlnum.size() != cellCenterDepth.size()) {
290 OPM_THROW(std::runtime_error,
291 fmt::format("EQLNUM contains {} entries for {} cell depths.",
292 eqlnum.size(), cellCenterDepth.size()));
293 }
294 for (std::size_t cell = 0; cell < eqlnum.size(); ++cell) {
295 const auto region = eqlnum[cell];
296 if (region < 0 || std::cmp_greater_equal(region, records.size())) {
297 OPM_THROW(std::runtime_error,
298 fmt::format("Cell {} has EQLNUM {} outside the {} "
299 "equilibration regions.",
300 cell, region + 1, records.size()));
301 }
302 }
303 if (!pvtnum.empty() && (pvtnum.size() != cellCenterDepth.size())) {
304 OPM_THROW(std::runtime_error,
305 fmt::format("PVTNUM contains {} entries for {} cell depths.",
306 pvtnum.size(), cellCenterDepth.size()));
307 }
308 for (std::size_t cell = 0; cell < pvtnum.size(); ++cell) {
309 const auto region = pvtnum[cell];
310 if (region < 0 || std::cmp_greater_equal(region, numPvtRegions)) {
311 OPM_THROW(std::runtime_error,
312 fmt::format("Cell {} has PVTNUM {} outside the {} "
313 "PVT regions.",
314 cell, region + 1, numPvtRegions));
315 }
316 }
317 if (!eosnum.empty() && (eosnum.size() != cellCenterDepth.size())) {
318 OPM_THROW(std::runtime_error,
319 fmt::format("EOSNUM contains {} entries for {} cell depths.",
320 eosnum.size(), cellCenterDepth.size()));
321 }
322 const auto numEosRegions = inputState.runspec().tabdims().getNumEosRes();
323 for (std::size_t cell = 0; cell < eosnum.size(); ++cell) {
324 const auto region = eosnum[cell];
325 if (region < 0 || std::cmp_greater_equal(region, numEosRegions)) {
326 OPM_THROW(std::runtime_error,
327 fmt::format("Cell {} has EOSNUM {} outside the {} "
328 "EOS regions.",
329 cell, region + 1, numEosRegions));
330 }
331 }
332 // The endpoint vectors are optional, but a non-empty one is indexed for
333 // every cell.
334 for (const auto& [name, limits] : {std::pair{"connate water", std::cref(connateWater)},
335 std::pair{"maximum water", std::cref(maxWater)}}) {
336 if (!limits.get().empty() &&
337 (limits.get().size() != cellCenterDepth.size())) {
338 OPM_THROW(std::runtime_error,
339 fmt::format("The {} saturation has {} entries for {} cell depths.",
340 name, limits.get().size(), cellCenterDepth.size()));
341 }
342 }
343 OPM_END_PARALLEL_TRY_CATCH("Invalid equilibration input: ", comm);
344
345 const auto pvtRegions =
346 pvtRegionsOfEachRegion(eqlnum, pvtnum, records.size(), numPvtRegions, comm);
347 const auto eosRegions = eosRegionOfEachEqlRegion(eqlnum, eosnum, records.size(), comm);
348 regions_.reserve(records.size());
349 for (std::size_t r = 0; r < records.size(); ++r) {
350 regions_.push_back(setupRegion(records.getRecord(r), tables, pvtRegions[r],
351 eosRegions[r], cellCenterDepth, eqlnum, pvtnum, comm,
352 gravity, numSamplePoints, r));
353 }
354
355 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
356 fluidStates_.resize(cellCenterDepth.size());
357 referencePressures_.resize(cellCenterDepth.size());
358 twoPhaseCheckRegions_.assign(cellCenterDepth.size(), -1);
359 for (std::size_t cell = 0; cell < cellCenterDepth.size(); ++cell) {
360 const auto& reg = regions_[eqlnum[cell]];
361 const auto pvtRegion = pvtnum.empty() ? 0u : static_cast<unsigned>(pvtnum[cell]);
362 referencePressures_[cell] = assignCell(fluidStates_[cell], reg,
363 pvtRegion, cellCenterDepth[cell], cell);
364 // The type 3 gas is saturated at the contact, so the lower pressure
365 // above it splits that gas slightly. Below the water-oil contact
366 // the pore space holds water.
367 if ((reg.initType == 1) && !(waterActive && (cellCenterDepth[cell] > reg.zwoc))) {
368 twoPhaseCheckRegions_[cell] = eqlnum[cell];
369 }
370 }
371 }
372
373 std::vector<FluidState>& fluidStates()
374 { return fluidStates_; }
375
376 const std::vector<FluidState>& fluidStates() const
377 { return fluidStates_; }
378
382 const std::vector<Scalar>& referencePressures() const
383 { return referencePressures_; }
384
389 std::vector<int>& twoPhaseCheckRegions()
390 { return twoPhaseCheckRegions_; }
391
392 const std::vector<int>& twoPhaseCheckRegions() const
393 { return twoPhaseCheckRegions_; }
394
399 {
406 unsigned pvtRegion{};
407 };
408
411
442 std::vector<std::vector<ReportRow>>
443 compositionVersusDepth(const std::vector<ReportRegion>& regions) const
444 {
445 std::vector<std::vector<ReportRow>> rows(regions_.size());
446 for (std::size_t r = 0; r < regions_.size(); ++r) {
447 // A region without cells has no columns.
448 if (regions_[r].oilPressure.has_value()) {
449 rows[r] = reportRows(regions_[r], regions.at(r));
450 }
451 }
452 return rows;
453 }
454
455private:
456 using CompVec = std::array<Scalar, FluidSystem::numComponents>;
457 using TabulatedFunction = Tabulated1DFunction<Scalar>;
462
463 static constexpr int numComponents = FluidSystem::numComponents;
464
468 static constexpr Scalar constantTableSpan{1.0};
469
472 static constexpr Scalar minimumSpanExtent{1.0};
473
475 struct Region {
476 int initType{1}; // EQUIL item 10
478 Scalar datum{};
479 Scalar statedGoc{};
481 std::vector<unsigned> pvtRegions;
483 unsigned eosRegion{0};
485 Scalar zgoc{};
487 std::string_view compositionKeyword;
489 std::optional<unsigned> statedPhaseIdx{};
491 unsigned nominalPhaseIdx{FluidSystem::oilPhaseIdx};
494 bool twoZone{false};
498 Scalar lastVaporDepth{};
500 std::vector<TabulatedFunction> vaporVdTable;
502 CompVec vaporComposition{};
504 std::optional<TabulatedFunction> statedSaturationPressure;
506 std::array<Scalar, 2> span{};
508 std::vector<TabulatedFunction> compositionVdTable;
509 TabulatedFunction tempVdTable;
510 std::optional<PressFunc> oilPressure;
511 std::optional<PressFunc> gasPressure; // two zones, or type 3
512
513 Scalar zwoc{}; // water-oil contact
517 bool anchoredAtWaterContact{false};
519 std::map<unsigned, WaterPressFunc> waterPressure;
520 };
521
524 static std::array<Scalar, 2> waterContactSpan(const Region& reg,
525 const std::array<Scalar, 2>& span)
526 {
527 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
528 return {std::min(span[0], reg.zwoc), std::max(span[1], reg.zwoc)};
529 }
530 return span;
531 }
532
534 static CompVec vaporComposition(const Region& reg, const Scalar depth)
535 {
536 CompVec z{};
537 Scalar sum = 0.0;
538 for (int c = 0; c < numComponents; ++c) {
539 z[c] = std::max(Scalar{0}, Details::evalDepthTable(reg.vaporVdTable[c], depth));
540 sum += z[c];
541 }
542 if (!(sum > 0.0)) {
543 OPM_THROW(std::runtime_error,
544 fmt::format("The COMPVD vapour composition vanishes at depth {} m.", depth));
545 }
546 std::ranges::transform(z, z.begin(), [sum](const Scalar zc) { return zc / sum; });
547 return z;
548 }
549
550 static CompVec composition(const Region& reg, const Scalar depth)
551 {
552 CompVec z{};
553 Scalar sum{};
554 for (int c = 0; c < numComponents; ++c) {
555 z[c] = std::max(Scalar{0}, Details::evalDepthTable(reg.compositionVdTable[c], depth));
556 sum += z[c];
557 }
558 if (!(sum > 0.0)) {
559 OPM_THROW(std::runtime_error,
560 fmt::format("The composition vanishes at depth {} m.", depth));
561 }
562 std::ranges::transform(z, z.begin(), [sum](const Scalar zc) { return zc / sum; });
563 return z;
564 }
565
569 static typename ODE::CompositionFunction gasColumnComposition(const Region& reg)
570 {
571 if (reg.initType == 1) {
572 return [&reg](const Scalar depth) { return composition(reg, depth); };
573 }
574 if (reg.twoZone) {
575 return [&reg](const Scalar depth) { return vaporComposition(reg, depth); };
576 }
577 return [vapor = reg.vaporComposition](const Scalar) { return vapor; };
578 }
579
581 static TabulatedFunction saturationPressureTable(const CompvdTable& compvd)
582 {
583 const auto& depthCol = compvd.getDepthColumn();
584 const auto& psatCol = compvd.getSaturationPressureColumn();
585 std::vector<Scalar> depths(depthCol.begin(), depthCol.end());
586 std::vector<Scalar> psat(psatCol.begin(), psatCol.end());
587 // As for the composition, a single row needs a second sample point.
588 if (depths.size() == 1) {
589 depths.push_back(depths.front() + constantTableSpan);
590 psat.push_back(psat.front());
591 }
592 TabulatedFunction table;
593 table.setXYContainers(depths, psat);
594 return table;
595 }
596
599 template <class Table>
600 static void setupComposition(std::vector<TabulatedFunction>& out,
601 const Table& table,
602 const std::vector<std::size_t>& rows)
603 {
604 const auto& depthCol = table.getDepthColumn();
605
606 std::vector<Scalar> depths;
607 depths.reserve(rows.size() + 1);
608 for (const auto row : rows) {
609 depths.push_back(depthCol[row]);
610 }
611 // A single row means a depth-independent composition; the interpolant
612 // needs two sample points, so duplicate it onto an arbitrary interval.
613 const bool constantComposition = (depths.size() == 1);
614 if (constantComposition) {
615 depths.push_back(depths.front() + constantTableSpan);
616 }
617
618 out.resize(numComponents);
619 for (int c = 0; c < numComponents; ++c) {
620 const auto& col = table.getMoleFractionColumn(c);
621 std::vector<Scalar> values;
622 values.reserve(depths.size());
623 for (const auto row : rows) {
624 values.push_back(col[row]);
625 }
626 if (constantComposition) {
627 values.push_back(values.front());
628 }
629 out[c].setXYContainers(depths, values);
630 }
631 }
632
635 static std::optional<std::size_t> sourceTable(const TableContainer& container,
636 const std::size_t regionIdx)
637 {
638 const auto& byIndex = container.tables();
639 const auto after = byIndex.upper_bound(regionIdx);
640 if (after == byIndex.begin()) {
641 return std::nullopt;
642 }
643 return std::prev(after)->first;
644 }
645
647 static std::vector<std::size_t> allRows(const std::size_t count)
648 {
649 std::vector<std::size_t> rows(count);
650 std::iota(rows.begin(), rows.end(), std::size_t{0});
651 return rows;
652 }
653
660 static Scalar zoneBoundary(const CompvdTable& compvd,
661 const std::vector<std::size_t>& vaporRows,
662 const std::vector<std::size_t>& liquidRows,
663 const Region& reg,
664 const std::size_t regionIdx)
665 {
666 if (vaporRows.empty() || liquidRows.empty()) {
667 OPM_THROW(std::runtime_error,
668 fmt::format("The COMPVD table of region {} names both phases but has "
669 "no row for one of them.", regionIdx + 1));
670 }
671
672 const auto& depth = compvd.getDepthColumn();
673 const Scalar lastVapor = depth[vaporRows.back()];
674 const Scalar firstLiquid = depth[liquidRows.front()];
675 if (lastVapor > firstLiquid) {
676 OPM_THROW(std::runtime_error,
677 fmt::format("The COMPVD table of region {} has a vapour row at {} m "
678 "below its liquid row at {} m. All vapour rows must lie "
679 "above the liquid rows.",
680 regionIdx + 1, lastVapor, firstLiquid));
681 }
682
683 const Scalar boundary = std::clamp(reg.zgoc, lastVapor, firstLiquid);
684 if (boundary == reg.zgoc) {
685 return boundary;
686 }
687
688 if (reg.initType != 1) {
689 OPM_THROW(std::runtime_error,
690 fmt::format("The COMPVD table of region {} puts its vapour rows down to "
691 "{} m and its liquid rows from {} m, which do not meet at "
692 "the gas-oil contact at {} m. EQUIL item 10 = {} takes the "
693 "contact as the reference depth, so the rows must agree "
694 "with it.",
695 regionIdx + 1, lastVapor, firstLiquid, reg.zgoc,
696 reg.initType));
697 }
698
699 OpmLog::warning(fmt::format("Equilibration region {}: the gas-oil contact at {} m lies "
700 "outside the COMPVD phase change between the last vapour "
701 "row at {} m and the first liquid row at {} m. With EQUIL "
702 "item 10 = 1 the rows give the composition versus depth, "
703 "so the gas zone ends at {} m instead.",
704 regionIdx + 1, reg.zgoc, lastVapor, firstLiquid, boundary));
705 return boundary;
706 }
707
709 static std::vector<std::size_t> rowsOfPhase(const CompvdTable& compvd,
710 const CompvdTable::Phase phase)
711 {
712 const auto& flags = compvd.phaseFlags();
713 std::vector<std::size_t> rows;
714 for (std::size_t r = 0; r < flags.size(); ++r) {
715 if (flags[r] == phase) {
716 rows.push_back(r);
717 }
718 }
719 return rows;
720 }
721
724 static std::optional<unsigned> statedPhase(const CompvdTable& compvd,
725 const std::size_t regionIdx)
726 {
727 const auto& flags = compvd.phaseFlags();
728 if (flags.empty()) {
729 return std::nullopt;
730 }
731
732 const auto first = flags.front();
733 if (std::ranges::any_of(flags, [first](const auto f) { return f != first; })) {
734 OpmLog::info(fmt::format("Equilibration region {}: COMPVD names both phases, "
735 "so the contact and row labels determine the gas and "
736 "liquid zones.",
737 regionIdx + 1));
738 return std::nullopt;
739 }
740
741 return (first == CompvdTable::Phase::Vapor)
742 ? FluidSystem::gasPhaseIdx : FluidSystem::oilPhaseIdx;
743 }
744
746 static bool compositionVariesBetween(const Region& reg,
747 const Scalar depthA,
748 const Scalar depthB)
749 {
750 // Input mole fractions that differ physically across the contact should
751 // exceed this round-off tolerance.
752 constexpr Scalar sameComposition{1.0e-10};
753
754 const CompVec a = composition(reg, depthA);
755 const CompVec b = composition(reg, depthB);
756 return !std::ranges::equal(a, b, [](const Scalar x, const Scalar y) {
757 return std::abs(x - y) <= sameComposition;
758 });
759 }
760
763 static std::vector<std::vector<unsigned>>
764 pvtRegionsOfEachRegion(const std::vector<int>& eqlnum,
765 const std::vector<int>& pvtnum,
766 const std::size_t numRegions,
767 const std::size_t numPvtRegions,
768 const Parallel::Communication& comm)
769 {
770 // Whether equilibration region r holds a cell of PVT region p, at
771 // r * numPvtRegions + p.
772 std::vector<int> present(numRegions * numPvtRegions, 0);
773 for (std::size_t cell = 0; cell < eqlnum.size(); ++cell) {
774 const auto pvtRegion = pvtnum.empty() ? 0 : pvtnum[cell];
775 present[static_cast<std::size_t>(eqlnum[cell]) * numPvtRegions
776 + static_cast<std::size_t>(pvtRegion)] = 1;
777 }
778 comm.max(present.data(), static_cast<int>(present.size()));
779
780 std::vector<std::vector<unsigned>> pvtRegions(numRegions);
781 for (std::size_t r = 0; r < numRegions; ++r) {
782 for (std::size_t p = 0; p < numPvtRegions; ++p) {
783 if (present[r * numPvtRegions + p] != 0) {
784 pvtRegions[r].push_back(static_cast<unsigned>(p));
785 }
786 }
787 }
788 return pvtRegions;
789 }
790
793 static std::vector<unsigned>
794 eosRegionOfEachEqlRegion(const std::vector<int>& eqlnum,
795 const std::vector<int>& eosnum,
796 const std::size_t numRegions,
797 const Parallel::Communication& comm)
798 {
799 std::vector<int> lowest(numRegions, std::numeric_limits<int>::max());
800 std::vector<int> highest(numRegions, std::numeric_limits<int>::min());
801 for (std::size_t cell = 0; cell < eosnum.size(); ++cell) {
802 const auto region = eqlnum[cell];
803 lowest[region] = std::min(lowest[region], eosnum[cell]);
804 highest[region] = std::max(highest[region], eosnum[cell]);
805 }
806 comm.min(lowest.data(), static_cast<int>(numRegions));
807 comm.max(highest.data(), static_cast<int>(numRegions));
808
809 std::vector<unsigned> eosRegions(numRegions, 0);
810 for (std::size_t r = 0; r < numRegions; ++r) {
811 if (lowest[r] > highest[r]) {
812 continue;
813 }
814 if (lowest[r] != highest[r]) {
815 OPM_THROW(std::runtime_error,
816 fmt::format("Equilibration region {} holds cells of EOS regions "
817 "{} and {}; each equilibration region must lie "
818 "within one EOS region.",
819 r + 1, lowest[r] + 1, highest[r] + 1));
820 }
821 eosRegions[r] = static_cast<unsigned>(lowest[r]);
822 }
823 return eosRegions;
824 }
825
826 Region setupRegion(const EquilRecord& record,
827 const TableManager& tables,
828 const std::vector<unsigned>& pvtRegions,
829 const unsigned eosRegion,
830 const std::vector<Scalar>& cellCenterDepth,
831 const std::vector<int>& eqlnum,
832 const std::vector<int>& pvtnum,
833 const Parallel::Communication& comm,
834 const Scalar gravity,
835 const int numSamplePoints,
836 const std::size_t regionIdx) const
837 {
838 Region reg;
839
840 reg.pvtRegions = pvtRegions;
841 reg.eosRegion = eosRegion;
842 reg.initType = record.compositionalInitType();
843 if (reg.initType != 1 && reg.initType != 3) {
844 OPM_THROW(std::runtime_error,
845 fmt::format("Compositional initialization type {} (EQUIL item 10) is "
846 "not supported for region {}; only type 1 (total "
847 "composition) and type 3 (liquid composition) are.",
848 reg.initType, regionIdx + 1));
849 }
850
851 if (record.gasOilContactCapillaryPressure() != 0.0) {
852 OPM_THROW(std::runtime_error,
853 fmt::format("Compositional equilibration only supports zero gas-oil "
854 "contact capillary pressure (EQUIL item 6); region {} "
855 "specifies {} bar.",
856 regionIdx + 1,
857 unit::convert::to(record.gasOilContactCapillaryPressure(),
858 unit::barsa)));
859 }
860
861 if (const auto accuracy = record.initializationTargetAccuracy(); accuracy != 0) {
862 OPM_THROW(std::runtime_error,
863 fmt::format("Compositional equilibration only supports cell-centre "
864 "initialization (EQUIL item 9 = 0); region {} specifies {}.",
865 regionIdx + 1, accuracy));
866 }
867
868 reg.zgoc = record.gasOilContactDepth();
869 reg.datum = record.datumDepth();
870 reg.statedGoc = reg.zgoc;
871
872 // With one composition keyword, a missing regional record inherits the
873 // nearest preceding record. If both keywords are present, each region
874 // must select one explicitly because inheritance would be ambiguous.
875 const bool deckHasZmfvd = tables.hasTables("ZMFVD");
876 const bool deckHasCompvd = tables.hasTables("COMPVD");
877 const bool statesZmfvd = deckHasZmfvd &&
878 tables.getZmfvdTables().hasTable(regionIdx);
879 const bool statesCompvd = deckHasCompvd &&
880 tables.getCompvdTables().hasTable(regionIdx);
881
882 if (statesZmfvd && statesCompvd) {
883 OPM_THROW(std::runtime_error,
884 fmt::format("Region {} has both a ZMFVD and a COMPVD composition "
885 "versus depth; give only one of them.", regionIdx + 1));
886 }
887
888 std::optional<std::size_t> zmfvdAt;
889 std::optional<std::size_t> compvdAt;
890 if (deckHasZmfvd && deckHasCompvd) {
891 if (!statesZmfvd && !statesCompvd) {
892 OPM_THROW(std::runtime_error,
893 fmt::format("Region {} has neither a ZMFVD nor a COMPVD "
894 "composition versus depth. A deck using both "
895 "keywords has to give every region a record of "
896 "its own, as neither can be inherited.",
897 regionIdx + 1));
898 }
899 (statesZmfvd ? zmfvdAt : compvdAt) = regionIdx;
900 }
901 else if (deckHasZmfvd) {
902 zmfvdAt = sourceTable(tables.getZmfvdTables(), regionIdx);
903 }
904 else if (deckHasCompvd) {
905 compvdAt = sourceTable(tables.getCompvdTables(), regionIdx);
906 }
907
908 if (!zmfvdAt.has_value() && !compvdAt.has_value()) {
909 OPM_THROW(std::runtime_error,
910 fmt::format("Region {} has neither a ZMFVD nor a COMPVD composition "
911 "versus depth.", regionIdx + 1));
912 }
913
914 if (zmfvdAt.has_value()) {
915 reg.compositionKeyword = "ZMFVD";
916 const auto& zmfvd =
917 tables.getZmfvdTables().template getTable<ZmfvdTable>(*zmfvdAt);
918 setupComposition(reg.compositionVdTable, zmfvd,
919 allRows(zmfvd.getDepthColumn().size()));
920 }
921 else {
922 reg.compositionKeyword = "COMPVD";
923 const auto& compvd =
924 tables.getCompvdTables().template getTable<CompvdTable>(*compvdAt);
925 reg.statedPhaseIdx = statedPhase(compvd, regionIdx);
926 reg.statedSaturationPressure = saturationPressureTable(compvd);
927
928 if (reg.statedPhaseIdx.has_value()) {
929 // One phase named: all rows form one composition profile, and
930 // the phase flag selects its EOS root.
931 if ((reg.initType == 3) &&
932 (*reg.statedPhaseIdx == FluidSystem::gasPhaseIdx)) {
933 OPM_THROW(std::runtime_error,
934 fmt::format("Region {} states a vapour composition in COMPVD "
935 "while EQUIL item 10 is 3, which takes the liquid "
936 "composition at the gas-oil contact.",
937 regionIdx + 1));
938 }
939 setupComposition(reg.compositionVdTable, compvd,
940 allRows(compvd.getDepthColumn().size()));
941 }
942 else {
943 // Both phases named: the gas root applies above the effective
944 // contact and the liquid root below it. For type 1 all rows give
945 // the total composition, interpolated across the gap between the
946 // two phases as well. Type 3 takes the gas from the vapour rows
947 // and the liquid from the liquid rows.
948 const auto vaporRows = rowsOfPhase(compvd, CompvdTable::Phase::Vapor);
949 const auto liquidRows = rowsOfPhase(compvd, CompvdTable::Phase::Liquid);
950 reg.zgoc = zoneBoundary(compvd, vaporRows, liquidRows, reg, regionIdx);
951 reg.twoZone = true;
952 reg.lastVaporDepth = compvd.getDepthColumn()[vaporRows.back()];
953 if (reg.initType == 1) {
954 setupComposition(reg.compositionVdTable, compvd,
955 allRows(compvd.getDepthColumn().size()));
956 }
957 else {
958 setupComposition(reg.vaporVdTable, compvd, vaporRows);
959 setupComposition(reg.compositionVdTable, compvd, liquidRows);
960 }
961 }
962 }
963
964 if (tables.hasTables("RTEMPVD")) {
965 const auto& rtempvd =
966 tables.getRtempvdTables().template getTable<RtempvdTable>(regionIdx);
967 std::vector<Scalar> tempDepths(rtempvd.getDepthColumn().begin(),
968 rtempvd.getDepthColumn().end());
969 const auto& tempCol = rtempvd.getTemperatureColumn();
970 std::vector<Scalar> temps(tempCol.begin(), tempCol.end());
971 // As for the composition tables, a single row is a depth-independent
972 // temperature and the interpolant needs a second sample point.
973 if (tempDepths.size() == 1) {
974 tempDepths.push_back(tempDepths.front() + constantTableSpan);
975 temps.push_back(temps.front());
976 }
977 reg.tempVdTable.setXYContainers(tempDepths, temps);
978 }
979 else {
980 const std::vector<Scalar> tempDepths{Scalar{0}, constantTableSpan};
981 const std::vector<Scalar> temps(tempDepths.size(), tables.rtemp());
982 reg.tempVdTable.setXYContainers(tempDepths, temps);
983 }
984
985 // Vertical extent of the region's cells across all processes.
986 auto span = std::array{std::numeric_limits<Scalar>::max(),
987 std::numeric_limits<Scalar>::lowest()};
988 for (std::size_t cell = 0; cell < cellCenterDepth.size(); ++cell) {
989 if (std::cmp_equal(eqlnum[cell], regionIdx)) {
990 span[0] = std::min(span[0], cellCenterDepth[cell]);
991 span[1] = std::max(span[1], cellCenterDepth[cell]);
992 }
993 }
994 span[0] = comm.min(span[0]);
995 span[1] = comm.max(span[1]);
996 if (span[0] > span[1]) {
997 // No cells anywhere in this region.
998 return reg;
999 }
1000 const Scalar deepestCellDepth = span[1];
1001 if (span[1] - span[0] < minimumSpanExtent) {
1002 span = {span[0] - minimumSpanExtent, span[1] + minimumSpanExtent};
1003 }
1004 reg.span = span;
1005
1006 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
1007 std::vector<unsigned> waterPvtRegions;
1008 if (waterActive) {
1009 reg.zwoc = record.waterOilContactDepth();
1010 if (pvtRegions.size() > 1) {
1011 // Only PVT regions with cells below the contact have water
1012 // columns that can anchor the hydrocarbon there. Include cells
1013 // on all ranks.
1014 std::vector<int> present(pvtRegions.back() + 1, 0);
1015 for (std::size_t cell = 0; cell < cellCenterDepth.size(); ++cell) {
1016 if (std::cmp_equal(eqlnum[cell], regionIdx) &&
1017 cellCenterDepth[cell] > reg.zwoc) {
1018 present[pvtnum[cell]] = 1;
1019 }
1020 }
1021 comm.max(present.data(), static_cast<int>(present.size()));
1022
1023 for (const auto pvtRegion : pvtRegions) {
1024 if (present[pvtRegion] != 0) {
1025 waterPvtRegions.push_back(pvtRegion);
1026 }
1027 }
1028 }
1029 }
1030
1031 // A datum below the water-oil contact states the pressure of the water
1032 // rather than of the hydrocarbon: integrate the water from there and
1033 // hand the hydrocarbon its pressure at the contact. Otherwise the
1034 // hydrocarbon is anchored at the datum and the water follows from the
1035 // contact.
1036 Scalar hcDatum = record.datumDepth();
1037 Scalar hcPressure = record.datumDepthPressure();
1038 const bool datumInWater = waterActive && (record.datumDepth() > reg.zwoc);
1039 // A datum on the water-oil contact is no more a depth the hydrocarbon
1040 // occupies than one below it, so the EOS root follows the fluid just
1041 // above the contact in both cases.
1042 reg.anchoredAtWaterContact = waterActive && (record.datumDepth() >= reg.zwoc);
1043
1044 if (datumInWater) {
1045 // A PVT region confined above the contact has no water zone to
1046 // which the datum applies. Its connate water follows the hydrocarbon
1047 // pressure at the contact instead. With no water-zone cells, retain
1048 // the existing interpretation of the datum for every PVT region.
1049 const auto& datumPvtRegions =
1050 waterPvtRegions.empty() ? reg.pvtRegions : waterPvtRegions;
1051 integrateWaterPressure(reg, datumPvtRegions, span, gravity, numSamplePoints,
1052 record.datumDepth(), record.datumDepthPressure());
1053 hcDatum = reg.zwoc;
1054 hcPressure = waterContactPressure(reg, record.datumDepth(), regionIdx)
1055 + record.waterOilContactCapillaryPressure();
1056 OpmLog::info(fmt::format("Equilibration region {}: the datum at {} m lies below the "
1057 "water-oil contact at {} m, so it gives the water pressure; "
1058 "the hydrocarbon pressure at the contact is {:.5} bar.",
1059 regionIdx + 1, record.datumDepth(), reg.zwoc,
1060 hcPressure / 1.0e5));
1061 }
1062
1063 if (reg.initType == 1) {
1064 setupSinglePhaseRegion(reg, span, gravity, numSamplePoints, regionIdx,
1065 hcDatum, hcPressure);
1066 }
1067 else {
1068 // Type 3 anchors the hydrocarbon at the gas-oil contact on its own
1069 // saturation pressure, so it has no use for a datum that states the
1070 // water pressure: the two columns would not meet at the water-oil
1071 // contact.
1072 if (datumInWater) {
1073 OPM_THROW(std::runtime_error,
1074 fmt::format("Compositional equilibration of region {} places the "
1075 "datum at {} m, below the water-oil contact at {} m, "
1076 "while EQUIL item 10 is 3. Put the datum in the "
1077 "hydrocarbon column or use item 10 = 1.",
1078 regionIdx + 1, record.datumDepth(), reg.zwoc));
1079 }
1080 setupTwoPhaseRegion(reg, record, span, gravity, numSamplePoints, regionIdx);
1081 }
1082
1083 // Anchor any water columns not fixed by the datum at the contact.
1084 if (waterActive) {
1085 setupWaterZone(reg, record, span, gravity, numSamplePoints, regionIdx);
1086 }
1087
1088 if (waterPvtRegions.size() > 1) {
1089 Scalar minPressure = std::numeric_limits<Scalar>::max();
1090 Scalar maxPressure = std::numeric_limits<Scalar>::lowest();
1091 for (const auto pvtRegion : waterPvtRegions) {
1092 const Scalar pressure = reg.waterPressure.at(pvtRegion).value(deepestCellDepth);
1093 minPressure = std::min(minPressure, pressure);
1094 maxPressure = std::max(maxPressure, pressure);
1095 }
1096 const Scalar difference = maxPressure - minPressure;
1097 const Scalar scale = std::max(std::abs(minPressure), std::abs(maxPressure));
1098 if (difference > 1.0e-10 * scale) {
1099 auto displayedRegions = waterPvtRegions;
1100 for (auto& pvtRegion : displayedRegions) {
1101 ++pvtRegion;
1102 }
1103 OpmLog::warning(fmt::format(
1104 "Equilibration region {} has water-zone cells in PVT regions {} "
1105 "with pressures differing by {:.6g} bar at {} m. If those cells "
1106 "connect (including numerical-aquifer NNCs), initial crossflow "
1107 "may occur. Check PVTNUM and initial pressures.",
1108 regionIdx + 1, fmt::join(displayedRegions, ", "),
1109 unit::convert::to(difference, unit::barsa), deepestCellDepth));
1110 }
1111 }
1112
1113 return reg;
1114 }
1115
1119 void setupWaterZone(Region& reg,
1120 const EquilRecord& record,
1121 const std::array<Scalar, 2>& span,
1122 const Scalar gravity,
1123 const int numSamplePoints,
1124 const std::size_t regionIdx) const
1125 {
1126 // The capillary pressure at the contact (EQUIL item 4) offsets the
1127 // water pressure from the hydrocarbon pressure there.
1128 if (!reg.oilPressure.has_value() && !reg.gasPressure.has_value()) {
1129 return;
1130 }
1131 // The water meets the hydrocarbon zone just above its contact: the gas
1132 // zone when the gas-oil contact lies at or below the water-oil contact.
1133 const bool gasAtContact = reg.gasPressure.has_value()
1134 && (!reg.oilPressure.has_value() || (reg.zwoc <= reg.zgoc));
1135 const auto& hcPressure = gasAtContact ? reg.gasPressure : reg.oilPressure;
1136 const Scalar pcow = record.waterOilContactCapillaryPressure();
1137 const Scalar pContact = hcPressure->value(reg.zwoc) - pcow;
1138
1139 integrateWaterPressure(reg, reg.pvtRegions, span, gravity, numSamplePoints,
1140 reg.zwoc, pContact);
1141
1142 OpmLog::info(fmt::format("Equilibration region {}: the water-oil contact "
1143 "is at {} m.", regionIdx + 1, reg.zwoc));
1144 }
1145
1148 void integrateWaterPressure(Region& reg,
1149 const std::vector<unsigned>& pvtRegions,
1150 const std::array<Scalar, 2>& span,
1151 const Scalar gravity,
1152 const int numSamplePoints,
1153 const Scalar depth,
1154 const Scalar pressure) const
1155 {
1156 for (const auto pvtRegion : pvtRegions) {
1157 const WaterODE ode(reg.tempVdTable, reg.eosRegion, pvtRegion, gravity);
1158 reg.waterPressure.try_emplace(pvtRegion, ode,
1159 typename WaterPressFunc::InitCond{depth, pressure},
1160 numSamplePoints, waterContactSpan(reg, span));
1161 }
1162 }
1163
1167 static Scalar waterContactPressure(const Region& reg,
1168 const Scalar datum,
1169 const std::size_t regionIdx)
1170 {
1171 // Waters that differ physically part by more than this round-off
1172 // tolerance between the datum and the contact.
1173 constexpr Scalar samePressure{1.0e-10};
1174
1175 const auto& [firstPvtRegion, firstColumn] = *reg.waterPressure.begin();
1176 const Scalar pressure = firstColumn.value(reg.zwoc);
1177 for (const auto& [pvtRegion, column] : reg.waterPressure) {
1178 const Scalar other = column.value(reg.zwoc);
1179 if (std::abs(other - pressure) > samePressure * pressure) {
1180 OPM_THROW(std::runtime_error,
1181 fmt::format("Equilibration region {} places the datum at {} m, below "
1182 "the water-oil contact at {} m, but the water of its PVT "
1183 "regions {} and {} reaches the contact at {:.6g} and "
1184 "{:.6g} bar. Put the datum in the hydrocarbon column.",
1185 regionIdx + 1, datum, reg.zwoc,
1186 firstPvtRegion + 1, pvtRegion + 1,
1187 unit::convert::to(pressure, unit::barsa),
1188 unit::convert::to(other, unit::barsa)));
1189 }
1190 }
1191 return pressure;
1192 }
1193
1196 static Scalar waterLimit(const std::vector<Scalar>& limits,
1197 const std::size_t cell,
1198 const Scalar fallback)
1199 {
1200 return limits.empty() ? fallback : limits[cell];
1201 }
1202
1217 void setupSinglePhaseRegion(Region& reg,
1218 const std::array<Scalar, 2>& span,
1219 const Scalar gravity,
1220 const int numSamplePoints,
1221 const std::size_t regionIdx,
1222 const Scalar datum,
1223 const Scalar datumPressure) const
1224 {
1225 if (reg.twoZone) {
1226 setupTwoZoneRegion(reg, span, gravity, numSamplePoints, regionIdx,
1227 datum, datumPressure);
1228 return;
1229 }
1230
1231 // COMPVD states the phase its composition belongs to; without that the
1232 // datum's side of the gas-oil contact decides the EOS root. A datum on
1233 // the water-oil contact is not in the hydrocarbon at all, so there the
1234 // gas-oil contact itself still leaves gas above: a column whose two
1235 // contacts coincide holds no liquid.
1236 const bool gasAtDatum = reg.anchoredAtWaterContact ? (datum <= reg.zgoc)
1237 : (datum < reg.zgoc);
1238 const auto phaseIdx = reg.statedPhaseIdx.value_or(
1239 gasAtDatum ? FluidSystem::gasPhaseIdx : FluidSystem::oilPhaseIdx);
1240
1241 // A gas-oil contact inside a single-zone region requires the composition
1242 // to vary across it, so the flash can label the phases correctly. Only
1243 // the hydrocarbon above the water-oil contact needs labelling.
1244 const Scalar hydrocarbonBottom = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)
1245 ? std::min(span[1], reg.zwoc) : span[1];
1246 if ((reg.zgoc > span[0]) && (reg.zgoc < hydrocarbonBottom) &&
1247 !compositionVariesBetween(reg, span[0], reg.zgoc) &&
1248 !compositionVariesBetween(reg, reg.zgoc, hydrocarbonBottom)) {
1249 OpmLog::warning(fmt::format("Equilibration region {}: the gas-oil contact "
1250 "at {} m lies inside a type-1 region, but the "
1251 "composition does not vary across the contact. "
1252 "Compositional variation is required for proper "
1253 "phase labeling.", regionIdx + 1, reg.zgoc));
1254 }
1255
1256 const ODE ode([&reg](const Scalar depth) { return composition(reg, depth); },
1257 reg.tempVdTable, phaseIdx, reg.eosRegion, gravity);
1258 reg.oilPressure.emplace(ode,
1259 typename PressFunc::InitCond{datum, datumPressure},
1260 numSamplePoints, waterContactSpan(reg, span));
1261 reg.nominalPhaseIdx = phaseIdx;
1262
1263 OpmLog::info(fmt::format("Equilibration region {}: pressure integrated with one "
1264 "EOS root and the total composition from {} "
1265 "(EQUIL item 10 = 1).",
1266 regionIdx + 1, reg.compositionKeyword));
1267 }
1268
1272 void setupTwoZoneRegion(Region& reg,
1273 const std::array<Scalar, 2>& span,
1274 const Scalar gravity,
1275 const int numSamplePoints,
1276 const std::size_t regionIdx,
1277 const Scalar datum,
1278 const Scalar datumPressure) const
1279 {
1280 const auto z = [&reg](const Scalar depth) { return composition(reg, depth); };
1281 const ODE liquidOde(z, reg.tempVdTable, FluidSystem::oilPhaseIdx, reg.eosRegion, gravity);
1282 const ODE gasOde(z, reg.tempVdTable, FluidSystem::gasPhaseIdx, reg.eosRegion, gravity);
1283
1284 // The datum-side pressure function must reach the actual contact even
1285 // when it lies outside the cell span, because the other pressure function
1286 // is initialized from its value at the contact.
1287 const auto pressureSpan = waterContactSpan(reg, span);
1288 const std::array<Scalar, 2> datumSpan{std::min(pressureSpan[0], reg.zgoc),
1289 std::max(pressureSpan[1], reg.zgoc)};
1290 if ((reg.zgoc < span[0]) || (reg.zgoc > span[1])) {
1291 OpmLog::warning(fmt::format("Equilibration region {}: the gas zone ends at {} m, "
1292 "outside the cells of the region, so all of them "
1293 "lie in the {} zone.",
1294 regionIdx + 1,
1295 reg.zgoc,
1296 (reg.zgoc < span[0]) ? "liquid" : "gas"));
1297 }
1298
1299 if (datum < reg.zgoc) {
1300 reg.gasPressure.emplace(gasOde,
1301 typename PressFunc::InitCond{datum, datumPressure},
1302 numSamplePoints, datumSpan);
1303 reg.oilPressure.emplace(liquidOde,
1304 typename PressFunc::InitCond{
1305 reg.zgoc, reg.gasPressure->value(reg.zgoc)},
1306 numSamplePoints, pressureSpan);
1307 }
1308 else {
1309 reg.oilPressure.emplace(liquidOde,
1310 typename PressFunc::InitCond{datum, datumPressure},
1311 numSamplePoints, datumSpan);
1312 reg.gasPressure.emplace(gasOde,
1313 typename PressFunc::InitCond{
1314 reg.zgoc, reg.oilPressure->value(reg.zgoc)},
1315 numSamplePoints, pressureSpan);
1316 }
1317
1318 OpmLog::info(fmt::format("Equilibration region {}: COMPVD gives a gas zone above "
1319 "{} m and a liquid one below it "
1320 "(EQUIL item 10 = 1).",
1321 regionIdx + 1,
1322 reg.zgoc));
1323 }
1324
1332 void setupTwoPhaseRegion(Region& reg,
1333 const EquilRecord& record,
1334 const std::array<Scalar, 2>& span,
1335 const Scalar gravity,
1336 const int numSamplePoints,
1337 const std::size_t regionIdx) const
1338 {
1339 const Scalar inputReferenceDepth = record.datumDepth();
1340 if (inputReferenceDepth != reg.zgoc) {
1341 OpmLog::warning(fmt::format("Equilibration region {}: the reference depth {} m "
1342 "does not coincide with the gas-oil contact when "
1343 "EQUIL item 10 is 3; resetting it to the contact "
1344 "depth {} m.",
1345 regionIdx + 1, inputReferenceDepth, reg.zgoc));
1346 }
1347
1348 const CompVec liquid = composition(reg, reg.zgoc);
1349 const Scalar temp = Details::evalDepthTable(reg.tempVdTable, reg.zgoc);
1350 Scalar psat{};
1351 CompVec vapor{};
1352 if (!SaturationPressure<Scalar, FluidSystem>::bubblePressure(liquid, temp, reg.eosRegion,
1353 psat, vapor)) {
1354 OPM_THROW(std::runtime_error,
1355 fmt::format("The saturation pressure calculation at the gas-oil "
1356 "contact of region {} did not converge.", regionIdx + 1));
1357 }
1358 reg.vaporComposition = vapor;
1359
1360 // For type 3, the contact is the reference depth. With item 11
1361 // defaulted, the input pressure must agree with the saturation pressure
1362 // to within one atmosphere and is reset to the computed value otherwise.
1363 // Item 11 = 1 retains the numeric input pressure at the contact regardless
1364 // of that test; the result need not be an equilibrium system in that case.
1365 constexpr Scalar oneAtmosphere = unit::atm;
1366 const Scalar inputPressure = record.datumDepthPressure();
1367 const bool resetToPsat = record.setToSaturationPressure()
1368 && (std::abs(inputPressure - psat) >= oneAtmosphere);
1369 const Scalar referencePressure = resetToPsat ? psat : inputPressure;
1370
1371 OpmLog::info(fmt::format("Equilibration region {}: two phases, liquid composition "
1372 "specified (EQUIL item 10 is 3). The saturation pressure "
1373 "at the gas-oil contact ({} m) is {:.6g} bar.",
1374 regionIdx + 1, reg.zgoc,
1375 unit::convert::to(psat, unit::barsa)));
1376
1377 if (resetToPsat) {
1378 OpmLog::warning(fmt::format("Equilibration region {}: the datum pressure {:.6g} bar "
1379 "differs from the saturation pressure {:.6g} bar at the "
1380 "gas-oil contact by one atmosphere or more; the "
1381 "saturation pressure is used instead.",
1382 regionIdx + 1,
1383 unit::convert::to(inputPressure, unit::barsa),
1384 unit::convert::to(psat, unit::barsa)));
1385 }
1386
1387 const ODE oilOde([&reg](const Scalar depth) { return composition(reg, depth); },
1388 reg.tempVdTable, FluidSystem::oilPhaseIdx, reg.eosRegion, gravity);
1389 reg.oilPressure.emplace(oilOde,
1390 typename PressFunc::InitCond{reg.zgoc, referencePressure},
1391 numSamplePoints, waterContactSpan(reg, span));
1392
1393 const ODE gasOde(gasColumnComposition(reg),
1394 reg.tempVdTable, FluidSystem::gasPhaseIdx, reg.eosRegion, gravity);
1395 reg.gasPressure.emplace(gasOde,
1396 typename PressFunc::InitCond{reg.zgoc, referencePressure},
1397 numSamplePoints, waterContactSpan(reg, span));
1398 }
1399
1405 static bool isInGasZone(const Region& reg, const Scalar depth)
1406 {
1407 if (reg.twoZone && (reg.initType == 1) && (depth <= reg.lastVaporDepth)) {
1408 return true;
1409 }
1410 return ((reg.initType == 3) || reg.twoZone) && (depth < reg.zgoc);
1411 }
1412
1413 Scalar assignCell(FluidState& fs, const Region& reg, const unsigned pvtRegion,
1414 const Scalar depth, const std::size_t cell) const
1415 {
1416 const bool inGasZone = isInGasZone(reg, depth);
1417
1418 const CompVec z = [&reg, depth, inGasZone]() {
1419 // Type 1 takes the total composition on either side of the contact.
1420 if (!inGasZone || (reg.initType == 1)) {
1421 return composition(reg, depth);
1422 }
1423 // Type 3 holds the contact vapour above the contact; a two-zone
1424 // COMPVD table gives the gas zone its own composition versus depth.
1425 return reg.twoZone ? vaporComposition(reg, depth) : reg.vaporComposition;
1426 }();
1427 const auto& pressFunc = inGasZone ? reg.gasPressure : reg.oilPressure;
1428 if (!pressFunc.has_value()) {
1429 OPM_THROW(std::runtime_error,
1430 "Evaluating the equilibrated pressure of a region without cells.");
1431 }
1432
1433 // The common pressure used by the current flash follows the water
1434 // column below the contact, including when the scaled maximum water
1435 // saturation leaves some residual hydrocarbon. Keep this separate from
1436 // the phase pressures so equilibration retains the capillary offset.
1437 const Scalar hydrocarbonPressure = pressFunc->value(depth);
1438 // The water column of the cell's own PVT region.
1439 const auto water = reg.waterPressure.find(pvtRegion);
1440 const WaterPressFunc* waterPressure =
1441 (water != reg.waterPressure.end()) ? &water->second : nullptr;
1442 const bool inWaterZone = (depth > reg.zwoc) && (waterPressure != nullptr);
1443 const Scalar press = inWaterZone ? waterPressure->value(depth)
1444 : hydrocarbonPressure;
1445
1446 fs.setTemperature(Details::evalDepthTable(reg.tempVdTable, depth));
1447 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
1448 if (FluidSystem::phaseIsActive(phaseIdx)) {
1449 fs.setPressure(phaseIdx, hydrocarbonPressure);
1450 fs.setSaturation(phaseIdx, 0.0);
1451 }
1452 }
1453
1454 // Below the water-oil contact the pore space holds water alone; above
1455 // it the hydrocarbon leaves room for the connate water only.
1456 Scalar sWat = 0.0;
1457 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1458 // The saturation function's own endpoints, per cell: below the
1459 // contact the water fills what it can, above it only the connate
1460 // water remains.
1461 sWat = (depth > reg.zwoc) ? waterLimit(maxWater_, cell, Scalar{1})
1462 : waterLimit(connateWater_, cell, Scalar{0});
1463 fs.setSaturation(FluidSystem::waterPhaseIdx, sWat);
1464 if (waterPressure != nullptr) {
1465 fs.setPressure(FluidSystem::waterPhaseIdx, waterPressure->value(depth));
1466 }
1467 }
1468
1469 // Set a nominal single-phase saturation for the hydrocarbon using the
1470 // phase represented by the pressure integration. The downstream flash
1471 // recomputes the phase split from composition, pressure, and temperature.
1472 fs.setSaturation(inGasZone ? FluidSystem::gasPhaseIdx : reg.nominalPhaseIdx,
1473 Scalar{1} - sWat);
1474
1475 for (int c = 0; c < numComponents; ++c) {
1476 fs.setMoleFraction(c, z[c]);
1477 }
1478 return press;
1479 }
1480
1482 static constexpr int numReportDepths{50};
1483
1486 std::optional<std::pair<Scalar, CompVec>> bubblePoint(const Region& reg,
1487 const CompVec& liquid,
1488 const Scalar depth) const
1489 {
1490 Scalar psat{};
1491 CompVec vapour{};
1492 const Scalar temp = Details::evalDepthTable(reg.tempVdTable, depth);
1493 if (!SaturationPressure<Scalar, FluidSystem>::bubblePressure(liquid, temp, reg.eosRegion,
1494 psat, vapour)) {
1495 return std::nullopt;
1496 }
1497 return std::pair{psat, vapour};
1498 }
1499
1500 std::vector<ReportRow> reportRows(const Region& reg, const ReportRegion& where) const
1501 {
1502 // Past a type 3 contact each column carries the composition the report
1503 // gives its phase there: the contact liquid above the contact, and the
1504 // incipient vapour of the liquid below it.
1505 const bool type3 = (reg.initType == 3);
1506 const CompVec contactLiquid = type3 ? composition(reg, reg.zgoc) : CompVec{};
1507 const auto gasZoneComposition = gasColumnComposition(reg);
1508 const typename ODE::CompositionFunction oilComposition =
1509 [&reg, type3, contactLiquid](const Scalar depth) {
1510 return (type3 && isInGasZone(reg, depth)) ? contactLiquid
1511 : composition(reg, depth);
1512 };
1513 const typename ODE::CompositionFunction gasComposition =
1514 [this, &reg, type3, gasZoneComposition](const Scalar depth) -> CompVec {
1515 if (!type3 || isInGasZone(reg, depth)) {
1516 return gasZoneComposition(depth);
1517 }
1518 const auto bubble = bubblePoint(reg, composition(reg, depth), depth);
1519 return bubble.has_value() ? bubble->second : gasZoneComposition(depth);
1520 };
1521 // The columns' hydrostatic gradients, and with unit gravity their densities.
1522 const ODE oilOde(oilComposition, reg.tempVdTable, reg.nominalPhaseIdx, reg.eosRegion,
1523 gravity_);
1524 const ODE oilDensity(oilComposition, reg.tempVdTable, reg.nominalPhaseIdx, reg.eosRegion,
1525 Scalar{1});
1526 const ODE gasOde(gasComposition, reg.tempVdTable, FluidSystem::gasPhaseIdx,
1527 reg.eosRegion, gravity_);
1528 const ODE gasDensity(gasComposition, reg.tempVdTable, FluidSystem::gasPhaseIdx,
1529 reg.eosRegion, Scalar{1});
1530
1531 // Each column starts where the equilibration anchored the one it
1532 // extends, so the zone the cells take from it is integrated alike and
1533 // no step crosses a contact the cells' column does not.
1534 const std::array<Scalar, 2> span{where.top, where.bottom};
1535 const PressFunc oilColumn(oilOde, reg.oilPressure->initialCondition(),
1536 numSamplePoints_, span);
1537 std::optional<PressFunc> gasColumn;
1538 if (reg.gasPressure.has_value()) {
1539 gasColumn.emplace(gasOde, reg.gasPressure->initialCondition(),
1540 numSamplePoints_, span);
1541 }
1542
1543 // The water of the representative PVT region, or of the region's first
1544 // one when that has no column. A fluid system without a water phase
1545 // has no water state to evaluate.
1546 constexpr bool hasWaterPhase = FluidSystem::numPhases > FluidSystem::waterPhaseIdx;
1547 std::optional<WaterPressFunc> waterColumn;
1548 std::optional<WaterODE> waterDensity;
1549 if constexpr (hasWaterPhase) {
1550 auto water = reg.waterPressure.find(where.pvtRegion);
1551 if (water == reg.waterPressure.end()) {
1552 water = reg.waterPressure.begin();
1553 }
1554 if (water != reg.waterPressure.end()) {
1555 const WaterODE waterOde(reg.tempVdTable, reg.eosRegion, water->first, gravity_);
1556 waterColumn.emplace(waterOde, water->second.initialCondition(),
1557 numSamplePoints_, span);
1558 waterDensity.emplace(reg.tempVdTable, reg.eosRegion, water->first, Scalar{1});
1559 }
1560 }
1561
1562 // Rows without hydrocarbon give the total composition only when the
1563 // datum lies in an oil zone under a gas cap, and none otherwise.
1564 const bool totalWithoutHydrocarbon = (reg.statedGoc > where.top)
1565 && (reg.statedGoc <= reg.datum) && (reg.datum < reg.zwoc);
1566
1567 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
1568 std::vector<ReportRow> rows(numReportDepths);
1569 for (int i = 0; i < numReportDepths; ++i) {
1570 auto& row = rows[i];
1571 const Scalar depth = where.top + (where.bottom - where.top) * i / (numReportDepths - 1);
1572 row.depth = depth;
1573
1574 const bool inGasZone = isInGasZone(reg, depth);
1575 row.poil = oilColumn.value(depth);
1576 row.pgas = gasColumn.has_value() ? gasColumn->value(depth) : row.poil;
1577 if constexpr (hasWaterPhase) {
1578 if (waterColumn.has_value()) {
1579 row.pwat = waterColumn->value(depth);
1580 }
1581 }
1582
1583 // All densities are taken at the one pressure that assignCell()
1584 // gives a cell at this depth, as the run starts from that state.
1585 const bool inWaterZone = (depth > reg.zwoc) && waterColumn.has_value();
1586 const Scalar cellPressure = inWaterZone ? row.pwat
1587 : (inGasZone && gasColumn.has_value()) ? row.pgas
1588 : row.poil;
1589 row.deno = oilDensity(depth, cellPressure);
1590 row.deng = gasColumn.has_value() ? gasDensity(depth, cellPressure) : row.deno;
1591 if constexpr (hasWaterPhase) {
1592 if (waterColumn.has_value()) {
1593 row.denw = (*waterDensity)(depth, cellPressure);
1594 }
1595 }
1596
1597 // The nominal saturations that assignCell() gives a cell at this depth.
1598 if (waterActive) {
1599 row.swat = (depth > reg.zwoc) ? where.swu : where.swl;
1600 }
1601 const auto hydrocarbonPhase = inGasZone ? FluidSystem::gasPhaseIdx
1602 : reg.nominalPhaseIdx;
1603 (hydrocarbonPhase == FluidSystem::gasPhaseIdx ? row.sgas : row.soil)
1604 = Scalar{1} - row.swat;
1605
1606 if (reg.statedSaturationPressure.has_value()) {
1607 row.statedPsat = Details::evalDepthTable(*reg.statedSaturationPressure, depth);
1608 }
1609
1610 if (!type3) {
1611 row.oil = row.gas = row.total = composition(reg, depth);
1612 }
1613 else if (inGasZone) {
1614 row.oil = contactLiquid;
1615 row.gas = row.total = gasZoneComposition(depth);
1616 // The contact liquid's bubble point at the temperature of this
1617 // depth; zero, as below, when it does not converge.
1618 if (const auto bubble = bubblePoint(reg, contactLiquid, depth);
1619 bubble.has_value()) {
1620 row.psat = bubble->first;
1621 }
1622 }
1623 else {
1624 row.oil = row.total = composition(reg, depth);
1625 // Reported as zero when the bubble point does not converge.
1626 if (const auto bubble = bubblePoint(reg, row.oil, depth); bubble.has_value()) {
1627 row.psat = bubble->first;
1628 row.gas = bubble->second;
1629 }
1630 }
1631 if ((row.soil + row.sgas == 0) && !totalWithoutHydrocarbon) {
1632 row.total = CompVec{};
1633 }
1634 }
1635 return rows;
1636 }
1637
1638 Scalar gravity_;
1639 int numSamplePoints_;
1643 std::vector<Scalar> connateWater_;
1644 std::vector<Scalar> maxWater_;
1645 std::vector<Region> regions_;
1646 std::vector<FluidState> fluidStates_;
1647 std::vector<Scalar> referencePressures_;
1648 std::vector<int> twoPhaseCheckRegions_;
1649};
1650
1665template <class Scalar, class LiquidFraction>
1666void reportTwoPhaseCells(const std::vector<int>& checkRegions,
1667 const std::vector<Scalar>& cellCenterDepth,
1668 const LiquidFraction& liquidFraction,
1669 const std::size_t numRegions,
1670 const Parallel::Communication& comm)
1671{
1672 // The smallest mole fraction of the smaller phase that is reported. Gas
1673 // just above a saturated gas-oil contact lies slightly below its dew point
1674 // and condenses a trace of liquid well under it.
1675 constexpr Scalar minReportedFraction{1.0e-3};
1676
1677 // Ranges of the depth and of the smaller phase's mole fraction of the split
1678 // cells of each region, over all processes. A range is unaffected by the
1679 // cells that several processes hold.
1680 std::vector<Scalar> shallowest(numRegions, std::numeric_limits<Scalar>::max());
1681 std::vector<Scalar> deepest(numRegions, std::numeric_limits<Scalar>::lowest());
1682 std::vector<Scalar> leastFraction(numRegions, std::numeric_limits<Scalar>::max());
1683 std::vector<Scalar> mostFraction(numRegions, std::numeric_limits<Scalar>::lowest());
1684 for (std::size_t cell = 0; cell < checkRegions.size(); ++cell) {
1685 if (checkRegions[cell] < 0) {
1686 continue;
1687 }
1688 const Scalar liquid = liquidFraction(cell);
1689 const Scalar fraction = std::min(liquid, Scalar{1} - liquid);
1690 // Negated so that a NaN fraction is skipped too.
1691 if (!(fraction >= minReportedFraction)) {
1692 continue;
1693 }
1694 const auto r = static_cast<std::size_t>(checkRegions[cell]);
1695 const Scalar depth = cellCenterDepth[cell];
1696 shallowest[r] = std::min(shallowest[r], depth);
1697 deepest[r] = std::max(deepest[r], depth);
1698 leastFraction[r] = std::min(leastFraction[r], fraction);
1699 mostFraction[r] = std::max(mostFraction[r], fraction);
1700 }
1701 const auto count = static_cast<int>(numRegions);
1702 comm.min(shallowest.data(), count);
1703 comm.max(deepest.data(), count);
1704 comm.min(leastFraction.data(), count);
1705 comm.max(mostFraction.data(), count);
1706
1707 // A single depth needs no range.
1708 const auto depthRange = [](const Scalar top, const Scalar bottom) {
1709 const auto shallow = fmt::format("{:.2f} m", top);
1710 const auto deep = fmt::format("{:.2f} m", bottom);
1711 return (shallow == deep) ? "at " + shallow : "between " + shallow + " and " + deep;
1712 };
1713 for (std::size_t r = 0; r < numRegions; ++r) {
1714 if (shallowest[r] > deepest[r]) {
1715 continue;
1716 }
1717 // A single share needs no range. A share lies between the cut-off and
1718 // one half, so it cannot round to 0% or 100%.
1719 const auto least = fmt::format("{:.3g}%", 100 * leastFraction[r]);
1720 const auto most = fmt::format("{:.3g}%", 100 * mostFraction[r]);
1721 OpmLog::warning(fmt::format("Equilibration region {}: cells {} split into gas and "
1722 "liquid at their initial pressure, with the smaller phase "
1723 "holding {} of the hydrocarbon moles. With EQUIL "
1724 "item 10 = 1, that pressure comes from the density of a "
1725 "single phase, so the gas and liquid in these cells are "
1726 "not in hydrostatic equilibrium and may move up or down "
1727 "once the simulation starts.",
1728 r + 1,
1729 depthRange(shallowest[r], deepest[r]),
1730 (least == most) ? least : least + " to " + most));
1731 }
1732}
1733
1734} // namespace Opm::EQUIL::Comp
1735
1736#endif // OPM_INIT_STATE_EQUIL_COMP_HPP
#define OPM_END_PARALLEL_TRY_CATCH(prefix, comm)
Catch exception and throw in a parallel try-catch clause.
Definition: DeferredLoggingErrorHelpers.hpp:197
#define OPM_BEGIN_PARALLEL_TRY_CATCH()
Macro to setup the try of a parallel try-catch.
Definition: DeferredLoggingErrorHelpers.hpp:160
Composition versus depth report (RPTSOL SOLVD) of the compositional equilibration.
The ODE integrator and phase-pressure function used to solve the hydrostatic equilibrium problem,...
Definition: InitStateEquilComp.hpp:95
Tabulated1DFunction< Scalar > TabulatedFunction
Definition: InitStateEquilComp.hpp:100
EosDensityODE(CompositionFunction composition, const TabulatedFunction &tempVdTable, const unsigned phaseIdx, const unsigned eosRegion, const Scalar normGrav)
Definition: InitStateEquilComp.hpp:102
Scalar operator()(const Scalar depth, const Scalar press) const
Definition: InitStateEquilComp.hpp:114
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:97
std::array< Scalar, FluidSystem::numComponents > CompVec
Definition: InitStateEquilComp.hpp:98
std::function< CompVec(Scalar)> CompositionFunction
Definition: InitStateEquilComp.hpp:99
Definition: InitStateEquilComp.hpp:146
Scalar operator()(const Scalar depth, const Scalar press) const
Definition: InitStateEquilComp.hpp:161
WaterDensityODE(const TabulatedFunction &tempVdTable, const unsigned eosRegion, const unsigned pvtRegion, const Scalar normGrav)
Definition: InitStateEquilComp.hpp:151
Tabulated1DFunction< Scalar > TabulatedFunction
Definition: InitStateEquilComp.hpp:149
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:148
Computes the initial state of a compositional model from hydrostatic equilibrium (the EQUIL and ZMFVD...
Definition: InitStateEquilComp.hpp:243
std::vector< std::vector< ReportRow > > compositionVersusDepth(const std::vector< ReportRegion > &regions) const
Definition: InitStateEquilComp.hpp:443
CompositionalFluidState< Scalar, FluidSystem > FluidState
Definition: InitStateEquilComp.hpp:246
std::vector< int > & twoPhaseCheckRegions()
Definition: InitStateEquilComp.hpp:389
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:245
const std::vector< int > & twoPhaseCheckRegions() const
Definition: InitStateEquilComp.hpp:392
const std::vector< Scalar > & referencePressures() const
Definition: InitStateEquilComp.hpp:382
const std::vector< FluidState > & fluidStates() const
Definition: InitStateEquilComp.hpp:376
std::vector< FluidState > & fluidStates()
Definition: InitStateEquilComp.hpp:373
InitialStateComputer(const EclipseState &inputState, const std::vector< int > &eosnum, const std::vector< Scalar > &cellCenterDepth, const std::vector< int > &eqlnum, const std::vector< int > &pvtnum, const Parallel::Communication &comm, const Scalar gravity, const int numSamplePoints, const std::vector< Scalar > &connateWater={}, const std::vector< Scalar > &maxWater={})
Definition: InitStateEquilComp.hpp:263
Definition: PressureFunction.hpp:128
Scalar evalDepthTable(const Tabulated1DFunction< Scalar > &table, const Scalar depth)
Definition: InitStateEquilComp.hpp:84
Definition: EquilCompReport.hpp:46
void reportTwoPhaseCells(const std::vector< int > &checkRegions, const std::vector< Scalar > &cellCenterDepth, const LiquidFraction &liquidFraction, const std::size_t numRegions, const Parallel::Communication &comm)
Definition: InitStateEquilComp.hpp:1666
Scalar cellCenterDepth(const Element &element)
Definition: InitStateEquil_impl.hpp:134
Dune::Communication< MPIComm > Communication
Definition: ParallelCommunication.hpp:30
Phase
Phase indices for reservoir coupling, we currently only support black-oil phases (oil,...
Definition: ReservoirCoupling.hpp:184
One depth of the composition versus depth report, in SI units.
Definition: EquilCompReport.hpp:51
Definition: InitStateEquilComp.hpp:399
Scalar bottom
Definition: InitStateEquilComp.hpp:401
unsigned pvtRegion
Zero-based PVT region whose water column is reported.
Definition: InitStateEquilComp.hpp:406
Scalar swl
Connate and maximum water saturation of the representative cell.
Definition: InitStateEquilComp.hpp:403
Scalar swu
Definition: InitStateEquilComp.hpp:404
Scalar top
Definition: InitStateEquilComp.hpp:400