diff --git a/CMakeLists_files.cmake b/CMakeLists_files.cmake index 8b7fefec7f3..5b870c1721d 100644 --- a/CMakeLists_files.cmake +++ b/CMakeLists_files.cmake @@ -1034,6 +1034,7 @@ list (APPEND PUBLIC_HEADER_FILES opm/models/ptflash/flashindices.hh opm/models/ptflash/flashintensivequantities.hh opm/models/ptflash/flashlocalresidual.hh + opm/models/ptflash/flashlocalresidualtpfa.hh opm/models/ptflash/flashmodel.hh opm/models/ptflash/flashnewtonmethod.hh opm/models/ptflash/flashparameters.hh @@ -1119,6 +1120,7 @@ list (APPEND PUBLIC_HEADER_FILES opm/simulators/flow/FacePropertiesTPSA_impl.hpp opm/simulators/flow/FemCpGridCompat.hpp opm/simulators/flow/FIBlackoilModel.hpp + opm/simulators/flow/FICompositionalModel.hpp opm/simulators/flow/GpuFlowProblem.hpp opm/simulators/flow/SimpleFIBlackOilModel.hpp opm/simulators/flow/FIPContainer.hpp diff --git a/flowexperimental/comp/flow_comp.hpp b/flowexperimental/comp/flow_comp.hpp index 7140412460c..a28cb70d87e 100644 --- a/flowexperimental/comp/flow_comp.hpp +++ b/flowexperimental/comp/flow_comp.hpp @@ -23,10 +23,13 @@ #include #include +#include #include +#include #include #include +#include #include #include #include @@ -163,6 +166,27 @@ template struct FluxModule> { using type = NewTranFluxModule; }; +template +struct Model> +{ using type = FICompositionalModel; }; + +template +struct Linearizer> +{ using type = TpfaLinearizer; }; + +template +struct LocalResidual> +{ using type = FlashLocalResidualTPFA; }; + +//! The TPFA linearizer assembles total rates, not rates per unit volume +template +struct UseVolumetricResidual> +{ static constexpr bool value = false; }; + +template +struct RunAssemblyOnGpu> +{ static constexpr bool value = false; }; + template struct FlashSolver> { private: diff --git a/flowexperimental/comp/wells/CompWellInterface.hpp b/flowexperimental/comp/wells/CompWellInterface.hpp index a60d3c9ae7b..d2129252ab4 100644 --- a/flowexperimental/comp/wells/CompWellInterface.hpp +++ b/flowexperimental/comp/wells/CompWellInterface.hpp @@ -69,6 +69,8 @@ class CompWellInterface const std::vector& cells() const { return well_cells_; } + const std::vector& connectionRates() const { return connectionRates_; } + virtual void apply(BVector& r) const = 0; /// Ax = Ax - C^T D^-1 B x, the well part of the reservoir operator diff --git a/flowexperimental/comp/wells/CompWellModel.hpp b/flowexperimental/comp/wells/CompWellModel.hpp index 78fef24d820..55e706fd4c5 100644 --- a/flowexperimental/comp/wells/CompWellModel.hpp +++ b/flowexperimental/comp/wells/CompWellModel.hpp @@ -133,6 +133,12 @@ class CompWellModel : public WellConnectionAuxiliaryModule& + diagMatAddress) const; // [[nodiscard]] data::Wells wellData() const; diff --git a/flowexperimental/comp/wells/CompWellModel_impl.hpp b/flowexperimental/comp/wells/CompWellModel_impl.hpp index 35691f788f3..9b59f6ecfa9 100644 --- a/flowexperimental/comp/wells/CompWellModel_impl.hpp +++ b/flowexperimental/comp/wells/CompWellModel_impl.hpp @@ -374,15 +374,7 @@ void CompWellModel:: beginIteration() { - // do we need to do every iteration here? - const auto& grid = simulator_.vanguard().grid(); - const auto& gridView = grid.leafGridView(); - ElementContext elemCtx(simulator_); - for (const auto& elem : elements(gridView, Dune::Partitions::interior)) { - elemCtx.updatePrimaryStencil(elem); - elemCtx.updatePrimaryIntensiveQuantities(/*timeIdx=*/0); - } - + // The model has updated the cached intensive quantities, which the wells read. assemble(simulator_.timeStepSize()); } @@ -429,6 +421,31 @@ computeTotalRatesForDof(RateVector& rate, } } +template +void +CompWellModel:: +addReservoirSourceTerms(GlobalEqVector& residual, + const std::vector& + diagMatAddress) const +{ + // Not parallelised with OpenMP: a cell perforated by several wells would be + // written by more than one thread. + for (const auto& well : well_container_) { + const auto& cells = well->cells(); + const auto& rates = well->connectionRates(); + for (std::size_t con = 0; con < rates.size(); ++con) { + const auto cellIdx = cells[con]; + auto rate = rates[con]; + rate *= -1.0; + VectorBlockType res(0.0); + typename SparseMatrixAdapter::MatrixBlock bMat(0.0); + simulator_.model().linearizer().setResAndJacobi(res, bMat, rate); + residual[cellIdx] += res; + *diagMatAddress[cellIdx] += bMat; + } + } +} + template void CompWellModel:: diff --git a/opm/models/discretization/common/tpfalinearizer.hh b/opm/models/discretization/common/tpfalinearizer.hh index 1c9c9eea62a..998de89357c 100644 --- a/opm/models/discretization/common/tpfalinearizer.hh +++ b/opm/models/discretization/common/tpfalinearizer.hh @@ -587,7 +587,7 @@ private: const auto& exFluidState = problem_().boundaryFluidState(myIdx, dir_id); BoundaryConditionDataCPU bcdata {type, massrate, - exFluidState.pvtRegionIndex(), + problem_().pvtRegionIndex(myIdx), bfIndex, bf.area(), bf.integrationPos()[dimWorld - 1], diff --git a/opm/models/ptflash/flashintensivequantities.hh b/opm/models/ptflash/flashintensivequantities.hh index 4c427fea898..fa9617b6244 100644 --- a/opm/models/ptflash/flashintensivequantities.hh +++ b/opm/models/ptflash/flashintensivequantities.hh @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -96,6 +97,8 @@ class FlashIntensiveQuantities using Evaluation = GetPropType; using FluidSystem = GetPropType; using FlashSolver = GetPropType; + using ParameterCache = typename FluidSystem::template ParameterCache; + using Toolbox = MathToolbox; using ComponentVector = Dune::FieldVector; using DimMatrix = Dune::FieldMatrix; @@ -107,6 +110,8 @@ class FlashIntensiveQuantities public: //! The type of the object returned by the fluidState() method using FluidState = CompositionalFluidState; + //! Fluid state without derivatives, e.g. for boundary conditions + using ScalarFluidState = CompositionalFluidState; /// Minimum overall mole fraction of a component; the flash needs every /// component present. @@ -134,6 +139,82 @@ public: const auto& priVars = elemCtx.primaryVars(dofIdx, timeIdx); const auto& problem = elemCtx.problem(); + // Get initial K and L from storage initially (if enabled), else from the + // previous time step + const auto* hint = elemCtx.thermodynamicHint(dofIdx, timeIdx); + if (!hint && timeIdx == 0) { + hint = elemCtx.thermodynamicHint(dofIdx, 1); + } + + ParameterCache paramCache(problem.getEosType()); + updatePhaseProperties_(problem, priVars, elemCtx.globalSpaceIndex(dofIdx, timeIdx), timeIdx, + hint, problem.pvtRegionIndex(elemCtx, dofIdx, timeIdx), + problem.materialLawParams(elemCtx, dofIdx, timeIdx), paramCache); + + const Scalar rockCompressibility = problem.rockCompressibility(elemCtx, dofIdx, timeIdx); + updatePorosity_(priVars, timeIdx, problem.porosity(elemCtx, dofIdx, timeIdx), + rockCompressibility, + rockCompressibility > 0.0 + ? problem.rockReferencePressure(elemCtx, dofIdx, timeIdx) : 0.0); + + // intrinsic permeability + intrinsicPerm_ = problem.intrinsicPermeability(elemCtx, dofIdx, timeIdx); + + // update the quantities specific for the velocity model + FluxIntensiveQuantities::update_(elemCtx, dofIdx, timeIdx); + + // energy related quantities + EnergyIntensiveQuantities::update_(fluidState_, paramCache, elemCtx, dofIdx, timeIdx); + + // update the diffusion specific quantities of the intensive quantities + DiffusionIntensiveQuantities::update_(fluidState_, paramCache, elemCtx, dofIdx, timeIdx); + } + + /*! + * \brief Update the quantities of a cell from its primary variables, without + * an element context. + */ + template + void update(const Problem& problem, + const PrimaryVariables& priVars, + unsigned globalIdx, + unsigned timeIdx) + { + // the energy and diffusion modules need an element context + static_assert(!enableEnergy); + static_assert(!enableDiffusion); + + this->extrusionFactor_ = problem.extrusionFactor(); + const Scalar T = problem.temperature(globalIdx, timeIdx); + fluidState_.setTemperature(Toolbox::createConstant(T)); + + // No fallback to the previous time step as in the element-context update: + // the element-context cache refresh never provided one. + ParameterCache paramCache(problem.getEosType()); + updatePhaseProperties_(problem, priVars, globalIdx, timeIdx, + problem.model().thermodynamicHint(globalIdx, timeIdx), + problem.pvtRegionIndex(globalIdx), + problem.materialLawParams(globalIdx), paramCache); + + const Scalar rockCompressibility = problem.rockCompressibility(globalIdx); + updatePorosity_(priVars, timeIdx, problem.porosity(globalIdx, timeIdx), rockCompressibility, + rockCompressibility > 0.0 ? problem.rockReferencePressure(globalIdx) : 0.0); + + intrinsicPerm_ = problem.intrinsicPermeability(globalIdx); + } + +private: + // The flash and the phase properties, shared by both update() overloads + template + void updatePhaseProperties_(const Problem& problem, + const PrimaryVariables& priVars, + unsigned globalIdx, + unsigned timeIdx, + const IntensiveQuantities* hint, + unsigned pvtRegionIdx, + const MaterialLawParams& materialParams, + ParameterCache& paramCache) + { const Scalar flashTolerance = Parameters::Get>(); const int flashVerbosity = Parameters::Get(); const auto ptFlashMethod = @@ -171,8 +252,6 @@ public: fluidState_.setPressure(phaseIdx, p); } - // Get initial K and L from storage initially (if enabled) - const auto* hint = elemCtx.thermodynamicHint(dofIdx, timeIdx); if (hint) { for (unsigned compIdx = 0; compIdx < numComponents; ++compIdx) { const Evaluation& Ktmp = hint->fluidState().K(compIdx); @@ -181,16 +260,6 @@ public: const Evaluation& Ltmp = hint->fluidState().L(); fluidState_.setLvalue(Ltmp); } - else if (timeIdx == 0 && elemCtx.thermodynamicHint(dofIdx, 1)) { - // checking the storage cache - const auto& hint2 = elemCtx.thermodynamicHint(dofIdx, 1); - for (unsigned compIdx = 0; compIdx < numComponents; ++compIdx) { - const Evaluation& Ktmp = hint2->fluidState().K(compIdx); - fluidState_.setKvalue(compIdx, Ktmp); - } - const Evaluation& Ltmp = hint2->fluidState().L(); - fluidState_.setLvalue(Ltmp); - } else { for (unsigned compIdx = 0; compIdx < numComponents; ++compIdx) { const Evaluation Ktmp = fluidState_.wilsonK_(compIdx); @@ -205,7 +274,7 @@ public: ///////////// if (flashVerbosity >= 1) { OpmLog::debug(fmt::format("Updating the intensive quantities for cell {}", - elemCtx.globalSpaceIndex(dofIdx, timeIdx))); + globalIdx)); } const auto& eos_type = problem.getEosType(); FlashSolver::solve(fluidState_, ptFlashMethod, flashTolerance, eos_type, flashVerbosity); @@ -221,15 +290,14 @@ public: getValue(fluidState_.moleFraction(FluidSystem::gasPhaseIdx, compIdx))); } OpmLog::debug(fmt::format("After the flash for cell {}: liquid fraction = {}\n{}", - elemCtx.globalSpaceIndex(dofIdx, timeIdx), + globalIdx, getValue(fluidState_.L()), phaseCompositions)); } // Update phases - typename FluidSystem::template ParameterCache paramCache(eos_type); // the water properties of the cell's PVT region - paramCache.setPvtRegionIndex(problem.pvtRegionIndex(elemCtx, dofIdx, timeIdx)); + paramCache.setPvtRegionIndex(pvtRegionIdx); paramCache.updatePhase(fluidState_, FluidSystem::oilPhaseIdx); paramCache.updatePhase(fluidState_, FluidSystem::gasPhaseIdx); @@ -285,7 +353,7 @@ public: OpmLog::debug(fmt::format("Flash phase properties for cell {}: " "oil saturation = {}, gas saturation = {}, " "oil molar volume = {}, gas molar volume = {}", - elemCtx.globalSpaceIndex(dofIdx, timeIdx), + globalIdx, getValue(So), getValue(Sg), getValue(Vm_L), @@ -295,7 +363,6 @@ public: ///////////// // Compute rel. perm and viscosity and densities ///////////// - const MaterialLawParams& materialParams = problem.materialLawParams(elemCtx, dofIdx, timeIdx); // calculate relative permeability MaterialLaw::relativePermeabilities(relativePermeability_, @@ -320,35 +387,28 @@ public: const Evaluation& rho = FluidSystem::density(fluidState_, paramCache, phaseIdx); fluidState_.setDensity(phaseIdx, rho); } + } - ///////////// - // Compute the remaining quantities - ///////////// - - // porosity, scaled with the pressure by the rock compressibility of the - // cell's region as in the black-oil model - porosity_ = problem.porosity(elemCtx, dofIdx, timeIdx); - const Scalar rockCompressibility = problem.rockCompressibility(elemCtx, dofIdx, timeIdx); + // porosity, scaled with the pressure by the rock compressibility of the + // cell's region as in the black-oil model + template + void updatePorosity_(const PrimaryVariables& priVars, + unsigned timeIdx, + const Evaluation& referencePorosity, + Scalar rockCompressibility, + Scalar rockRefPressure) + { + porosity_ = referencePorosity; if (rockCompressibility > 0.0) { - const Scalar rockRefPressure = problem.rockReferencePressure(elemCtx, dofIdx, timeIdx); + const Evaluation p = priVars.makeEvaluation(pressure0Idx, timeIdx); const Evaluation x = rockCompressibility * (p - rockRefPressure); porosity_ *= 1.0 + x + 0.5 * x * x; } Valgrind::CheckDefined(porosity_); - - // intrinsic permeability - intrinsicPerm_ = problem.intrinsicPermeability(elemCtx, dofIdx, timeIdx); - - // update the quantities specific for the velocity model - FluxIntensiveQuantities::update_(elemCtx, dofIdx, timeIdx); - - // energy related quantities - EnergyIntensiveQuantities::update_(fluidState_, paramCache, elemCtx, dofIdx, timeIdx); - - // update the diffusion specific quantities of the intensive quantities - DiffusionIntensiveQuantities::update_(fluidState_, paramCache, elemCtx, dofIdx, timeIdx); } +public: + /*! * \copydoc ImmiscibleIntensiveQuantities::fluidState */ diff --git a/opm/models/ptflash/flashlocalresidual.hh b/opm/models/ptflash/flashlocalresidual.hh index 49e034430f8..00a07e2217d 100644 --- a/opm/models/ptflash/flashlocalresidual.hh +++ b/opm/models/ptflash/flashlocalresidual.hh @@ -82,7 +82,15 @@ public: unsigned timeIdx, unsigned phaseIdx) const { - const IntensiveQuantities& intQuants = elemCtx.intensiveQuantities(dofIdx, timeIdx); + addPhaseStorage(storage, elemCtx.intensiveQuantities(dofIdx, timeIdx), phaseIdx); + } + + //! Add the storage term of one phase in a single cell, per unit bulk volume. + template + static void addPhaseStorage(Dune::FieldVector& storage, + const IntensiveQuantities& intQuants, + unsigned phaseIdx) + { const auto& fs = intQuants.fluidState(); // compute water storage term @@ -105,7 +113,7 @@ public: } } - EnergyModule::addPhaseStorage(storage, elemCtx.intensiveQuantities(dofIdx, timeIdx), phaseIdx); + EnergyModule::addPhaseStorage(storage, intQuants, phaseIdx); } /*! @@ -116,13 +124,21 @@ public: const ElementContext& elemCtx, unsigned dofIdx, unsigned timeIdx) const + { + computeStorage(storage, elemCtx.intensiveQuantities(dofIdx, timeIdx)); + } + + //! Compute the storage term of a single cell, per unit bulk volume. + template + static void computeStorage(Dune::FieldVector& storage, + const IntensiveQuantities& intQuants) { storage = 0; for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) { - addPhaseStorage(storage, elemCtx, dofIdx, timeIdx, phaseIdx); + addPhaseStorage(storage, intQuants, phaseIdx); } - EnergyModule::addSolidEnergyStorage(storage, elemCtx.intensiveQuantities(dofIdx, timeIdx)); + EnergyModule::addSolidEnergyStorage(storage, intQuants); } /*! diff --git a/opm/models/ptflash/flashlocalresidualtpfa.hh b/opm/models/ptflash/flashlocalresidualtpfa.hh new file mode 100644 index 00000000000..254b0f9529b --- /dev/null +++ b/opm/models/ptflash/flashlocalresidualtpfa.hh @@ -0,0 +1,226 @@ +// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +// vi: set et ts=4 sw=4 sts=4: +/* + Copyright 2026, SINTEF Digital + + This file is part of the Open Porous Media project (OPM). + + OPM is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OPM is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OPM. If not, see . + + Consult the COPYING file in the top-level source directory of this + module for the precise wording of the license and the list of + copyright holders. +*/ +/*! + * \file + * + * \copydoc Opm::FlashLocalResidualTPFA + */ +#ifndef OPM_PTFLASH_LOCAL_RESIDUAL_TPFA_HH +#define OPM_PTFLASH_LOCAL_RESIDUAL_TPFA_HH + +#include + +#include +#include + +#include +#include + +#include + +namespace Opm { + +/*! + * \ingroup FlashModel + * + * \brief Local residual of the PT-flash model for the TPFA linearizer. + * + * The TPFA linearizer evaluates the storage, face flux and source terms one + * cell or face at a time, without an element context. The face flux here is + * the same transmissibility-based flux that the element-context assembly + * computes. The element-context versions are still inherited from + * FlashLocalResidual. + */ +template +class FlashLocalResidualTPFA : public FlashLocalResidual +{ + using ParentType = FlashLocalResidual; + + using Evaluation = GetPropType; + using ExtensiveQuantities = GetPropType; + using FluidSystem = GetPropType; + using Indices = GetPropType; + using IntensiveQuantities = GetPropType; + using Problem = GetPropType; + using RateVector = GetPropType; + using Scalar = GetPropType; + + static constexpr unsigned numPhases = getPropValue(); + static constexpr unsigned numComponents = getPropValue(); + static constexpr unsigned conti0EqIdx = Indices::conti0EqIdx; + static constexpr bool waterEnabled = Indices::waterEnabled; + + static_assert(!getPropValue(), + "The TPFA flash residual does not support the energy equation"); + static_assert(!getPropValue(), + "The TPFA flash residual does not support molecular diffusion"); + + using Toolbox = MathToolbox; + +public: + //! Face data. The TPFA linearizer fills it by aggregate initialization, + //! so the members must keep this order. The last five, for heat + //! conduction, diffusion, dispersion and polymer, are unused. + struct ResidualNBInfo + { + double trans; + double faceArea; + double thpresInToEx; + double thpresExToIn; + double dZg; + FaceDir::DirEnum faceDir; + double Vin; + double Vex; + ConditionalStorage inAlpha; + ConditionalStorage outAlpha; + ConditionalStorage diffusivity; + ConditionalStorage dispersivity; + ConditionalStorage dist; + }; + + using ParentType::computeFlux; + using ParentType::computeSource; + + /*! + * \brief Mass flux of each component from the inside to the outside cell, + * per unit face area. + * + * Derivatives are taken with respect to the inside cell only. \p darcy + * receives the volume rate of each phase, indexed by phase. + */ + template + static void computeFlux(RateVectorT& flux, + RateVectorT& darcy, + const unsigned globalIndexIn, + const unsigned globalIndexEx, + const IntensiveQuantities& intQuantsIn, + const IntensiveQuantities& intQuantsEx, + const ResidualNBInfoT& nbInfo, + const ModuleParamsT& moduleParams) + { + flux = 0.0; + darcy = 0.0; + + constexpr unsigned interiorIdx = 0; + constexpr unsigned exteriorIdx = 1; + + // Average the rock compaction multipliers of the two cells, as the + // element-context flux does. + const Evaluation transMult = (intQuantsIn.rockCompTransMultiplier() + + Toolbox::value(intQuantsEx.rockCompTransMultiplier())) / 2; + const Scalar transFactor = -nbInfo.trans / nbInfo.faceArea; + + for (unsigned phaseIdx = 0; phaseIdx < numPhases; ++phaseIdx) { + if (!FluidSystem::phaseIsActive(phaseIdx)) { + continue; + } + + short upIdx = interiorIdx; + short dnIdx = exteriorIdx; + Evaluation pressureDifference; + ExtensiveQuantities::calculatePhasePressureDiff_(upIdx, + dnIdx, + pressureDifference, + intQuantsIn, + intQuantsEx, + phaseIdx, + interiorIdx, + exteriorIdx, + nbInfo.Vin, + nbInfo.Vex, + globalIndexIn, + globalIndexEx, + nbInfo.dZg, + nbInfo.thpresInToEx, + nbInfo.thpresExToIn, + moduleParams); + + const bool upIsIn = static_cast(upIdx) == interiorIdx; + const IntensiveQuantities& up = upIsIn ? intQuantsIn : intQuantsEx; + const auto& fs = up.fluidState(); + + const Evaluation volumeFlux = upIsIn + ? pressureDifference * up.mobility(phaseIdx, nbInfo.faceDir) * transMult * transFactor + : pressureDifference * (Toolbox::value(up.mobility(phaseIdx, nbInfo.faceDir)) * + transMult * transFactor); + darcy[phaseIdx] = volumeFlux.value() * nbInfo.faceArea; + + const Evaluation massFlux = upIsIn + ? fs.density(phaseIdx) * volumeFlux + : Toolbox::value(fs.density(phaseIdx)) * volumeFlux; + + if (waterEnabled && phaseIdx == static_cast(FluidSystem::waterPhaseIdx)) { + flux[conti0EqIdx + numComponents] = massFlux; + continue; + } + + for (unsigned compIdx = 0; compIdx < numComponents; ++compIdx) { + flux[conti0EqIdx + compIdx] += upIsIn + ? massFlux * fs.massFraction(phaseIdx, compIdx) + : massFlux * Toolbox::value(fs.massFraction(phaseIdx, compIdx)); + } + } + } + + //! Source term of a single cell, per unit bulk volume. + static void computeSource(RateVector& source, + const Problem& problem, + const IntensiveQuantities& /*intQuants*/, + const unsigned globalSpaceIdx, + const unsigned timeIdx) + { + problem.source(source, globalSpaceIdx, timeIdx); + } + + //! Source term of a single cell, per unit bulk volume, without the wells. + static void computeSourceDense(RateVector& source, + const Problem& problem, + const IntensiveQuantities& /*intQuants*/, + const unsigned globalSpaceIdx, + const unsigned timeIdx) + { + source = 0.0; + problem.addToSourceDense(source, globalSpaceIdx, timeIdx); + } + + //! Only no-flow boundaries are supported. + template + static void computeBoundaryFlux(RateVectorT& bdyFlux, + const Problem& /*problem*/, + const BoundaryConditionData& bdyInfo, + const IntensiveQuantities& /*insideIntQuants*/, + const unsigned /*globalSpaceIdx*/) + { + if (bdyInfo.type != BCType::NONE) { + throw std::logic_error("Boundary conditions are not supported " + "by the compositional model yet"); + } + bdyFlux = 0.0; + } +}; + +} // namespace Opm + +#endif // OPM_PTFLASH_LOCAL_RESIDUAL_TPFA_HH diff --git a/opm/simulators/flow/FICompositionalModel.hpp b/opm/simulators/flow/FICompositionalModel.hpp new file mode 100644 index 00000000000..c43ffac2815 --- /dev/null +++ b/opm/simulators/flow/FICompositionalModel.hpp @@ -0,0 +1,96 @@ +// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +// vi: set et ts=4 sw=4 sts=4: +/* + Copyright 2026, SINTEF Digital + + This file is part of the Open Porous Media project (OPM). + + OPM is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OPM is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OPM. If not, see . +*/ +/*! + * \file + * + * \copydoc Opm::FICompositionalModel + */ +#ifndef OPM_FI_COMPOSITIONAL_MODEL_HPP +#define OPM_FI_COMPOSITIONAL_MODEL_HPP + +#include +#include + +#include +#include + +namespace Opm { + +/*! + * \brief PT-flash model that updates the cached intensive quantities cell by + * cell, without element contexts. + */ +template +class FICompositionalModel : public FlashModel +{ + using ParentType = FlashModel; + using Simulator = GetPropType; + +public: + explicit FICompositionalModel(Simulator& simulator) + : ParentType(simulator) + {} + + void invalidateAndUpdateIntensiveQuantities(unsigned timeIdx) const + { + if (!this->storeIntensiveQuantities() || + timeIdx >= this->cachedIntensiveQuantityHistorySize()) { + ParentType::invalidateAndUpdateIntensiveQuantities(timeIdx); + return; + } + + this->invalidateIntensiveQuantitiesCache(timeIdx); + + const auto& problem = this->simulator_.problem(); + const auto& solution = this->solution(timeIdx); + const unsigned numDof = this->numGridDof(); + + // An exception must not escape the parallel loop, which would call + // std::terminate(); rethrow it afterwards, so that a failed flash + // chops the time step. + std::mutex exceptionLock; + std::exception_ptr exceptionPtr = nullptr; + + // dynamic scheduling, since the flash costs more in two-phase cells +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic, 64) +#endif + for (unsigned globalIdx = 0; globalIdx < numDof; ++globalIdx) { + try { + this->intensiveQuantityCache_[timeIdx][globalIdx] + .update(problem, solution[globalIdx], globalIdx, timeIdx); + this->setIntensiveQuantitiesCacheEntryValidity(globalIdx, timeIdx, true); + } + catch (...) { + const std::lock_guard lock(exceptionLock); + exceptionPtr = std::current_exception(); + } + } + + if (exceptionPtr) { + std::rethrow_exception(exceptionPtr); + } + } +}; + +} // namespace Opm + +#endif // OPM_FI_COMPOSITIONAL_MODEL_HPP diff --git a/opm/simulators/flow/FlowProblemComp.hpp b/opm/simulators/flow/FlowProblemComp.hpp index 3efbfbf26a6..bf47028d322 100644 --- a/opm/simulators/flow/FlowProblemComp.hpp +++ b/opm/simulators/flow/FlowProblemComp.hpp @@ -52,6 +52,7 @@ #include #include +#include #include #include @@ -68,6 +69,7 @@ #include #include #include +#include #include namespace Opm::Parameters { @@ -196,6 +198,10 @@ class FlowProblemComp : public FlowProblem throw std::runtime_error("Rock compaction (ROCKCOMP) is not supported " "by compositional modeling yet"); } + if (eclState.getSimulationConfig().bcconfig().size() > 0) { + throw std::runtime_error("Boundary conditions (BCCON) are not supported " + "by compositional modeling yet"); + } this->initializeModelProperties_(); // write the static output files (EGRID, INIT) @@ -322,10 +328,20 @@ class FlowProblemComp : public FlowProblem return; values.setNoFlow(); + } - if (this->nonTrivialBoundaryConditions()) { - throw std::logic_error("boundary condition is not supported by compostional modeling yet"); - } + //! Boundary conditions are not supported; finishInit() rejects decks with BCCON. + std::pair + boundaryCondition(const unsigned int /* globalSpaceIdx */, const int /* directionId */) const + { + return { BCType::NONE, RateVector(0.0) }; + } + + typename IntensiveQuantities::ScalarFluidState + boundaryFluidState(unsigned /* globalDofIdx */, const int /* directionId */) const + { + throw std::logic_error("Boundary conditions are not supported " + "by compositional modeling yet"); } /*! diff --git a/opm/simulators/flow/NonlinearSystemCompositional_impl.hpp b/opm/simulators/flow/NonlinearSystemCompositional_impl.hpp index b3dc2211a95..eee43a07819 100644 --- a/opm/simulators/flow/NonlinearSystemCompositional_impl.hpp +++ b/opm/simulators/flow/NonlinearSystemCompositional_impl.hpp @@ -327,6 +327,7 @@ reservoirResidualMetrics() const const auto& constraintsMap = model.linearizer().constraintsMap(); std::vector residualMetrics(numEq, 0.0); + constexpr bool volumetricResidual = getPropValue(); // Ghost-cell residuals may omit fluxes from neighbors beyond the overlap. // Use the owning rank's residual to assess convergence. @@ -341,11 +342,14 @@ reservoirResidualMetrics() const continue; } + // The tolerances apply to rates per unit volume, so divide by the cell + // volume when the residual holds total rates. + const Scalar volume = volumetricResidual ? 1.0 : model.dofTotalVolume(dofIdx); const auto& localResidual = residual[dofIdx]; for (int eqIdx = 0; eqIdx < numEq; ++eqIdx) { residualMetrics[eqIdx] = std::max( residualMetrics[eqIdx], - std::abs(localResidual[eqIdx] * model.eqWeight(dofIdx, eqIdx))); + std::abs(localResidual[eqIdx] / volume * model.eqWeight(dofIdx, eqIdx))); } }