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/Compositional/CompositionalConfig.hpp>
42#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
43#include <opm/input/eclipse/EclipseState/InitConfig/Equil.hpp>
44#include <opm/input/eclipse/EclipseState/Tables/CompvdTable.hpp>
45#include <opm/input/eclipse/EclipseState/Tables/RtempvdTable.hpp>
46#include <opm/input/eclipse/EclipseState/Tables/SwfnTable.hpp>
47#include <opm/input/eclipse/EclipseState/Tables/TableContainer.hpp>
48#include <opm/input/eclipse/EclipseState/Tables/TableManager.hpp>
49#include <opm/input/eclipse/EclipseState/Tables/ZmfvdTable.hpp>
50#include <opm/input/eclipse/Units/Units.hpp>
51
55
56#include <fmt/format.h>
57
58#include <algorithm>
59#include <array>
60#include <cmath>
61#include <cstddef>
62#include <functional>
63#include <iterator>
64#include <limits>
65#include <numeric>
66#include <optional>
67#include <stdexcept>
68#include <string>
69#include <string_view>
70#include <utility>
71#include <vector>
72
73
75
76namespace Details {
77
81template <class Scalar>
82Scalar evalDepthTable(const Tabulated1DFunction<Scalar>& table, const Scalar depth)
83{
84 return table.eval(std::clamp(depth, table.xMin(), table.xMax()));
85}
86
91template <class FluidSystem>
93{
94public:
95 using Scalar = typename FluidSystem::Scalar;
96 using CompVec = std::array<Scalar, FluidSystem::numComponents>;
97 using CompositionFunction = std::function<CompVec(Scalar)>;
98 using TabulatedFunction = Tabulated1DFunction<Scalar>;
99
101 const TabulatedFunction& tempVdTable,
102 const unsigned phaseIdx,
103 const CompositionalConfig::EOSType eosType,
104 const Scalar normGrav)
105 : composition_(std::move(composition))
106 , tempVdTable_(tempVdTable)
107 , phaseIdx_(phaseIdx)
108 , eosType_(eosType)
109 , g_(normGrav)
110 {}
111
113 const Scalar press) const
114 {
115 const CompVec z = composition_(depth);
116 const Scalar temp = evalDepthTable(tempVdTable_, depth);
117
118 CompositionalFluidState<Scalar, FluidSystem> fs;
119 fs.setTemperature(temp);
120 fs.setPressure(FluidSystem::oilPhaseIdx, press);
121 fs.setPressure(FluidSystem::gasPhaseIdx, press);
122 for (unsigned compIdx = 0; compIdx < FluidSystem::numComponents; ++compIdx) {
123 fs.setMoleFraction(phaseIdx_, compIdx, z[compIdx]);
124 }
125
126 typename FluidSystem::template ParameterCache<Scalar> paramCache(eosType_);
127 paramCache.updatePhase(fs, phaseIdx_);
128
129 return FluidSystem::density(fs, paramCache, phaseIdx_) * g_;
130 }
131
132private:
133 CompositionFunction composition_;
134 const TabulatedFunction& tempVdTable_;
135 unsigned phaseIdx_;
136 CompositionalConfig::EOSType eosType_;
137 Scalar g_;
138};
139
142template <class FluidSystem>
144{
145public:
146 using Scalar = typename FluidSystem::Scalar;
147 using TabulatedFunction = Tabulated1DFunction<Scalar>;
148
150 const CompositionalConfig::EOSType eosType,
151 const Scalar normGrav)
152 : tempVdTable_(tempVdTable)
153 , eosType_(eosType)
154 , g_(normGrav)
155 {}
156
158 const Scalar press) const
159 {
160 CompositionalFluidState<Scalar, FluidSystem> fs;
161 fs.setTemperature(evalDepthTable(tempVdTable_, depth));
162 fs.setPressure(FluidSystem::waterPhaseIdx, press);
163
164 typename FluidSystem::template ParameterCache<Scalar> paramCache(eosType_);
165
166 return FluidSystem::density(fs, paramCache, FluidSystem::waterPhaseIdx) * g_;
167 }
168
169private:
170 const TabulatedFunction& tempVdTable_;
171 CompositionalConfig::EOSType eosType_;
172 Scalar g_;
173};
174
175} // namespace Details
176
210template <class FluidSystem>
212{
213public:
214 using Scalar = typename FluidSystem::Scalar;
215 using FluidState = CompositionalFluidState<Scalar, FluidSystem>;
216
229 InitialStateComputer(const EclipseState& inputState,
230 const CompositionalConfig::EOSType eosType,
231 const std::vector<Scalar>& cellCenterDepth,
232 const std::vector<int>& eqlnum,
233 const Parallel::Communication& comm,
234 const Scalar gravity,
235 const int numSamplePoints,
236 const std::vector<Scalar>& connateWater = {},
237 const std::vector<Scalar>& maxWater = {})
238 : eosType_(eosType)
239 , connateWater_(connateWater)
240 , maxWater_(maxWater)
241 {
242 const auto& records = inputState.getInitConfig().getEquil();
243 const auto& tables = inputState.getTableManager();
244
245 if (!tables.hasTables("ZMFVD") && !tables.hasTables("COMPVD")) {
246 OPM_THROW(std::runtime_error,
247 "Equilibration of a compositional model requires the composition "
248 "versus depth from the ZMFVD or the COMPVD keyword.");
249 }
250
252 if (eqlnum.size() != cellCenterDepth.size()) {
253 OPM_THROW(std::runtime_error,
254 fmt::format("EQLNUM contains {} entries for {} cell depths.",
255 eqlnum.size(), cellCenterDepth.size()));
256 }
257 for (std::size_t cell = 0; cell < eqlnum.size(); ++cell) {
258 const auto region = eqlnum[cell];
259 if (region < 0 || std::cmp_greater_equal(region, records.size())) {
260 OPM_THROW(std::runtime_error,
261 fmt::format("Cell {} has EQLNUM {} outside the {} "
262 "equilibration regions.",
263 cell, region + 1, records.size()));
264 }
265 }
266 // The endpoint vectors are optional, but a non-empty one is indexed for
267 // every cell.
268 for (const auto& [name, limits] : {std::pair{"connate water", std::cref(connateWater)},
269 std::pair{"maximum water", std::cref(maxWater)}}) {
270 if (!limits.get().empty() &&
271 (limits.get().size() != cellCenterDepth.size())) {
272 OPM_THROW(std::runtime_error,
273 fmt::format("The {} saturation has {} entries for {} cell depths.",
274 name, limits.get().size(), cellCenterDepth.size()));
275 }
276 }
277 OPM_END_PARALLEL_TRY_CATCH("Invalid equilibration input: ", comm);
278
279 std::vector<Region> regions;
280 regions.reserve(records.size());
281 for (std::size_t r = 0; r < records.size(); ++r) {
282 regions.push_back(setupRegion(records.getRecord(r), tables, cellCenterDepth,
283 eqlnum, comm, gravity, numSamplePoints, r));
284 }
285
286 fluidStates_.resize(cellCenterDepth.size());
287 referencePressures_.resize(cellCenterDepth.size());
288 for (std::size_t cell = 0; cell < cellCenterDepth.size(); ++cell) {
289 referencePressures_[cell] =
290 assignCell(fluidStates_[cell], regions[eqlnum[cell]], cellCenterDepth[cell], cell);
291 }
292 }
293
294 std::vector<FluidState>& fluidStates()
295 { return fluidStates_; }
296
297 const std::vector<FluidState>& fluidStates() const
298 { return fluidStates_; }
299
303 const std::vector<Scalar>& referencePressures() const
304 { return referencePressures_; }
305
306private:
307 using CompVec = std::array<Scalar, FluidSystem::numComponents>;
308 using TabulatedFunction = Tabulated1DFunction<Scalar>;
313
314 static constexpr int numComponents = FluidSystem::numComponents;
315
319 static constexpr Scalar constantTableSpan{1.0};
320
323 static constexpr Scalar minimumSpanExtent{1.0};
324
326 struct Region {
327 int initType{1}; // EQUIL item 10
328 Scalar zgoc{};
330 std::string_view compositionKeyword;
332 std::optional<unsigned> statedPhaseIdx{};
334 unsigned nominalPhaseIdx{FluidSystem::oilPhaseIdx};
337 bool twoZone{false};
339 std::vector<TabulatedFunction> vaporVdTable;
341 CompVec vaporComposition{};
344 std::vector<TabulatedFunction> compositionVdTable;
345 TabulatedFunction tempVdTable;
346 std::optional<PressFunc> oilPressure;
347 std::optional<PressFunc> gasPressure; // two zones, or type 3
348
349 Scalar zwoc{}; // water-oil contact
353 bool anchoredAtWaterContact{false};
354 std::optional<WaterPressFunc> waterPressure;
355 };
356
359 static std::array<Scalar, 2> waterContactSpan(const Region& reg,
360 const std::array<Scalar, 2>& span)
361 {
362 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
363 return {std::min(span[0], reg.zwoc), std::max(span[1], reg.zwoc)};
364 }
365 return span;
366 }
367
369 static CompVec vaporComposition(const Region& reg, const Scalar depth)
370 {
371 CompVec z{};
372 Scalar sum = 0.0;
373 for (int c = 0; c < numComponents; ++c) {
374 z[c] = std::max(Scalar{0}, Details::evalDepthTable(reg.vaporVdTable[c], depth));
375 sum += z[c];
376 }
377 if (!(sum > 0.0)) {
378 OPM_THROW(std::runtime_error,
379 fmt::format("The COMPVD vapour composition vanishes at depth {} m.", depth));
380 }
381 std::ranges::transform(z, z.begin(), [sum](const Scalar zc) { return zc / sum; });
382 return z;
383 }
384
385 static CompVec composition(const Region& reg, const Scalar depth)
386 {
387 CompVec z{};
388 Scalar sum{};
389 for (int c = 0; c < numComponents; ++c) {
390 z[c] = std::max(Scalar{0}, Details::evalDepthTable(reg.compositionVdTable[c], depth));
391 sum += z[c];
392 }
393 if (!(sum > 0.0)) {
394 OPM_THROW(std::runtime_error,
395 fmt::format("The composition vanishes at depth {} m.", depth));
396 }
397 std::ranges::transform(z, z.begin(), [sum](const Scalar zc) { return zc / sum; });
398 return z;
399 }
400
403 template <class Table>
404 static void setupComposition(std::vector<TabulatedFunction>& out,
405 const Table& table,
406 const std::vector<std::size_t>& rows)
407 {
408 const auto& depthCol = table.getDepthColumn();
409
410 std::vector<Scalar> depths;
411 depths.reserve(rows.size() + 1);
412 for (const auto row : rows) {
413 depths.push_back(depthCol[row]);
414 }
415 // A single row means a depth-independent composition; the interpolant
416 // needs two sample points, so duplicate it onto an arbitrary interval.
417 const bool constantComposition = (depths.size() == 1);
418 if (constantComposition) {
419 depths.push_back(depths.front() + constantTableSpan);
420 }
421
422 out.resize(numComponents);
423 for (int c = 0; c < numComponents; ++c) {
424 const auto& col = table.getMoleFractionColumn(c);
425 std::vector<Scalar> values;
426 values.reserve(depths.size());
427 for (const auto row : rows) {
428 values.push_back(col[row]);
429 }
430 if (constantComposition) {
431 values.push_back(values.front());
432 }
433 out[c].setXYContainers(depths, values);
434 }
435 }
436
439 static std::optional<std::size_t> sourceTable(const TableContainer& container,
440 const std::size_t regionIdx)
441 {
442 const auto& byIndex = container.tables();
443 const auto after = byIndex.upper_bound(regionIdx);
444 if (after == byIndex.begin()) {
445 return std::nullopt;
446 }
447 return std::prev(after)->first;
448 }
449
451 static std::vector<std::size_t> allRows(const std::size_t count)
452 {
453 std::vector<std::size_t> rows(count);
454 std::iota(rows.begin(), rows.end(), std::size_t{0});
455 return rows;
456 }
457
460 static void checkZonesStraddleContact(const CompvdTable& compvd,
461 const std::vector<std::size_t>& vaporRows,
462 const std::vector<std::size_t>& liquidRows,
463 const Scalar zgoc,
464 const std::size_t regionIdx)
465 {
466 if (vaporRows.empty() || liquidRows.empty()) {
467 OPM_THROW(std::runtime_error,
468 fmt::format("The COMPVD table of region {} names both phases but has "
469 "no row for one of them.", regionIdx + 1));
470 }
471
472 const auto& depth = compvd.getDepthColumn();
473 if ((depth[vaporRows.back()] > zgoc) || (depth[liquidRows.front()] < zgoc)) {
474 OPM_THROW(std::runtime_error,
475 fmt::format("The COMPVD table of region {} puts its vapour rows down to "
476 "{} m and its liquid rows from {} m, which do not meet at "
477 "the gas-oil contact at {} m.",
478 regionIdx + 1, depth[vaporRows.back()],
479 depth[liquidRows.front()], zgoc));
480 }
481 }
482
484 static std::vector<std::size_t> rowsOfPhase(const CompvdTable& compvd,
485 const CompvdTable::Phase phase)
486 {
487 const auto& flags = compvd.phaseFlags();
488 std::vector<std::size_t> rows;
489 for (std::size_t r = 0; r < flags.size(); ++r) {
490 if (flags[r] == phase) {
491 rows.push_back(r);
492 }
493 }
494 return rows;
495 }
496
499 static std::optional<unsigned> statedPhase(const CompvdTable& compvd,
500 const std::size_t regionIdx)
501 {
502 const auto& flags = compvd.phaseFlags();
503 if (flags.empty()) {
504 return std::nullopt;
505 }
506
507 const auto first = flags.front();
508 if (std::ranges::any_of(flags, [first](const auto f) { return f != first; })) {
509 OpmLog::info(fmt::format("Equilibration region {}: COMPVD names both phases, "
510 "so the composition of each depth decides the phase.",
511 regionIdx + 1));
512 return std::nullopt;
513 }
514
515 return (first == CompvdTable::Phase::Vapor)
516 ? FluidSystem::gasPhaseIdx : FluidSystem::oilPhaseIdx;
517 }
518
520 static bool compositionVariesBetween(const Region& reg,
521 const Scalar depthA,
522 const Scalar depthB)
523 {
524 // Input mole fractions that differ physically across the contact should
525 // exceed this round-off tolerance.
526 constexpr Scalar sameComposition{1.0e-10};
527
528 const CompVec a = composition(reg, depthA);
529 const CompVec b = composition(reg, depthB);
530 return !std::ranges::equal(a, b, [](const Scalar x, const Scalar y) {
531 return std::abs(x - y) <= sameComposition;
532 });
533 }
534
535 Region setupRegion(const EquilRecord& record,
536 const TableManager& tables,
537 const std::vector<Scalar>& cellCenterDepth,
538 const std::vector<int>& eqlnum,
539 const Parallel::Communication& comm,
540 const Scalar gravity,
541 const int numSamplePoints,
542 const std::size_t regionIdx) const
543 {
544 Region reg;
545
546 reg.initType = record.compositionalInitType();
547 if (reg.initType != 1 && reg.initType != 3) {
548 OPM_THROW(std::runtime_error,
549 fmt::format("Compositional initialization type {} (EQUIL item 10) is "
550 "not supported for region {}; only type 1 (total "
551 "composition) and type 3 (liquid composition) are.",
552 reg.initType, regionIdx + 1));
553 }
554
555 if (record.gasOilContactCapillaryPressure() != 0.0) {
556 OPM_THROW(std::runtime_error,
557 fmt::format("Compositional equilibration only supports zero gas-oil "
558 "contact capillary pressure (EQUIL item 6); region {} "
559 "specifies {} bar.",
560 regionIdx + 1,
561 unit::convert::to(record.gasOilContactCapillaryPressure(),
562 unit::barsa)));
563 }
564
565 if (const auto accuracy = record.initializationTargetAccuracy(); accuracy != 0) {
566 OPM_THROW(std::runtime_error,
567 fmt::format("Compositional equilibration only supports cell-centre "
568 "initialization (EQUIL item 9 = 0); region {} specifies {}.",
569 regionIdx + 1, accuracy));
570 }
571
572 reg.zgoc = record.gasOilContactDepth();
573
574 // With one composition keyword, a missing regional record inherits the
575 // nearest preceding record. If both keywords are present, each region
576 // must select one explicitly because inheritance would be ambiguous.
577 const bool deckHasZmfvd = tables.hasTables("ZMFVD");
578 const bool deckHasCompvd = tables.hasTables("COMPVD");
579 const bool statesZmfvd = deckHasZmfvd &&
580 tables.getZmfvdTables().hasTable(regionIdx);
581 const bool statesCompvd = deckHasCompvd &&
582 tables.getCompvdTables().hasTable(regionIdx);
583
584 if (statesZmfvd && statesCompvd) {
585 OPM_THROW(std::runtime_error,
586 fmt::format("Region {} has both a ZMFVD and a COMPVD composition "
587 "versus depth; give only one of them.", regionIdx + 1));
588 }
589
590 std::optional<std::size_t> zmfvdAt;
591 std::optional<std::size_t> compvdAt;
592 if (deckHasZmfvd && deckHasCompvd) {
593 if (!statesZmfvd && !statesCompvd) {
594 OPM_THROW(std::runtime_error,
595 fmt::format("Region {} has neither a ZMFVD nor a COMPVD "
596 "composition versus depth. A deck using both "
597 "keywords has to give every region a record of "
598 "its own, as neither can be inherited.",
599 regionIdx + 1));
600 }
601 (statesZmfvd ? zmfvdAt : compvdAt) = regionIdx;
602 }
603 else if (deckHasZmfvd) {
604 zmfvdAt = sourceTable(tables.getZmfvdTables(), regionIdx);
605 }
606 else if (deckHasCompvd) {
607 compvdAt = sourceTable(tables.getCompvdTables(), regionIdx);
608 }
609
610 if (!zmfvdAt.has_value() && !compvdAt.has_value()) {
611 OPM_THROW(std::runtime_error,
612 fmt::format("Region {} has neither a ZMFVD nor a COMPVD composition "
613 "versus depth.", regionIdx + 1));
614 }
615
616 if (zmfvdAt.has_value()) {
617 reg.compositionKeyword = "ZMFVD";
618 const auto& zmfvd =
619 tables.getZmfvdTables().template getTable<ZmfvdTable>(*zmfvdAt);
620 setupComposition(reg.compositionVdTable, zmfvd,
621 allRows(zmfvd.getDepthColumn().size()));
622 }
623 else {
624 reg.compositionKeyword = "COMPVD";
625 const auto& compvd =
626 tables.getCompvdTables().template getTable<CompvdTable>(*compvdAt);
627 reg.statedPhaseIdx = statedPhase(compvd, regionIdx);
628
629 if (reg.statedPhaseIdx.has_value()) {
630 // One phase named: all rows form one composition profile, and
631 // the phase flag selects its EOS root.
632 if ((reg.initType == 3) &&
633 (*reg.statedPhaseIdx == FluidSystem::gasPhaseIdx)) {
634 OPM_THROW(std::runtime_error,
635 fmt::format("Region {} states a vapour composition in COMPVD "
636 "while EQUIL item 10 is 3, which takes the liquid "
637 "composition at the gas-oil contact.",
638 regionIdx + 1));
639 }
640 setupComposition(reg.compositionVdTable, compvd,
641 allRows(compvd.getDepthColumn().size()));
642 }
643 else {
644 // Both phases named: the vapour rows describe the gas zone and
645 // the liquid rows the one below the contact.
646 const auto vaporRows = rowsOfPhase(compvd, CompvdTable::Phase::Vapor);
647 const auto liquidRows = rowsOfPhase(compvd, CompvdTable::Phase::Liquid);
648 checkZonesStraddleContact(compvd, vaporRows, liquidRows,
649 record.gasOilContactDepth(), regionIdx);
650 reg.twoZone = true;
651 setupComposition(reg.vaporVdTable, compvd, vaporRows);
652 setupComposition(reg.compositionVdTable, compvd, liquidRows);
653 }
654 }
655
656 if (tables.hasTables("RTEMPVD")) {
657 const auto& rtempvd =
658 tables.getRtempvdTables().template getTable<RtempvdTable>(regionIdx);
659 std::vector<Scalar> tempDepths(rtempvd.getDepthColumn().begin(),
660 rtempvd.getDepthColumn().end());
661 const auto& tempCol = rtempvd.getTemperatureColumn();
662 std::vector<Scalar> temps(tempCol.begin(), tempCol.end());
663 // As for the composition tables, a single row is a depth-independent
664 // temperature and the interpolant needs a second sample point.
665 if (tempDepths.size() == 1) {
666 tempDepths.push_back(tempDepths.front() + constantTableSpan);
667 temps.push_back(temps.front());
668 }
669 reg.tempVdTable.setXYContainers(tempDepths, temps);
670 }
671 else {
672 const std::vector<Scalar> tempDepths{Scalar{0}, constantTableSpan};
673 const std::vector<Scalar> temps(tempDepths.size(), tables.rtemp());
674 reg.tempVdTable.setXYContainers(tempDepths, temps);
675 }
676
677 // Vertical extent of the region's cells across all processes.
678 auto span = std::array{std::numeric_limits<Scalar>::max(),
679 std::numeric_limits<Scalar>::lowest()};
680 for (std::size_t cell = 0; cell < cellCenterDepth.size(); ++cell) {
681 if (std::cmp_equal(eqlnum[cell], regionIdx)) {
682 span[0] = std::min(span[0], cellCenterDepth[cell]);
683 span[1] = std::max(span[1], cellCenterDepth[cell]);
684 }
685 }
686 span[0] = comm.min(span[0]);
687 span[1] = comm.max(span[1]);
688 if (span[0] > span[1]) {
689 // No cells anywhere in this region.
690 return reg;
691 }
692 if (span[1] - span[0] < minimumSpanExtent) {
693 span = {span[0] - minimumSpanExtent, span[1] + minimumSpanExtent};
694 }
695
696 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
697 if (waterActive) {
698 reg.zwoc = record.waterOilContactDepth();
699 }
700
701 // A datum below the water-oil contact states the pressure of the water
702 // rather than of the hydrocarbon: integrate the water from there and
703 // hand the hydrocarbon its pressure at the contact. Otherwise the
704 // hydrocarbon is anchored at the datum and the water follows from the
705 // contact.
706 Scalar hcDatum = record.datumDepth();
707 Scalar hcPressure = record.datumDepthPressure();
708 const bool datumInWater = waterActive && (record.datumDepth() > reg.zwoc);
709 // A datum on the water-oil contact is no more a depth the hydrocarbon
710 // occupies than one below it, so the EOS root follows the fluid just
711 // above the contact in both cases.
712 reg.anchoredAtWaterContact = waterActive && (record.datumDepth() >= reg.zwoc);
713
714 if (datumInWater) {
715 integrateWaterPressure(reg, span, gravity, numSamplePoints,
716 record.datumDepth(), record.datumDepthPressure());
717 hcDatum = reg.zwoc;
718 hcPressure = reg.waterPressure->value(reg.zwoc)
719 + record.waterOilContactCapillaryPressure();
720 OpmLog::info(fmt::format("Equilibration region {}: the datum at {} m lies below the "
721 "water-oil contact at {} m, so it gives the water pressure; "
722 "the hydrocarbon pressure at the contact is {:.5} bar.",
723 regionIdx + 1, record.datumDepth(), reg.zwoc,
724 hcPressure / 1.0e5));
725 }
726
727 if (reg.initType == 1) {
728 setupSinglePhaseRegion(reg, span, gravity, numSamplePoints, regionIdx,
729 hcDatum, hcPressure);
730 }
731 else {
732 // Type 3 anchors the hydrocarbon at the gas-oil contact on its own
733 // saturation pressure, so it has no use for a datum that states the
734 // water pressure: the two columns would not meet at the water-oil
735 // contact.
736 if (datumInWater) {
737 OPM_THROW(std::runtime_error,
738 fmt::format("Compositional equilibration of region {} places the "
739 "datum at {} m, below the water-oil contact at {} m, "
740 "while EQUIL item 10 is 3. Put the datum in the "
741 "hydrocarbon column or use item 10 = 1.",
742 regionIdx + 1, record.datumDepth(), reg.zwoc));
743 }
744 setupTwoPhaseRegion(reg, record, span, gravity, numSamplePoints, regionIdx);
745 }
746
747 // With the datum in the hydrocarbon the water follows from the contact.
748 if (waterActive && !datumInWater) {
749 setupWaterZone(reg, record, span, gravity, numSamplePoints, regionIdx);
750 }
751 else if (waterActive) {
752 OpmLog::info(fmt::format("Equilibration region {}: the water-oil contact "
753 "is at {} m.", regionIdx + 1, reg.zwoc));
754 }
755
756 return reg;
757 }
758
765 void setupWaterZone(Region& reg,
766 const EquilRecord& record,
767 const std::array<Scalar, 2>& span,
768 const Scalar gravity,
769 const int numSamplePoints,
770 const std::size_t regionIdx) const
771 {
772 // The capillary pressure at the contact (EQUIL item 4) offsets the
773 // water pressure from the hydrocarbon pressure there.
774 if (!reg.oilPressure.has_value() && !reg.gasPressure.has_value()) {
775 return;
776 }
777 const auto& hcPressure = reg.oilPressure.has_value() ? reg.oilPressure : reg.gasPressure;
778 const Scalar pcow = record.waterOilContactCapillaryPressure();
779 const Scalar pContact = hcPressure->value(reg.zwoc) - pcow;
780
781 integrateWaterPressure(reg, span, gravity, numSamplePoints, reg.zwoc, pContact);
782
783 OpmLog::info(fmt::format("Equilibration region {}: the water-oil contact "
784 "is at {} m.", regionIdx + 1, reg.zwoc));
785 }
786
789 void integrateWaterPressure(Region& reg,
790 const std::array<Scalar, 2>& span,
791 const Scalar gravity,
792 const int numSamplePoints,
793 const Scalar depth,
794 const Scalar pressure) const
795 {
796 const WaterODE ode(reg.tempVdTable, eosType_, gravity);
797 reg.waterPressure.emplace(ode,
798 typename WaterPressFunc::InitCond{depth, pressure},
799 numSamplePoints, waterContactSpan(reg, span));
800 }
801
804 static Scalar waterLimit(const std::vector<Scalar>& limits,
805 const std::size_t cell,
806 const Scalar fallback)
807 {
808 return limits.empty() ? fallback : limits[cell];
809 }
810
825 void setupSinglePhaseRegion(Region& reg,
826 const std::array<Scalar, 2>& span,
827 const Scalar gravity,
828 const int numSamplePoints,
829 const std::size_t regionIdx,
830 const Scalar datum,
831 const Scalar datumPressure) const
832 {
833 if (reg.twoZone) {
834 setupTwoZoneRegion(reg, span, gravity, numSamplePoints, regionIdx,
835 datum, datumPressure);
836 return;
837 }
838
839 // COMPVD states the phase its composition belongs to; without that the
840 // datum's side of the gas-oil contact decides the EOS root. A datum on
841 // the water-oil contact is not in the hydrocarbon at all, so there the
842 // gas-oil contact itself still leaves gas above: a column whose two
843 // contacts coincide holds no liquid.
844 const bool gasAtDatum = reg.anchoredAtWaterContact ? (datum <= reg.zgoc)
845 : (datum < reg.zgoc);
846 const auto phaseIdx = reg.statedPhaseIdx.value_or(
847 gasAtDatum ? FluidSystem::gasPhaseIdx : FluidSystem::oilPhaseIdx);
848
849 // A gas-oil contact inside a single-zone region requires the composition
850 // to vary across it, so the flash can label the phases correctly.
851 if ((reg.zgoc > span[0]) && (reg.zgoc < span[1]) &&
852 !compositionVariesBetween(reg, span[0], reg.zgoc) &&
853 !compositionVariesBetween(reg, reg.zgoc, span[1])) {
854 OpmLog::warning(fmt::format("Equilibration region {}: the gas-oil contact "
855 "at {} m lies inside a type-1 region, but the "
856 "composition does not vary across the contact. "
857 "Compositional variation is required for proper "
858 "phase labeling.", regionIdx + 1, reg.zgoc));
859 }
860
861 const ODE ode([&reg](const Scalar depth) { return composition(reg, depth); },
862 reg.tempVdTable, phaseIdx, eosType_, gravity);
863 reg.oilPressure.emplace(ode,
864 typename PressFunc::InitCond{datum, datumPressure},
865 numSamplePoints, waterContactSpan(reg, span));
866 reg.nominalPhaseIdx = phaseIdx;
867
868 OpmLog::info(fmt::format("Equilibration region {}: pressure integrated with one "
869 "EOS root and the total composition from {} "
870 "(EQUIL item 10 = 1).",
871 regionIdx + 1, reg.compositionKeyword));
872 }
873
877 void setupTwoZoneRegion(Region& reg,
878 const std::array<Scalar, 2>& span,
879 const Scalar gravity,
880 const int numSamplePoints,
881 const std::size_t regionIdx,
882 const Scalar datum,
883 const Scalar datumPressure) const
884 {
885 const ODE liquidOde([&reg](const Scalar depth) { return composition(reg, depth); },
886 reg.tempVdTable, FluidSystem::oilPhaseIdx, eosType_, gravity);
887 const ODE gasOde([&reg](const Scalar depth) { return vaporComposition(reg, depth); },
888 reg.tempVdTable, FluidSystem::gasPhaseIdx, eosType_, gravity);
889
890 // The datum-side pressure function must reach the actual contact even
891 // when it lies outside the cell span, because the other pressure function
892 // is initialized from its value at the contact.
893 const auto pressureSpan = waterContactSpan(reg, span);
894 const std::array<Scalar, 2> datumSpan{std::min(pressureSpan[0], reg.zgoc),
895 std::max(pressureSpan[1], reg.zgoc)};
896 if ((reg.zgoc < span[0]) || (reg.zgoc > span[1])) {
897 OpmLog::warning(fmt::format("Equilibration region {}: the gas-oil contact at {} m "
898 "lies outside the cells of the region, so the COMPVD "
899 "rows of one phase describe no cell.",
900 regionIdx + 1, reg.zgoc));
901 }
902
903 if (datum < reg.zgoc) {
904 reg.gasPressure.emplace(gasOde,
905 typename PressFunc::InitCond{datum, datumPressure},
906 numSamplePoints, datumSpan);
907 reg.oilPressure.emplace(liquidOde,
908 typename PressFunc::InitCond{
909 reg.zgoc, reg.gasPressure->value(reg.zgoc)},
910 numSamplePoints, pressureSpan);
911 }
912 else {
913 reg.oilPressure.emplace(liquidOde,
914 typename PressFunc::InitCond{datum, datumPressure},
915 numSamplePoints, datumSpan);
916 reg.gasPressure.emplace(gasOde,
917 typename PressFunc::InitCond{
918 reg.zgoc, reg.oilPressure->value(reg.zgoc)},
919 numSamplePoints, pressureSpan);
920 }
921
922 OpmLog::info(fmt::format("Equilibration region {}: COMPVD gives a gas zone above the "
923 "contact at {} m and a liquid one below it "
924 "(EQUIL item 10 = 1).", regionIdx + 1, reg.zgoc));
925 }
926
934 void setupTwoPhaseRegion(Region& reg,
935 const EquilRecord& record,
936 const std::array<Scalar, 2>& span,
937 const Scalar gravity,
938 const int numSamplePoints,
939 const std::size_t regionIdx) const
940 {
941 const Scalar inputReferenceDepth = record.datumDepth();
942 if (inputReferenceDepth != reg.zgoc) {
943 OpmLog::warning(fmt::format("Equilibration region {}: the reference depth {} m "
944 "does not coincide with the gas-oil contact when "
945 "EQUIL item 10 is 3; resetting it to the contact "
946 "depth {} m.",
947 regionIdx + 1, inputReferenceDepth, reg.zgoc));
948 }
949
950 const CompVec liquid = composition(reg, reg.zgoc);
951 const Scalar temp = Details::evalDepthTable(reg.tempVdTable, reg.zgoc);
952 Scalar psat{};
953 CompVec vapor{};
954 if (!SaturationPressure<Scalar, FluidSystem>::bubblePressure(liquid, temp, eosType_,
955 psat, vapor)) {
956 OPM_THROW(std::runtime_error,
957 fmt::format("The saturation pressure calculation at the gas-oil "
958 "contact of region {} did not converge.", regionIdx + 1));
959 }
960 reg.vaporComposition = vapor;
961
962 // For type 3, the contact is the reference depth. With item 11
963 // defaulted, the input pressure must agree with the saturation pressure
964 // to within one atmosphere and is reset to the computed value otherwise.
965 // Item 11 = 1 retains the numeric input pressure at the contact regardless
966 // of that test; the result need not be an equilibrium system in that case.
967 constexpr Scalar oneAtmosphere = unit::atm;
968 const Scalar inputPressure = record.datumDepthPressure();
969 const bool resetToPsat = record.setToSaturationPressure()
970 && (std::abs(inputPressure - psat) >= oneAtmosphere);
971 const Scalar referencePressure = resetToPsat ? psat : inputPressure;
972
973 OpmLog::info(fmt::format("Equilibration region {}: two phases, liquid composition "
974 "specified (EQUIL item 10 is 3). The saturation pressure "
975 "at the gas-oil contact ({} m) is {:.6g} bar.",
976 regionIdx + 1, reg.zgoc,
977 unit::convert::to(psat, unit::barsa)));
978
979 if (resetToPsat) {
980 OpmLog::warning(fmt::format("Equilibration region {}: the datum pressure {:.6g} bar "
981 "differs from the saturation pressure {:.6g} bar at the "
982 "gas-oil contact by one atmosphere or more; the "
983 "saturation pressure is used instead.",
984 regionIdx + 1,
985 unit::convert::to(inputPressure, unit::barsa),
986 unit::convert::to(psat, unit::barsa)));
987 }
988
989 const ODE oilOde([&reg](const Scalar depth) { return composition(reg, depth); },
990 reg.tempVdTable, FluidSystem::oilPhaseIdx, eosType_, gravity);
991 reg.oilPressure.emplace(oilOde,
992 typename PressFunc::InitCond{reg.zgoc, referencePressure},
993 numSamplePoints, waterContactSpan(reg, span));
994
995 // Integrate a two-zone gas column with the same depth-dependent
996 // composition assigned to its cells. Otherwise use the equilibrium
997 // vapour composition at the contact throughout the gas column.
998 typename ODE::CompositionFunction gasComposition;
999 if (reg.twoZone) {
1000 gasComposition = [&reg](const Scalar depth) { return vaporComposition(reg, depth); };
1001 }
1002 else {
1003 gasComposition = [vapor](const Scalar) { return vapor; };
1004 }
1005 const ODE gasOde(gasComposition,
1006 reg.tempVdTable, FluidSystem::gasPhaseIdx, eosType_, gravity);
1007 reg.gasPressure.emplace(gasOde,
1008 typename PressFunc::InitCond{reg.zgoc, referencePressure},
1009 numSamplePoints, waterContactSpan(reg, span));
1010 }
1011
1012 Scalar assignCell(FluidState& fs, const Region& reg, const Scalar depth,
1013 const std::size_t cell) const
1014 {
1015 const bool inGasZone = ((reg.initType == 3) || reg.twoZone) && (depth < reg.zgoc);
1016
1017 const CompVec z = [&reg, depth, inGasZone]() {
1018 if (!inGasZone) {
1019 return composition(reg, depth);
1020 }
1021 // Type 3 holds the contact vapour above the contact; a two-zone
1022 // COMPVD table gives the gas zone its own composition versus depth.
1023 return reg.twoZone ? vaporComposition(reg, depth) : reg.vaporComposition;
1024 }();
1025 const auto& pressFunc = inGasZone ? reg.gasPressure : reg.oilPressure;
1026 if (!pressFunc.has_value()) {
1027 OPM_THROW(std::runtime_error,
1028 "Evaluating the equilibrated pressure of a region without cells.");
1029 }
1030
1031 // The common pressure used by the current flash follows the water
1032 // column below the contact, including when the scaled maximum water
1033 // saturation leaves some residual hydrocarbon. Keep this separate from
1034 // the phase pressures so equilibration retains the capillary offset.
1035 const Scalar hydrocarbonPressure = pressFunc->value(depth);
1036 const bool inWaterZone = (depth > reg.zwoc) && reg.waterPressure.has_value();
1037 const Scalar press = inWaterZone ? reg.waterPressure->value(depth)
1038 : hydrocarbonPressure;
1039
1040 fs.setTemperature(Details::evalDepthTable(reg.tempVdTable, depth));
1041 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
1042 if (FluidSystem::phaseIsActive(phaseIdx)) {
1043 fs.setPressure(phaseIdx, hydrocarbonPressure);
1044 fs.setSaturation(phaseIdx, 0.0);
1045 }
1046 }
1047
1048 // Below the water-oil contact the pore space holds water alone; above
1049 // it the hydrocarbon leaves room for the connate water only.
1050 Scalar sWat = 0.0;
1051 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1052 // The saturation function's own endpoints, per cell: below the
1053 // contact the water fills what it can, above it only the connate
1054 // water remains.
1055 sWat = (depth > reg.zwoc) ? waterLimit(maxWater_, cell, Scalar{1})
1056 : waterLimit(connateWater_, cell, Scalar{0});
1057 fs.setSaturation(FluidSystem::waterPhaseIdx, sWat);
1058 if (reg.waterPressure.has_value()) {
1059 fs.setPressure(FluidSystem::waterPhaseIdx, reg.waterPressure->value(depth));
1060 }
1061 }
1062
1063 // Set a nominal single-phase saturation for the hydrocarbon using the
1064 // phase represented by the pressure integration. The downstream flash
1065 // recomputes the phase split from composition, pressure, and temperature.
1066 fs.setSaturation(inGasZone ? FluidSystem::gasPhaseIdx : reg.nominalPhaseIdx,
1067 Scalar{1} - sWat);
1068
1069 for (int c = 0; c < numComponents; ++c) {
1070 fs.setMoleFraction(c, z[c]);
1071 }
1072 return press;
1073 }
1074
1075 CompositionalConfig::EOSType eosType_;
1079 std::vector<Scalar> connateWater_;
1080 std::vector<Scalar> maxWater_;
1081 std::vector<FluidState> fluidStates_;
1082 std::vector<Scalar> referencePressures_;
1083};
1084
1085} // namespace Opm::EQUIL::Comp
1086
1087#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
The ODE integrator and phase-pressure function used to solve the hydrostatic equilibrium problem,...
Definition: InitStateEquilComp.hpp:93
Tabulated1DFunction< Scalar > TabulatedFunction
Definition: InitStateEquilComp.hpp:98
Scalar operator()(const Scalar depth, const Scalar press) const
Definition: InitStateEquilComp.hpp:112
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:95
std::array< Scalar, FluidSystem::numComponents > CompVec
Definition: InitStateEquilComp.hpp:96
std::function< CompVec(Scalar)> CompositionFunction
Definition: InitStateEquilComp.hpp:97
EosDensityODE(CompositionFunction composition, const TabulatedFunction &tempVdTable, const unsigned phaseIdx, const CompositionalConfig::EOSType eosType, const Scalar normGrav)
Definition: InitStateEquilComp.hpp:100
Definition: InitStateEquilComp.hpp:144
Scalar operator()(const Scalar depth, const Scalar press) const
Definition: InitStateEquilComp.hpp:157
WaterDensityODE(const TabulatedFunction &tempVdTable, const CompositionalConfig::EOSType eosType, const Scalar normGrav)
Definition: InitStateEquilComp.hpp:149
Tabulated1DFunction< Scalar > TabulatedFunction
Definition: InitStateEquilComp.hpp:147
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:146
Computes the initial state of a compositional model from hydrostatic equilibrium (the EQUIL and ZMFVD...
Definition: InitStateEquilComp.hpp:212
CompositionalFluidState< Scalar, FluidSystem > FluidState
Definition: InitStateEquilComp.hpp:215
typename FluidSystem::Scalar Scalar
Definition: InitStateEquilComp.hpp:214
const std::vector< Scalar > & referencePressures() const
Definition: InitStateEquilComp.hpp:303
const std::vector< FluidState > & fluidStates() const
Definition: InitStateEquilComp.hpp:297
InitialStateComputer(const EclipseState &inputState, const CompositionalConfig::EOSType eosType, const std::vector< Scalar > &cellCenterDepth, const std::vector< int > &eqlnum, const Parallel::Communication &comm, const Scalar gravity, const int numSamplePoints, const std::vector< Scalar > &connateWater={}, const std::vector< Scalar > &maxWater={})
Definition: InitStateEquilComp.hpp:229
std::vector< FluidState > & fluidStates()
Definition: InitStateEquilComp.hpp:294
Definition: PressureFunction.hpp:128
Scalar evalDepthTable(const Tabulated1DFunction< Scalar > &table, const Scalar depth)
Definition: InitStateEquilComp.hpp:82
Definition: InitStateEquilComp.hpp:74
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:183