StandardWell_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2017 SINTEF Digital, Mathematics and Cybernetics.
3 Copyright 2017 Statoil ASA.
4 Copyright 2016 - 2017 IRIS AS.
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
22#ifndef OPM_STANDARDWELL_IMPL_HEADER_INCLUDED
23#define OPM_STANDARDWELL_IMPL_HEADER_INCLUDED
24
25// Improve IDE experience
26#ifndef OPM_STANDARDWELL_HEADER_INCLUDED
27#include <config.h>
29#endif
30
31#include <opm/common/Exceptions.hpp>
32
33#include <opm/input/eclipse/Units/Units.hpp>
34
40
41#include <algorithm>
42#include <cstddef>
43#include <functional>
44#include <numbers>
45
46#include <fmt/format.h>
47
48namespace Opm
49{
50
51 template<typename TypeTag>
53 StandardWell(const Well& well,
54 const ParallelWellInfo<Scalar>& pw_info,
55 const int time_step,
56 const ModelParameters& param,
57 const RateConverterType& rate_converter,
58 const int pvtRegionIdx,
59 const int num_conservation_quantities,
60 const int num_phases,
61 const int index_of_well,
62 const std::vector<PerforationData<Scalar>>& perf_data)
63 : Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_conservation_quantities, num_phases, index_of_well, perf_data)
64 , StdWellEval(static_cast<const WellInterfaceIndices<FluidSystem,Indices>&>(*this))
65 , regularize_(false)
66 {
68 }
69
70
71
72
73
74 template<typename TypeTag>
75 void
77 init(const std::vector<Scalar>& depth_arg,
78 const Scalar gravity_arg,
79 const std::vector< Scalar >& B_avg,
80 const bool changed_to_open_this_step)
81 {
82 Base::init(depth_arg, gravity_arg, B_avg, changed_to_open_this_step);
83 this->StdWellEval::init(this->perf_depth_, depth_arg, Base::has_polymermw);
84 }
85
86
87
88
89
90 template<typename TypeTag>
91 template<class Value>
92 void
95 const std::vector<Value>& mob,
96 const Value& bhp,
97 const std::vector<Value>& Tw,
98 const int perf,
99 const bool allow_cf,
100 std::vector<Value>& cq_s,
101 PerforationRates<Scalar>& perf_rates,
102 DeferredLogger& deferred_logger) const
103 {
104 auto obtain = [this](const Eval& value)
105 {
106 if constexpr (std::is_same_v<Value, Scalar>) {
107 static_cast<void>(this); // suppress clang warning
108 return getValue(value);
109 } else {
110 return this->extendEval(value);
111 }
112 };
113 auto obtainN = [](const auto& value)
114 {
115 if constexpr (std::is_same_v<Value, Scalar>) {
116 return getValue(value);
117 } else {
118 return value;
119 }
120 };
121 auto zeroElem = [this]()
122 {
123 if constexpr (std::is_same_v<Value, Scalar>) {
124 static_cast<void>(this); // suppress clang warning
125 return 0.0;
126 } else {
127 return Value{this->primary_variables_.numWellEq() + Indices::numEq, 0.0};
128 }
129 };
130
131 const auto& fs = intQuants.fluidState();
132 const Value pressure = obtain(this->getPerfCellPressure(fs));
133 const Value rs = obtain(fs.Rs());
134 const Value rv = obtain(fs.Rv());
135 const Value rvw = obtain(fs.Rvw());
136 const Value rsw = obtain(fs.Rsw());
137
138 std::vector<Value> b_perfcells_dense(this->numConservationQuantities(), zeroElem());
139 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
140 if (!FluidSystem::phaseIsActive(phaseIdx)) {
141 continue;
142 }
143 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
144 b_perfcells_dense[compIdx] = obtain(fs.invB(phaseIdx));
145 }
146 if constexpr (has_solvent) {
147 b_perfcells_dense[Indices::contiSolventEqIdx] = obtain(intQuants.solventInverseFormationVolumeFactor());
148 }
149
150 if constexpr (has_zFraction) {
151 if (this->isInjector()) {
152 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
153 b_perfcells_dense[gasCompIdx] *= (1.0 - this->wsolvent());
154 b_perfcells_dense[gasCompIdx] += this->wsolvent()*intQuants.zPureInvFormationVolumeFactor().value();
155 }
156 }
157
158 Value skin_pressure = zeroElem();
159 if (has_polymermw) {
160 if (this->isInjector()) {
161 const int pskin_index = Bhp + 1 + this->numLocalPerfs() + perf;
162 skin_pressure = obtainN(this->primary_variables_.eval(pskin_index));
163 }
164 }
165
166 // surface volume fraction of fluids within wellbore
167 std::vector<Value> cmix_s(this->numConservationQuantities(), zeroElem());
168 for (int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
169 cmix_s[componentIdx] = obtainN(this->primary_variables_.surfaceVolumeFraction(componentIdx));
170 }
171
172 computePerfRate(mob,
173 pressure,
174 bhp,
175 rs,
176 rv,
177 rvw,
178 rsw,
179 b_perfcells_dense,
180 Tw,
181 perf,
182 allow_cf,
183 skin_pressure,
184 cmix_s,
185 cq_s,
186 perf_rates,
187 deferred_logger);
188 }
189
190
191
192 template<typename TypeTag>
193 template<class Value>
194 void
196 computePerfRate(const std::vector<Value>& mob,
197 const Value& pressure,
198 const Value& bhp,
199 const Value& rs,
200 const Value& rv,
201 const Value& rvw,
202 const Value& rsw,
203 std::vector<Value>& b_perfcells_dense,
204 const std::vector<Value>& Tw,
205 const int perf,
206 const bool allow_cf,
207 const Value& skin_pressure,
208 const std::vector<Value>& cmix_s,
209 std::vector<Value>& cq_s,
210 PerforationRates<Scalar>& perf_rates,
211 DeferredLogger& deferred_logger) const
212 {
213 // Pressure drawdown (also used to determine direction of flow)
214 const Value well_pressure = bhp + this->connections_.pressure_diff(perf);
215 Value drawdown = pressure - well_pressure;
216 if (this->isInjector()) {
217 drawdown += skin_pressure;
218 }
219
220 RatioCalculator<Value> ratioCalc{
221 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)
222 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx)
223 : -1,
224 FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
225 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx)
226 : -1,
227 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)
228 ? FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx)
229 : -1,
230 this->name()
231 };
232
233 // producing perforations
234 if (drawdown > 0) {
235 // Do nothing if crossflow is not allowed
236 if (!allow_cf && this->isInjector()) {
237 return;
238 }
239
240 // compute component volumetric rates at standard conditions
241 for (int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
242 const Value cq_p = - Tw[componentIdx] * (mob[componentIdx] * drawdown);
243 cq_s[componentIdx] = b_perfcells_dense[componentIdx] * cq_p;
244 }
245
246 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
247 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
248 {
249 ratioCalc.gasOilPerfRateProd(cq_s, perf_rates, rv, rs, rvw,
250 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
251 this->isProducer());
252 } else if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) &&
253 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
254 {
255 ratioCalc.gasWaterPerfRateProd(cq_s, perf_rates, rvw, rsw, this->isProducer());
256 }
257 } else {
258 // Do nothing if crossflow is not allowed
259 if (!allow_cf && this->isProducer()) {
260 return;
261 }
262
263 // Using total mobilities
264 Value total_mob_dense = mob[0];
265 for (int componentIdx = 1; componentIdx < this->numConservationQuantities(); ++componentIdx) {
266 total_mob_dense += mob[componentIdx];
267 }
268
269 // compute volume ratio between connection at standard conditions
270 Value volumeRatio = bhp * 0.0; // initialize it with the correct type
271
272 if (FluidSystem::enableVaporizedWater() && FluidSystem::enableDissolvedGasInWater()) {
273 ratioCalc.disOilVapWatVolumeRatio(volumeRatio, rvw, rsw, pressure,
274 cmix_s, b_perfcells_dense, deferred_logger);
275 // DISGASW only supported for gas-water CO2STORE/H2STORE case
276 // and the simulator will throw long before it reach to this point in the code
277 // For blackoil support of DISGASW we need to add the oil component here
278 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
279 assert(FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx));
280 assert(!FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx));
281 } else {
282
283 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
284 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
285 volumeRatio += cmix_s[waterCompIdx] / b_perfcells_dense[waterCompIdx];
286 }
287
288 if constexpr (Indices::enableSolvent) {
289 volumeRatio += cmix_s[Indices::contiSolventEqIdx] / b_perfcells_dense[Indices::contiSolventEqIdx];
290 }
291
292 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
293 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
294 {
295 ratioCalc.gasOilVolumeRatio(volumeRatio, rv, rs, pressure,
296 cmix_s, b_perfcells_dense,
297 deferred_logger);
298 } else {
299 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
300 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
301 volumeRatio += cmix_s[oilCompIdx] / b_perfcells_dense[oilCompIdx];
302 }
303 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
304 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
305 volumeRatio += cmix_s[gasCompIdx] / b_perfcells_dense[gasCompIdx];
306 }
307 }
308 }
309
310 // injecting connections total volumerates at standard conditions
311 for (int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
312 const Value cqt_i = - Tw[componentIdx] * (total_mob_dense * drawdown);
313 Value cqt_is = cqt_i / volumeRatio;
314 cq_s[componentIdx] = cmix_s[componentIdx] * cqt_is;
315 }
316
317 // calculating the perforation solution gas rate and solution oil rates
318 if (this->isProducer()) {
319 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) &&
320 FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx))
321 {
322 ratioCalc.gasOilPerfRateInj(cq_s, perf_rates,
323 rv, rs, pressure, rvw,
324 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx),
325 deferred_logger);
326 }
327 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx) &&
328 FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx))
329 {
330 //no oil
331 ratioCalc.gasWaterPerfRateInj(cq_s, perf_rates, rvw, rsw,
332 pressure, deferred_logger);
333 }
334 }
335 }
336 }
337
338
339 template<typename TypeTag>
340 void
343 const GroupStateHelperType& groupStateHelper,
344 const double dt,
345 const Well::InjectionControls& inj_controls,
346 const Well::ProductionControls& prod_controls,
347 WellStateType& well_state,
348 const bool solving_with_zero_rate)
349 {
350 // TODO: only_wells should be put back to save some computation
351 // for example, the matrices B C does not need to update if only_wells
352 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
353
354 const auto assemble_timer = this->solveAssembleTimer();
355
356 // clear all entries
357 this->linSys_.clear();
358
359 assembleWellEqWithoutIterationImpl(simulator, groupStateHelper, dt, inj_controls,
360 prod_controls, well_state, solving_with_zero_rate);
361 }
362
363
364
365
366 template<typename TypeTag>
367 void
370 const GroupStateHelperType& groupStateHelper,
371 const double dt,
372 const Well::InjectionControls& inj_controls,
373 const Well::ProductionControls& prod_controls,
374 WellStateType& well_state,
375 const bool solving_with_zero_rate)
376 {
377 auto& deferred_logger = groupStateHelper.deferredLogger();
378
379 // try to regularize equation if the well does not converge
380 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
381 const Scalar volume = 0.1 * unit::cubic(unit::feet) * regularization_factor;
382
383 auto& ws = well_state.well(this->index_of_well_);
384 ws.phase_mixing_rates.fill(0.0);
385 if constexpr (has_energy) {
386 ws.energy_rate = 0.0;
387 }
388
389
390 const int np = this->number_of_phases_;
391
392 std::vector<RateVector> connectionRates = this->connectionRates_; // Copy to get right size.
393
394 auto& perf_data = ws.perf_data;
395 auto& perf_rates = perf_data.phase_rates;
396 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
397 // Calculate perforation quantities.
398 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
399 EvalWell water_flux_s{0.0};
400 EvalWell cq_s_zfrac_effective{0.0};
401 calculateSinglePerf(simulator, perf, well_state, connectionRates,
402 cq_s, water_flux_s, cq_s_zfrac_effective, deferred_logger);
403
404 // Equation assembly for this perforation.
405 if constexpr (has_polymer && Base::has_polymermw) {
406 if (this->isInjector()) {
407 handleInjectivityEquations(simulator, well_state, perf,
408 water_flux_s, deferred_logger);
409 }
410 }
411 for (int componentIdx = 0; componentIdx < this->num_conservation_quantities_; ++componentIdx) {
412 // the cq_s entering mass balance equations need to consider the efficiency factors.
413 const EvalWell cq_s_effective = cq_s[componentIdx] * this->well_efficiency_factor_;
414
415 connectionRates[perf][componentIdx] = Base::restrictEval(cq_s_effective);
416
418 assemblePerforationEq(cq_s_effective,
419 componentIdx,
420 perf,
421 this->primary_variables_.numWellEq(),
422 this->linSys_);
423
424 // Store the perforation phase flux for later usage.
425 if (has_solvent && componentIdx == Indices::contiSolventEqIdx) {
426 auto& perf_rate_solvent = perf_data.solvent_rates;
427 perf_rate_solvent[perf] = cq_s[componentIdx].value();
428 } else {
429 perf_rates[perf*np + FluidSystem::activeCompToActivePhaseIdx(componentIdx)] = cq_s[componentIdx].value();
430 }
431 }
432
433 if constexpr (has_zFraction) {
435 assembleZFracEq(cq_s_zfrac_effective,
436 perf,
437 this->primary_variables_.numWellEq(),
438 this->linSys_);
439 }
440 }
441 // Update the connection
442 this->connectionRates_ = connectionRates;
443
444 // Accumulate dissolved gas and vaporized oil flow rates across all
445 // ranks sharing this well (this->index_of_well_).
446 {
447 const auto& comm = this->parallel_well_info_.communication();
448 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
449 }
450
451 // accumulate resWell_ and duneD_ in parallel to get effects of all perforations (might be distributed)
452 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
453
454 // add vol * dF/dt + Q to the well equations;
455 for (int componentIdx = 0; componentIdx < numWellConservationEq; ++componentIdx) {
456 // TODO: following the development in MSW, we need to convert the volume of the wellbore to be surface volume
457 // since all the rates are under surface condition
458 EvalWell resWell_loc(0.0);
459 if (FluidSystem::numActivePhases() > 1) {
460 assert(dt > 0);
461 resWell_loc += (this->primary_variables_.surfaceVolumeFraction(componentIdx) -
462 this->F0_[componentIdx]) * volume / dt;
463 }
464 resWell_loc -= this->primary_variables_.getQs(componentIdx) * this->well_efficiency_factor_;
466 assembleSourceEq(resWell_loc,
467 componentIdx,
468 this->primary_variables_.numWellEq(),
469 this->linSys_);
470 }
471
472 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
473 {
474 // When solving_with_zero_rate=true (called from solveWellWithZeroRate),
475 // we use an empty GroupState to isolate the well from group constraints during assembly.
476 // This allows us to solve the well equations independently of group controls/targets.
477 GroupState<Scalar> empty_group_state;
478 auto& group_state = solving_with_zero_rate
479 ? empty_group_state
480 : groupStateHelper.groupState();
481 // For production wells under group control, ensure feasibility before assembling control equation
482 if (this->wellUnderGroupControl(ws) && this->isProducer() && !stopped_or_zero_target) {
483 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
484 }
485 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
486 auto group_guard = groupStateHelper_copy.pushGroupState(group_state);
488 assembleControlEq(groupStateHelper_copy,
489 inj_controls, prod_controls,
490 this->primary_variables_,
491 this->getRefDensity(),
492 this->linSys_,
493 stopped_or_zero_target);
494 }
495
496 // do the local inversion of D.
497 try {
498 this->linSys_.invert();
499 } catch( ... ) {
500 OPM_DEFLOG_PROBLEM(NumericalProblem, "Error when inverting local well equations for well " + name(), deferred_logger);
501 }
502 }
503
504
505
506
507 template<typename TypeTag>
508 void
510 calculateSinglePerf(const Simulator& simulator,
511 const int perf,
512 WellStateType& well_state,
513 std::vector<RateVector>& connectionRates,
514 std::vector<EvalWell>& cq_s,
515 EvalWell& water_flux_s,
516 EvalWell& cq_s_zfrac_effective,
517 DeferredLogger& deferred_logger) const
518 {
519 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
520 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
521 const int cell_idx = this->well_cells_[perf];
522 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
523 std::vector<EvalWell> mob(this->num_conservation_quantities_, {0.});
524 getMobility(simulator, perf, mob, deferred_logger);
525
526 PerforationRates<Scalar> perf_rates;
527 EvalWell trans_mult(0.0);
528 getTransMult(trans_mult, simulator, cell_idx);
529 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
530 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
531 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
532 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
533 cq_s, perf_rates, deferred_logger);
534
535 auto& ws = well_state.well(this->index_of_well_);
536 auto& perf_data = ws.perf_data;
537 if constexpr (has_polymer && Base::has_polymermw) {
538 if (this->isInjector()) {
539 // Store the original water flux computed from the reservoir quantities.
540 // It will be required to assemble the injectivity equations.
541 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
542 water_flux_s = cq_s[water_comp_idx];
543 // Modify the water flux for the rest of this function to depend directly on the
544 // local water velocity primary variable.
545 handleInjectivityRate(simulator, perf, cq_s);
546 }
547 }
548
549 // updating the solution gas rate and solution oil rate
550 if (this->isProducer()) {
551 ws.phase_mixing_rates[ws.dissolved_gas] += perf_rates.dis_gas;
552 ws.phase_mixing_rates[ws.dissolved_gas_in_water] += perf_rates.dis_gas_in_water;
553 ws.phase_mixing_rates[ws.vaporized_oil] += perf_rates.vap_oil;
554 ws.phase_mixing_rates[ws.vaporized_water] += perf_rates.vap_wat;
555 perf_data.phase_mixing_rates[perf][ws.dissolved_gas] = perf_rates.dis_gas;
556 perf_data.phase_mixing_rates[perf][ws.dissolved_gas_in_water] = perf_rates.dis_gas_in_water;
557 perf_data.phase_mixing_rates[perf][ws.vaporized_oil] = perf_rates.vap_oil;
558 perf_data.phase_mixing_rates[perf][ws.vaporized_water] = perf_rates.vap_wat;
559 }
560
561 if constexpr (has_energy) {
562 connectionRates[perf][Indices::contiEnergyEqIdx] =
563 connectionRateEnergy(cq_s, intQuants, deferred_logger);
564 ws.energy_rate += getValue(connectionRates[perf][Indices::contiEnergyEqIdx]);
565 }
566
567 if constexpr (has_polymer) {
568 std::variant<Scalar,EvalWell> polymerConcentration;
569 if (this->isInjector()) {
570 polymerConcentration = this->wpolymer();
571 } else {
572 polymerConcentration = this->extendEval(intQuants.polymerConcentration() *
573 intQuants.polymerViscosityCorrection());
574 }
575
576 [[maybe_unused]] EvalWell cq_s_poly;
577 std::tie(connectionRates[perf][Indices::contiPolymerEqIdx],
578 cq_s_poly) =
579 this->connections_.connectionRatePolymer(perf_data.polymer_rates[perf],
580 cq_s, polymerConcentration);
581
582 if constexpr (Base::has_polymermw) {
583 updateConnectionRatePolyMW(cq_s_poly, intQuants, well_state,
584 perf, connectionRates, deferred_logger);
585 }
586 }
587
588 if constexpr (has_foam) {
589 std::variant<Scalar,EvalWell> foamConcentration;
590 if (this->isInjector()) {
591 foamConcentration = this->wfoam();
592 } else {
593 foamConcentration = this->extendEval(intQuants.foamConcentration());
594 }
595 connectionRates[perf][Indices::contiFoamEqIdx] =
596 this->connections_.connectionRateFoam(cq_s, foamConcentration,
597 FoamModule::transportPhase(),
598 deferred_logger);
599 }
600
601 if constexpr (has_zFraction) {
602 std::variant<Scalar,std::array<EvalWell,2>> solventConcentration;
603 if (this->isInjector()) {
604 solventConcentration = this->wsolvent();
605 } else {
606 solventConcentration = std::array{this->extendEval(intQuants.xVolume()),
607 this->extendEval(intQuants.yVolume())};
608 }
609 std::tie(connectionRates[perf][Indices::contiZfracEqIdx],
610 cq_s_zfrac_effective) =
611 this->connections_.connectionRatezFraction(perf_data.solvent_rates[perf],
612 perf_rates.dis_gas, cq_s,
613 solventConcentration);
614 }
615
616 if constexpr (has_brine) {
617 std::variant<Scalar,EvalWell> saltConcentration;
618 if (this->isInjector()) {
619 saltConcentration = this->wsalt();
620 } else {
621 saltConcentration = this->extendEval(intQuants.fluidState().saltConcentration());
622 }
623
624 connectionRates[perf][Indices::contiBrineEqIdx] =
625 this->connections_.connectionRateBrine(perf_data.brine_rates[perf],
626 perf_rates.vap_wat, cq_s,
627 saltConcentration);
628 }
629
630 if constexpr (has_bioeffects) {
631 std::variant<Scalar,EvalWell> microbialConcentration;
632 if constexpr (has_micp) {
633 std::variant<Scalar,EvalWell> oxygenConcentration;
634 std::variant<Scalar,EvalWell> ureaConcentration;
635 if (this->isInjector()) {
636 microbialConcentration = this->wmicrobes();
637 oxygenConcentration = this->woxygen();
638 ureaConcentration = this->wurea();
639 } else {
640 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
641 oxygenConcentration = this->extendEval(intQuants.oxygenConcentration());
642 ureaConcentration = this->extendEval(intQuants.ureaConcentration());
643 }
644 std::tie(connectionRates[perf][Indices::contiMicrobialEqIdx],
645 connectionRates[perf][Indices::contiOxygenEqIdx],
646 connectionRates[perf][Indices::contiUreaEqIdx]) =
647 this->connections_.connectionRatesMICP(perf_data.microbial_rates[perf],
648 perf_data.oxygen_rates[perf],
649 perf_data.urea_rates[perf],
650 cq_s,
651 microbialConcentration,
652 oxygenConcentration,
653 ureaConcentration);
654 }
655 else {
656 if (this->isProducer()) {
657 microbialConcentration = this->extendEval(intQuants.microbialConcentration());
658 connectionRates[perf][Indices::contiMicrobialEqIdx] =
659 this->connections_.connectionRateBioeffects(perf_data.microbial_rates[perf],
660 perf_rates.vap_wat, cq_s,
661 microbialConcentration);
662 }
663 }
664 }
665
666 // Store the perforation pressure for later usage.
667 perf_data.pressure[perf] = ws.bhp + this->connections_.pressure_diff(perf);
668
669 // Store the perforation gass mass rate.
670 if (FluidSystem::phaseUsage().hasCO2orH2Store()) {
671 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
672 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::gasPhaseIdx, Base::pvtRegionIdx() );
673 perf_data.gas_mass_rates[perf] = cq_s[gas_comp_idx].value() * rho;
674 }
675
676 // Store the perforation water mass rate.
677 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
678 const unsigned wat_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
679 const Scalar rho = FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() );
680 perf_data.wat_mass_rates[perf] = cq_s[wat_comp_idx].value() * rho;
681 }
682 }
683
684 template<typename TypeTag>
685 template<class Value>
686 void
688 getTransMult(Value& trans_mult,
689 const Simulator& simulator,
690 const int cell_idx) const
691 {
692 auto obtain = [this](const Eval& value)
693 {
694 if constexpr (std::is_same_v<Value, Scalar>) {
695 static_cast<void>(this); // suppress clang warning
696 return getValue(value);
697 } else {
698 return this->extendEval(value);
699 }
700 };
701 WellInterface<TypeTag>::getTransMult(trans_mult, simulator, cell_idx, obtain);
702 }
703
704 template<typename TypeTag>
705 template<class Value>
706 void
708 getMobility(const Simulator& simulator,
709 const int perf,
710 std::vector<Value>& mob,
711 DeferredLogger& deferred_logger) const
712 {
713 auto obtain = [this](const Eval& value)
714 {
715 if constexpr (std::is_same_v<Value, Scalar>) {
716 static_cast<void>(this); // suppress clang warning
717 return getValue(value);
718 } else {
719 return this->extendEval(value);
720 }
721 };
722 WellInterface<TypeTag>::getMobility(simulator, perf, mob,
723 obtain, deferred_logger);
724
725 // modify the water mobility if polymer is present
726 if constexpr (has_polymer) {
727 if (!FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
728 OPM_DEFLOG_THROW(std::runtime_error, "Water is required when polymer is active", deferred_logger);
729 }
730
731 // for the cases related to polymer molecular weight, we assume fully mixing
732 // as a result, the polymer and water share the same viscosity
733 if constexpr (!Base::has_polymermw) {
734 if constexpr (std::is_same_v<Value, Scalar>) {
735 std::vector<EvalWell> mob_eval(this->num_conservation_quantities_, 0.);
736 for (std::size_t i = 0; i < mob.size(); ++i) {
737 mob_eval[i].setValue(mob[i]);
738 }
739 updateWaterMobilityWithPolymer(simulator, perf, mob_eval, deferred_logger);
740 for (std::size_t i = 0; i < mob.size(); ++i) {
741 mob[i] = getValue(mob_eval[i]);
742 }
743 } else {
744 updateWaterMobilityWithPolymer(simulator, perf, mob, deferred_logger);
745 }
746 }
747 }
748
749 // if the injecting well has WINJMULT setup, we update the mobility accordingly
750 if (this->isInjector() && this->well_ecl_.getInjMultMode() != Well::InjMultMode::NONE) {
751 const Scalar bhp = this->primary_variables_.value(Bhp);
752 const Scalar perf_press = bhp + this->connections_.pressure_diff(perf);
753 const Scalar multiplier = this->getInjMult(perf, bhp, perf_press, deferred_logger);
754 for (std::size_t i = 0; i < mob.size(); ++i) {
755 mob[i] *= multiplier;
756 }
757 }
758 }
759
760
761 template<typename TypeTag>
762 void
764 updateWellState(const Simulator& simulator,
765 const BVectorWell& dwells,
766 const GroupStateHelperType& groupStateHelper,
767 WellStateType& well_state)
768 {
769 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
770
771 auto& deferred_logger = groupStateHelper.deferredLogger();
772
773 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
774 updatePrimaryVariablesNewton(dwells, stop_or_zero_rate_target, deferred_logger);
775
776 const auto& summary_state = simulator.vanguard().summaryState();
777 updateWellStateFromPrimaryVariables(well_state, summary_state, deferred_logger);
778
779 // For injectors in a co2 storage case or a thermal case
780 // we convert to reservoir rates using the well bhp and temperature
781 const bool isThermal = simulator.vanguard().eclState().getSimulationConfig().isThermal();
782 const bool co2store = simulator.vanguard().eclState().runspec().co2Storage();
783 Base::calculateReservoirRates( (isThermal || co2store), well_state.well(this->index_of_well_));
784 }
785
786
787
788
789
790 template<typename TypeTag>
791 void
794 const bool stop_or_zero_rate_target,
795 DeferredLogger& deferred_logger)
796 {
797 const Scalar dFLimit = this->param_.dwell_fraction_max_;
798 const Scalar dBHPLimit = this->param_.dbhp_max_rel_;
799 this->primary_variables_.updateNewton(dwells, stop_or_zero_rate_target, dFLimit, dBHPLimit, deferred_logger);
800
801 // for the water velocity and skin pressure
802 if constexpr (Base::has_polymermw) {
803 this->primary_variables_.updateNewtonPolyMW(dwells);
804 }
805
806 this->primary_variables_.checkFinite(deferred_logger, "Newton update");
807 }
808
809
810
811
812
813 template<typename TypeTag>
814 void
817 const SummaryState& summary_state,
818 DeferredLogger& deferred_logger) const
819 {
820 this->primary_variables_.copyToWellState(well_state, deferred_logger);
821
822 WellBhpThpCalculator(this->baseif_).
823 updateThp(getRefDensity(),
824 [this,&well_state]() { return this->baseif_.getALQ(well_state); },
825 well_state, summary_state, deferred_logger);
826
827 // other primary variables related to polymer injectivity study
828 if constexpr (Base::has_polymermw) {
829 this->primary_variables_.copyToWellStatePolyMW(well_state);
830 }
831 }
832
833
834
835
836
837 template<typename TypeTag>
838 void
840 updateIPR(const Simulator& simulator, DeferredLogger& deferred_logger) const
841 {
842 // TODO: not handling solvent related here for now
843
844 // initialize all the values to be zero to begin with
845 std::ranges::fill(this->ipr_a_, 0.0);
846 std::ranges::fill(this->ipr_b_, 0.0);
847
848 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
849 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
850 getMobility(simulator, perf, mob, deferred_logger);
851
852 const int cell_idx = this->well_cells_[perf];
853 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
854 const auto& fs = int_quantities.fluidState();
855 // the pressure of the reservoir grid block the well connection is in
856 Scalar p_r = this->getPerfCellPressure(fs).value();
857
858 // calculating the b for the connection
859 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
860 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
861 if (!FluidSystem::phaseIsActive(phase)) {
862 continue;
863 }
864 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
865 b_perf[comp_idx] = fs.invB(phase).value();
866 }
867 if constexpr (has_solvent) {
868 b_perf[Indices::contiSolventEqIdx] = int_quantities.solventInverseFormationVolumeFactor().value();
869 }
870
871 // the pressure difference between the connection and BHP
872 const Scalar h_perf = this->connections_.pressure_diff(perf);
873 const Scalar pressure_diff = p_r - h_perf;
874
875 // Let us add a check, since the pressure is calculated based on zero value BHP
876 // it should not be negative anyway. If it is negative, we might need to re-formulate
877 // to taking into consideration the crossflow here.
878 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
879 deferred_logger.debug("CROSSFLOW_IPR",
880 "cross flow found when updateIPR for well " + name()
881 + " . The connection is ignored in IPR calculations");
882 // we ignore these connections for now
883 continue;
884 }
885
886 // the well index associated with the connection
887 Scalar trans_mult(0.0);
888 getTransMult(trans_mult, simulator, cell_idx);
889 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
890 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
891 this->getTw(tw_perf, perf, int_quantities, trans_mult, wellstate_nupcol);
892 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
893 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
894 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
895 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
896 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
897 ipr_b_perf[comp_idx] += tw_mob;
898 }
899
900 // we need to handle the rs and rv when both oil and gas are present
901 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
902 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
903 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
904 const Scalar rs = (fs.Rs()).value();
905 const Scalar rv = (fs.Rv()).value();
906
907 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
908 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
909
910 ipr_a_perf[gas_comp_idx] += dis_gas_a;
911 ipr_a_perf[oil_comp_idx] += vap_oil_a;
912
913 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
914 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
915
916 ipr_b_perf[gas_comp_idx] += dis_gas_b;
917 ipr_b_perf[oil_comp_idx] += vap_oil_b;
918 }
919
920 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
921 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
922 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
923 }
924 }
925 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
926 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
927 }
928
929 template<typename TypeTag>
930 void
932 updateIPRImplicit(const Simulator& simulator,
933 const GroupStateHelperType& groupStateHelper,
934 WellStateType& well_state)
935 {
936 auto& deferred_logger = groupStateHelper.deferredLogger();
937 // Compute IPR based on *converged* well-equation:
938 // For a component rate r the derivative dr/dbhp is obtained by
939 // dr/dbhp = - (partial r/partial x) * inv(partial Eq/partial x) * (partial Eq/partial bhp_target)
940 // where Eq(x)=0 is the well equation setup with bhp control and primary variables x
941
942 // We shouldn't have zero rates at this stage, but check
943 bool zero_rates;
944 auto rates = well_state.well(this->index_of_well_).surface_rates;
945 zero_rates = true;
946 for (std::size_t p = 0; p < rates.size(); ++p) {
947 zero_rates &= rates[p] == 0.0;
948 }
949 auto& ws = well_state.well(this->index_of_well_);
950 if (zero_rates) {
951 const auto msg = fmt::format("updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
952 deferred_logger.debug(msg);
953 /*
954 // could revert to standard approach here:
955 updateIPR(simulator, deferred_logger);
956 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
957 const int idx = this->activeCompToActivePhaseIdx(comp_idx);
958 ws.implicit_ipr_a[idx] = this->ipr_a_[comp_idx];
959 ws.implicit_ipr_b[idx] = this->ipr_b_[comp_idx];
960 }
961 return;
962 */
963 }
964
965 std::ranges::fill(ws.implicit_ipr_a, 0.0);
966 std::ranges::fill(ws.implicit_ipr_b, 0.0);
967
968 auto inj_controls = Well::InjectionControls(0);
969 auto prod_controls = Well::ProductionControls(0);
970 prod_controls.addControl(Well::ProducerCMode::BHP);
971 prod_controls.bhp_limit = well_state.well(this->index_of_well_).bhp;
972
973 // Set current control to bhp, and bhp value in state, modify bhp limit in control object.
974 const auto cmode = ws.production_cmode;
975 ws.production_cmode = Well::ProducerCMode::BHP;
976 const double dt = simulator.timeStepSize();
977 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
978 /*solving_with_zero_rate=*/false);
979
980 const size_t nEq = this->primary_variables_.numWellEq();
981 BVectorWell rhs(1);
982 rhs[0].resize(nEq);
983 // rhs = 0 except -1 for control eq
984 for (size_t i=0; i < nEq; ++i){
985 rhs[0][i] = 0.0;
986 }
987 rhs[0][Bhp] = -1.0;
988
989 BVectorWell x_well(1);
990 x_well[0].resize(nEq);
991 this->linSys_.solve(rhs, x_well);
992
993 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
994 EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
995 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
996 for (size_t pvIdx = 0; pvIdx < nEq; ++pvIdx) {
997 // well primary variable derivatives in EvalWell start at position Indices::numEq
998 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
999 }
1000 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
1001 }
1002 // reset cmode
1003 ws.production_cmode = cmode;
1004 }
1005
1006 template<typename TypeTag>
1007 void
1010 const Simulator& simulator,
1011 DeferredLogger& deferred_logger)
1012 {
1013 const auto& summaryState = simulator.vanguard().summaryState();
1014 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1015 // Crude but works: default is one atmosphere.
1016 // TODO: a better way to detect whether the BHP is defaulted or not
1017 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1018 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1019 // if the BHP limit is not defaulted or the well does not have a THP limit
1020 // we need to check the BHP limit
1021 Scalar total_ipr_mass_rate = 0.0;
1022 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1023 {
1024 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1025 continue;
1026 }
1027
1028 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1029 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1030
1031 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1032 total_ipr_mass_rate += ipr_rate * rho;
1033 }
1034 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1035 this->operability_status_.operable_under_only_bhp_limit = false;
1036 }
1037
1038 // checking whether running under BHP limit will violate THP limit
1039 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1040 // option 1: calculate well rates based on the BHP limit.
1041 // option 2: stick with the above IPR curve
1042 // we use IPR here
1043 std::vector<Scalar> well_rates_bhp_limit;
1044 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1045
1046 this->adaptRatesForVFP(well_rates_bhp_limit);
1047 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1048 const Scalar thp = WellBhpThpCalculator(*this).calculateThpFromBhp(well_rates_bhp_limit,
1049 bhp_limit,
1050 this->getRefDensity(),
1051 this->getALQ(well_state),
1052 thp_limit,
1053 deferred_logger);
1054 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1055 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
1056 }
1057 }
1058 } else {
1059 // defaulted BHP and there is a THP constraint
1060 // default BHP limit is about 1 atm.
1061 // when applied the hydrostatic pressure correction dp,
1062 // most likely we get a negative value (bhp + dp)to search in the VFP table,
1063 // which is not desirable.
1064 // we assume we can operate under defaulted BHP limit and will violate the THP limit
1065 // when operating under defaulted BHP limit.
1066 this->operability_status_.operable_under_only_bhp_limit = true;
1067 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
1068 }
1069 }
1070
1071
1072
1073
1074
1075 template<typename TypeTag>
1076 void
1079 const WellStateType& well_state,
1080 const GroupStateHelperType& groupStateHelper)
1081 {
1082 auto& deferred_logger = groupStateHelper.deferredLogger();
1083 const auto& summaryState = simulator.vanguard().summaryState();
1084 const auto obtain_bhp = this->isProducer() ? computeBhpAtThpLimitProd(well_state, simulator, groupStateHelper, summaryState)
1085 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1086
1087 if (obtain_bhp) {
1088 this->operability_status_.can_obtain_bhp_with_thp_limit = true;
1089
1090 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1091 this->operability_status_.obey_bhp_limit_with_thp_limit = this->isProducer() ?
1092 *obtain_bhp >= bhp_limit : *obtain_bhp <= bhp_limit ;
1093
1094 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1095 if (this->isProducer() && *obtain_bhp < thp_limit) {
1096 const std::string msg = " obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1097 + " bars is SMALLER than thp limit "
1098 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1099 + " bars as a producer for well " + name();
1100 deferred_logger.debug(msg);
1101 }
1102 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1103 const std::string msg = " obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1104 + " bars is LARGER than thp limit "
1105 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1106 + " bars as a injector for well " + name();
1107 deferred_logger.debug(msg);
1108 }
1109 } else {
1110 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
1111 this->operability_status_.obey_bhp_limit_with_thp_limit = false;
1112 if (!this->wellIsStopped()) {
1113 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1114 deferred_logger.debug(" could not find bhp value at thp limit "
1115 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1116 + " bar for well " + name() + ", the well might need to be closed ");
1117 }
1118 }
1119 }
1120
1121
1122
1123
1124
1125 template<typename TypeTag>
1126 bool
1128 allDrawDownWrongDirection(const Simulator& simulator) const
1129 {
1130 bool all_drawdown_wrong_direction = true;
1131
1132 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1133 const int cell_idx = this->well_cells_[perf];
1134 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/0);
1135 const auto& fs = intQuants.fluidState();
1136
1137 const Scalar pressure = this->getPerfCellPressure(fs).value();
1138 const Scalar bhp = this->primary_variables_.eval(Bhp).value();
1139
1140 // Pressure drawdown (also used to determine direction of flow)
1141 const Scalar well_pressure = bhp + this->connections_.pressure_diff(perf);
1142 const Scalar drawdown = pressure - well_pressure;
1143
1144 // for now, if there is one perforation can produce/inject in the correct
1145 // direction, we consider this well can still produce/inject.
1146 // TODO: it can be more complicated than this to cause wrong-signed rates
1147 if ( (drawdown < 0. && this->isInjector()) ||
1148 (drawdown > 0. && this->isProducer()) ) {
1149 all_drawdown_wrong_direction = false;
1150 break;
1151 }
1152 }
1153
1154 const auto& comm = this->parallel_well_info_.communication();
1155 if (comm.size() > 1)
1156 {
1157 all_drawdown_wrong_direction =
1158 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
1159 }
1160
1161 return all_drawdown_wrong_direction;
1162 }
1163
1164
1165
1166
1167 template<typename TypeTag>
1168 bool
1170 openCrossFlowAvoidSingularity(const Simulator& simulator) const
1171 {
1172 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
1173 }
1174
1175
1176
1177
1178 template<typename TypeTag>
1182 const WellStateType& well_state) const
1183 {
1184 auto prop_func = typename StdWellEval::StdWellConnections::PressurePropertyFunctions {
1185 // getTemperature
1186 [&model = simulator.model()](int cell_idx, int phase_idx)
1187 {
1188 return model.intensiveQuantities(cell_idx, /* time_idx = */ 0)
1189 .fluidState().temperature(phase_idx).value();
1190 },
1191
1192 // getSaltConcentration
1193 [&model = simulator.model()](int cell_idx)
1194 {
1195 return model.intensiveQuantities(cell_idx, /* time_idx = */ 0)
1196 .fluidState().saltConcentration().value();
1197 },
1198
1199 // getPvtRegionIdx
1200 [&model = simulator.model()](int cell_idx)
1201 {
1202 return model.intensiveQuantities(cell_idx, /* time_idx = */ 0)
1203 .fluidState().pvtRegionIndex();
1204 }
1205 };
1206
1207 if constexpr (Indices::enableSolvent) {
1208 prop_func.solventInverseFormationVolumeFactor =
1209 [&model = simulator.model()](int cell_idx)
1210 {
1211 return model.intensiveQuantities(cell_idx, /* time_idx = */ 0)
1212 .solventInverseFormationVolumeFactor().value();
1213 };
1214
1215 prop_func.solventRefDensity = [&model = simulator.model()](int cell_idx)
1216 {
1217 return model.intensiveQuantities(cell_idx, /* time_idx = */ 0)
1218 .solventRefDensity();
1219 };
1220 }
1221
1222 return this->connections_.computePropertiesForPressures(well_state, prop_func);
1223 }
1224
1225
1226
1227
1228
1229 template<typename TypeTag>
1232 getWellConvergence(const GroupStateHelperType& groupStateHelper,
1233 const std::vector<Scalar>& B_avg,
1234 const bool relax_tolerance) const
1235 {
1236 // the following implementation assume that the polymer is always after the w-o-g phases
1237 // For the polymer, energy and foam cases, there is one more mass balance equations of reservoir than wells
1238 assert((int(B_avg.size()) == this->num_conservation_quantities_) || has_polymer || has_energy || has_foam || has_brine || has_zFraction || has_bioeffects);
1239
1240 auto& deferred_logger = groupStateHelper.deferredLogger();
1241 Scalar tol_wells = this->param_.tolerance_wells_;
1242 // use stricter tolerance for stopped wells and wells under zero rate target control.
1243 constexpr Scalar stopped_factor = 1.e-4;
1244 // use stricter tolerance for dynamic thp to ameliorate network convergence
1245 constexpr Scalar dynamic_thp_factor = 1.e-1;
1246 if (this->stoppedOrZeroRateTarget(groupStateHelper)) {
1247 tol_wells = tol_wells*stopped_factor;
1248 } else if (this->getDynamicThpLimit()) {
1249 tol_wells = tol_wells*dynamic_thp_factor;
1250 }
1251
1252 std::vector<Scalar> res;
1253 ConvergenceReport report = this->StdWellEval::getWellConvergence(groupStateHelper.wellState(),
1254 B_avg,
1255 this->param_.max_residual_allowed_,
1256 tol_wells,
1257 this->param_.relaxed_tolerance_flow_well_,
1258 relax_tolerance,
1259 this->wellIsStopped(),
1260 res,
1261 deferred_logger);
1262
1263 checkConvergenceExtraEqs(res, report);
1264
1265 return report;
1266 }
1267
1268
1269
1270
1271
1272 template<typename TypeTag>
1273 void
1275 updateProductivityIndex(const Simulator& simulator,
1276 const WellProdIndexCalculator<Scalar>& wellPICalc,
1277 WellStateType& well_state,
1278 DeferredLogger& deferred_logger) const
1279 {
1280 auto fluidState = [&simulator, this](const int perf)
1281 {
1282 const auto cell_idx = this->well_cells_[perf];
1283 return simulator.model()
1284 .intensiveQuantities(cell_idx, /*timeIdx=*/ 0).fluidState();
1285 };
1286
1287 const int np = this->number_of_phases_;
1288 auto setToZero = [np](Scalar* x) -> void
1289 {
1290 std::fill_n(x, np, 0.0);
1291 };
1292
1293 auto addVector = [np](const Scalar* src, Scalar* dest) -> void
1294 {
1295 std::transform(src, src + np, dest, dest, std::plus<>{});
1296 };
1297
1298 auto& ws = well_state.well(this->index_of_well_);
1299 auto& perf_data = ws.perf_data;
1300 auto* wellPI = ws.productivity_index.data();
1301 auto* connPI = perf_data.prod_index.data();
1302
1303 setToZero(wellPI);
1304
1305 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
1306 auto subsetPerfID = 0;
1307
1308 for (const auto& perf : *this->perf_data_) {
1309 auto allPerfID = perf.ecl_index;
1310
1311 auto connPICalc = [&wellPICalc, allPerfID](const Scalar mobility) -> Scalar
1312 {
1313 return wellPICalc.connectionProdIndStandard(allPerfID, mobility);
1314 };
1315
1316 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1317 getMobility(simulator, static_cast<int>(subsetPerfID), mob, deferred_logger);
1318
1319 const auto& fs = fluidState(subsetPerfID);
1320 setToZero(connPI);
1321
1322 if (this->isInjector()) {
1323 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
1324 mob, connPI, deferred_logger);
1325 }
1326 else { // Production or zero flow rate
1327 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
1328 }
1329
1330 addVector(connPI, wellPI);
1331
1332 ++subsetPerfID;
1333 connPI += np;
1334 }
1335
1336 // Sum with communication in case of distributed well.
1337 const auto& comm = this->parallel_well_info_.communication();
1338 if (comm.size() > 1) {
1339 comm.sum(wellPI, np);
1340 }
1341
1342 assert ((static_cast<int>(subsetPerfID) == this->number_of_local_perforations_) &&
1343 "Internal logic error in processing connections for PI/II");
1344 }
1345
1346
1347
1348 template<typename TypeTag>
1351 const GroupStateHelperType& groupStateHelper,
1352 const WellConnectionProps& props)
1353 {
1354 auto& deferred_logger = groupStateHelper.deferredLogger();
1355 const auto& well_state = groupStateHelper.wellState();
1356 // Cell level dynamic property call-back functions as fall-back
1357 // option for calculating connection level mixture densities in
1358 // stopped or zero-rate producer wells.
1359 const auto prop_func = typename StdWellEval::StdWellConnections::DensityPropertyFunctions {
1360 // This becomes slightly more palatable with C++20's designated
1361 // initialisers.
1362
1363 // mobility: Phase mobilities in specified cell.
1364 [&model = simulator.model()](const int cell,
1365 const std::vector<int>& phases,
1366 std::vector<Scalar>& mob)
1367 {
1368 const auto& iq = model.intensiveQuantities(cell, /* time_idx = */ 0);
1369
1370 std::ranges::transform(phases, mob.begin(),
1371 [&iq](const int phase) { return iq.mobility(phase).value(); });
1372 },
1373
1374 // densityInCell: Reservoir condition phase densities in
1375 // specified cell.
1376 [&model = simulator.model()](const int cell,
1377 const std::vector<int>& phases,
1378 std::vector<Scalar>& rho)
1379 {
1380 const auto& fs = model.intensiveQuantities(cell, /* time_idx = */ 0).fluidState();
1381
1382 std::ranges::transform(phases, rho.begin(),
1383 [&fs](const int phase) { return fs.density(phase).value(); });
1384 }
1385 };
1386
1387 const auto stopped_or_zero_rate_target = this->
1388 stoppedOrZeroRateTarget(groupStateHelper);
1389
1390 this->connections_
1391 .computeProperties(stopped_or_zero_rate_target, well_state,
1392 prop_func, props, deferred_logger);
1393 // density was updated
1394 cachedRefDensity = this->connections_.rho(0);
1395 if (this->parallel_well_info_.communication().size() > 1) {
1396 cachedRefDensity = this->parallel_well_info_.broadcastFirstPerforationValue(cachedRefDensity);
1397 }
1398 }
1399
1400
1401
1402
1403
1404 template<typename TypeTag>
1405 void
1408 const GroupStateHelperType& groupStateHelper)
1409 {
1410 const auto& well_state = groupStateHelper.wellState();
1411 const auto props = computePropertiesForWellConnectionPressures
1412 (simulator, well_state);
1413
1414 computeWellConnectionDensitesPressures(simulator, groupStateHelper, props);
1415 }
1416
1417
1418
1419
1420
1421 template<typename TypeTag>
1422 void
1424 solveEqAndUpdateWellState(const Simulator& simulator,
1425 const GroupStateHelperType& groupStateHelper,
1426 WellStateType& well_state)
1427 {
1428 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1429
1430 // We assemble the well equations, then we check the convergence,
1431 // which is why we do not put the assembleWellEq here.
1432 BVectorWell dx_well(1);
1433 dx_well[0].resize(this->primary_variables_.numWellEq());
1434 {
1435 const auto linear_solve_timer = this->solveLinearSolveTimer();
1436 this->linSys_.solve( dx_well);
1437 }
1438
1439 updateWellState(simulator, dx_well, groupStateHelper, well_state);
1440 }
1441
1442
1443
1444
1445
1446 template<typename TypeTag>
1447 void
1450 const GroupStateHelperType& groupStateHelper)
1451 {
1452 updatePrimaryVariables(groupStateHelper);
1453 computeWellConnectionPressures(simulator, groupStateHelper);
1454 this->computeAccumWell();
1455 }
1456
1457
1458
1459 template<typename TypeTag>
1460 void
1462 apply(const BVector& x, BVector& Ax) const
1463 {
1464 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1465
1466 if (this->param_.matrix_add_well_contributions_)
1467 {
1468 // Contributions are already in the matrix itself
1469 return;
1470 }
1471
1472 this->linSys_.apply(x, Ax);
1473 }
1474
1475
1476
1477
1478 template<typename TypeTag>
1479 void
1481 apply(BVector& r) const
1482 {
1483 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1484
1485 this->linSys_.apply(r);
1486 }
1487
1488
1489
1490
1491 template<typename TypeTag>
1492 void
1495 const BVector& x,
1496 const GroupStateHelperType& groupStateHelper,
1497 WellStateType& well_state)
1498 {
1499 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1500
1501 BVectorWell xw(1);
1502 xw[0].resize(this->primary_variables_.numWellEq());
1503
1504 this->linSys_.recoverSolutionWell(x, xw);
1505 updateWellState(simulator, xw, groupStateHelper, well_state);
1506 }
1507
1508
1509
1510
1511 template<typename TypeTag>
1512 void
1514 computeWellRatesWithBhp(const Simulator& simulator,
1515 const Scalar& bhp,
1516 std::vector<Scalar>& well_flux,
1517 DeferredLogger& deferred_logger) const
1518 {
1519 OPM_TIMEFUNCTION();
1520 const int np = this->number_of_phases_;
1521 well_flux.resize(np, 0.0);
1522
1523 const bool allow_cf = this->getAllowCrossFlow();
1524
1525 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
1526 const int cell_idx = this->well_cells_[perf];
1527 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
1528 // flux for each perforation
1529 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
1530 getMobility(simulator, perf, mob, deferred_logger);
1531 Scalar trans_mult(0.0);
1532 getTransMult(trans_mult, simulator, cell_idx);
1533 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1534 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1535 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
1536
1537 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
1538 PerforationRates<Scalar> perf_rates;
1539 computePerfRate(intQuants, mob, bhp, Tw, perf, allow_cf,
1540 cq_s, perf_rates, deferred_logger);
1541
1542 for(int p = 0; p < np; ++p) {
1543 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
1544 }
1545
1546 // the solvent contribution is added to the gas potentials
1547 if constexpr (has_solvent) {
1548 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1549 // TODO: should we use compIdx here?
1550 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1551 well_flux[gas_pos] += cq_s[Indices::contiSolventEqIdx];
1552 }
1553 }
1554 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
1555 }
1556
1557
1558
1559 template<typename TypeTag>
1560 void
1563 const Scalar& bhp,
1564 const GroupStateHelperType& groupStateHelper,
1565 std::vector<Scalar>& well_flux) const
1566 {
1567 auto& deferred_logger = groupStateHelper.deferredLogger();
1568 // creating a copy of the well itself, to avoid messing up the explicit information
1569 // during this copy, the only information not copied properly is the well controls
1570 StandardWell<TypeTag> well_copy(*this);
1571 well_copy.resetDampening();
1572
1573 // iterate to get a more accurate well density
1574 // create a copy of the well_state to use. If the operability checking is sucessful, we use this one
1575 // to replace the original one
1576 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
1577 WellStateType well_state_copy = groupStateHelper_copy.wellState();
1578 // Ensure that groupStateHelper_copy uses well_state_copy as WellState for the rest of this function,
1579 // and the guard ensures that the original well state is restored at scope exit, i.e. at
1580 // the end of this function.
1581 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
1582
1583 // Get the current controls.
1584 const auto& summary_state = simulator.vanguard().summaryState();
1585 auto inj_controls = well_copy.well_ecl_.isInjector()
1586 ? well_copy.well_ecl_.injectionControls(summary_state)
1587 : Well::InjectionControls(0);
1588 auto prod_controls = well_copy.well_ecl_.isProducer()
1589 ? well_copy.well_ecl_.productionControls(summary_state) :
1590 Well::ProductionControls(0);
1591
1592 // Set current control to bhp, and bhp value in state, modify bhp limit in control object.
1593 auto& ws = well_state_copy.well(this->index_of_well_);
1594 if (well_copy.well_ecl_.isInjector()) {
1595 inj_controls.bhp_limit = bhp;
1596 ws.injection_cmode = Well::InjectorCMode::BHP;
1597 } else {
1598 prod_controls.bhp_limit = bhp;
1599 ws.production_cmode = Well::ProducerCMode::BHP;
1600 }
1601 ws.bhp = bhp;
1602
1603 // initialized the well rates with the potentials i.e. the well rates based on bhp
1604 const int np = this->number_of_phases_;
1605 const Scalar sign = this->well_ecl_.isInjector() ? 1.0 : -1.0;
1606 for (int phase = 0; phase < np; ++phase){
1607 well_state_copy.wellRates(this->index_of_well_)[phase]
1608 = sign * ws.well_potentials[phase];
1609 }
1610 well_copy.updatePrimaryVariables(groupStateHelper_copy);
1611 well_copy.computeAccumWell();
1612
1613 const double dt = simulator.timeStepSize();
1614 const bool converged = well_copy.iterateWellEqWithControl(
1615 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1616 );
1617 if (!converged) {
1618 const std::string msg = " well " + name() + " did not get converged during well potential calculations "
1619 " potentials are computed based on unconverged solution";
1620 deferred_logger.debug(msg);
1621 }
1622 well_copy.updatePrimaryVariables(groupStateHelper_copy);
1623 well_copy.computeWellConnectionPressures(simulator, groupStateHelper_copy);
1624 well_copy.computeWellRatesWithBhp(simulator, bhp, well_flux, deferred_logger);
1625 }
1626
1627
1628
1629
1630 template<typename TypeTag>
1631 std::vector<typename StandardWell<TypeTag>::Scalar>
1634 const GroupStateHelperType& groupStateHelper,
1635 const WellStateType& well_state) const
1636 {
1637 auto& deferred_logger = groupStateHelper.deferredLogger();
1638 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
1639 const auto& summary_state = simulator.vanguard().summaryState();
1640
1641 const auto& well = this->well_ecl_;
1642 if (well.isInjector()){
1643 const auto& controls = this->well_ecl_.injectionControls(summary_state);
1644 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
1645 if (bhp_at_thp_limit) {
1646 const Scalar bhp = std::min(*bhp_at_thp_limit,
1647 static_cast<Scalar>(controls.bhp_limit));
1648 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1649 } else {
1650 deferred_logger.warning("FAILURE_GETTING_CONVERGED_POTENTIAL",
1651 "Failed in getting converged thp based potential calculation for well "
1652 + name() + ". Instead the bhp based value is used");
1653 const Scalar bhp = controls.bhp_limit;
1654 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1655 }
1656 } else {
1657 computeWellRatesWithThpAlqProd(
1658 simulator, groupStateHelper, summary_state,
1659 potentials, this->getALQ(well_state)
1660 );
1661 }
1662
1663 return potentials;
1664 }
1665
1666 template<typename TypeTag>
1667 bool
1670 const GroupStateHelperType& groupStateHelper,
1671 std::vector<Scalar>& well_potentials) const
1672 {
1673 // Create a copy of the well.
1674 // TODO: check if we can avoid taking multiple copies. Call from updateWellPotentials
1675 // is allready a copy, but not from other calls.
1676 StandardWell<TypeTag> well_copy(*this);
1677
1678 // store a copy of the well state, we don't want to update the real well state
1679 WellStateType well_state_copy = groupStateHelper.wellState();
1680 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
1681 // Ensure that groupStateHelper_copy uses well_state_copy as WellState for the rest of this function,
1682 // and the guard ensures that the original well state is restored at scope exit, i.e. at
1683 // the end of this function.
1684 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
1685 auto& ws = well_state_copy.well(this->index_of_well_);
1686
1687 // get current controls
1688 const auto& summary_state = simulator.vanguard().summaryState();
1689 auto inj_controls = well_copy.well_ecl_.isInjector()
1690 ? well_copy.well_ecl_.injectionControls(summary_state)
1691 : Well::InjectionControls(0);
1692 auto prod_controls = well_copy.well_ecl_.isProducer()
1693 ? well_copy.well_ecl_.productionControls(summary_state) :
1694 Well::ProductionControls(0);
1695
1696 // prepare/modify well state and control
1697 well_copy.onlyKeepBHPandTHPcontrols(summary_state, well_state_copy, inj_controls, prod_controls);
1698
1699 // update connection pressures relative to updated bhp to get better estimate of connection dp
1700 const int num_perf = ws.perf_data.size();
1701 for (int perf = 0; perf < num_perf; ++perf) {
1702 ws.perf_data.pressure[perf] = ws.bhp + well_copy.connections_.pressure_diff(perf);
1703 }
1704 // initialize rates from previous potentials
1705 const int np = this->number_of_phases_;
1706 bool trivial = true;
1707 for (int phase = 0; phase < np; ++phase){
1708 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
1709 }
1710 if (!trivial) {
1711 const Scalar sign = well_copy.well_ecl_.isInjector() ? 1.0 : -1.0;
1712 for (int phase = 0; phase < np; ++phase) {
1713 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
1714 }
1715 }
1716
1717 well_copy.calculateExplicitQuantities(simulator, groupStateHelper_copy);
1718 const double dt = simulator.timeStepSize();
1719 // iterate to get a solution at the given bhp.
1720 bool converged = false;
1721 if (this->well_ecl_.isProducer()) {
1722 converged = well_copy.solveWellWithOperabilityCheck(
1723 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
1724 );
1725 } else {
1726 converged = well_copy.iterateWellEqWithSwitching(
1727 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
1728 /*fixed_control=*/false,
1729 /*fixed_status=*/false,
1730 /*solving_with_zero_rate=*/false
1731 );
1732 }
1733
1734 // fetch potentials (sign is updated on the outside).
1735 well_potentials.clear();
1736 well_potentials.resize(np, 0.0);
1737 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1738 if (has_solvent && comp_idx == Indices::contiSolventEqIdx) continue; // we do not store the solvent in the well_potentials
1739 const EvalWell rate = well_copy.primary_variables_.getQs(comp_idx);
1740 well_potentials[FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = rate.value();
1741 }
1742
1743 // the solvent contribution is added to the gas potentials
1744 if constexpr (has_solvent) {
1745 assert(FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx));
1746 // TODO: should we use compIdx here?
1747 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
1748 const EvalWell rate = well_copy.primary_variables_.getQs(Indices::contiSolventEqIdx);
1749 well_potentials[gas_pos] += rate.value();
1750 }
1751 return converged;
1752 }
1753
1754
1755 template<typename TypeTag>
1759 const GroupStateHelperType& groupStateHelper,
1760 const SummaryState &summary_state,
1761 std::vector<Scalar>& potentials,
1762 Scalar alq) const
1763 {
1764 auto& deferred_logger = groupStateHelper.deferredLogger();
1765 Scalar bhp;
1766 auto bhp_at_thp_limit = computeBhpAtThpLimitProdWithAlq(
1767 simulator, groupStateHelper, summary_state, alq, /*iterate_if_no_solution */ true);
1768 if (bhp_at_thp_limit) {
1769 const auto& controls = this->well_ecl_.productionControls(summary_state);
1770 bhp = std::max(*bhp_at_thp_limit,
1771 static_cast<Scalar>(controls.bhp_limit));
1772 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1773 }
1774 else {
1775 deferred_logger.warning("FAILURE_GETTING_CONVERGED_POTENTIAL",
1776 "Failed in getting converged thp based potential calculation for well "
1777 + name() + ". Instead the bhp based value is used");
1778 const auto& controls = this->well_ecl_.productionControls(summary_state);
1779 bhp = controls.bhp_limit;
1780 computeWellRatesWithBhp(simulator, bhp, potentials, deferred_logger);
1781 }
1782 return bhp;
1783 }
1784
1785 template<typename TypeTag>
1786 void
1789 const GroupStateHelperType& groupStateHelper,
1790 const SummaryState& summary_state,
1791 std::vector<Scalar>& potentials,
1792 Scalar alq) const
1793 {
1794 /*double bhp =*/
1795 computeWellRatesAndBhpWithThpAlqProd(simulator,
1796 groupStateHelper,
1797 summary_state,
1798 potentials,
1799 alq);
1800 }
1801
1802 template<typename TypeTag>
1803 void
1805 computeWellPotentials(const Simulator& simulator,
1806 const WellStateType& well_state,
1807 const GroupStateHelperType& groupStateHelper,
1808 std::vector<Scalar>& well_potentials) // const
1809 {
1810 auto& deferred_logger = groupStateHelper.deferredLogger();
1811 const auto [compute_potential, bhp_controlled_well] =
1813
1814 if (!compute_potential) {
1815 return;
1816 }
1817
1818 // attribute the well solves done below (also those done by well
1819 // copies) to the well potential calculations in the solve statistics
1820 const auto potential_scope = this->potentialCalculationScope();
1821
1822 bool converged_implicit = false;
1823 // for newly opened wells we dont compute the potentials implicit
1824 // group controlled wells with defaulted guiderates will have zero targets as
1825 // the potentials are used to compute the well fractions.
1826 if (this->param_.local_well_solver_control_switching_ && !(this->changed_to_open_this_step_ && this->wellUnderZeroRateTarget(groupStateHelper))) {
1827 converged_implicit = computeWellPotentialsImplicit(
1828 simulator, groupStateHelper, well_potentials
1829 );
1830 }
1831 if (!converged_implicit) {
1832 // does the well have a THP related constraint?
1833 const auto& summaryState = simulator.vanguard().summaryState();
1834 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
1835 // get the bhp value based on the bhp constraints
1836 Scalar bhp = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1837
1838 // In some very special cases the bhp pressure target are
1839 // temporary violated. This may lead to too small or negative potentials
1840 // that could lead to premature shutting of wells.
1841 // As a remedy the bhp that gives the largest potential is used.
1842 // For converged cases, ws.bhp <=bhp for injectors and ws.bhp >= bhp,
1843 // and the potentials will be computed using the limit as expected.
1844 const auto& ws = well_state.well(this->index_of_well_);
1845 if (this->isInjector())
1846 bhp = std::max(ws.bhp, bhp);
1847 else
1848 bhp = std::min(ws.bhp, bhp);
1849
1850 assert(std::abs(bhp) != std::numeric_limits<Scalar>::max());
1851 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, well_potentials);
1852 } else {
1853 // the well has a THP related constraint
1854 well_potentials = computeWellPotentialWithTHP(simulator, groupStateHelper, well_state);
1855 }
1856 }
1857
1858 this->checkNegativeWellPotentials(well_potentials,
1859 this->param_.check_well_operability_,
1860 deferred_logger);
1861 }
1862
1863
1864
1865
1866
1867
1868
1869 template<typename TypeTag>
1872 connectionDensity([[maybe_unused]] const int globalConnIdx,
1873 const int openConnIdx) const
1874 {
1875 return (openConnIdx < 0)
1876 ? 0.0
1877 : this->connections_.rho(openConnIdx);
1878 }
1879
1880
1881
1882
1883
1884 template<typename TypeTag>
1885 void
1887 updatePrimaryVariables(const GroupStateHelperType& groupStateHelper)
1888 {
1889 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1890
1891 auto& deferred_logger = groupStateHelper.deferredLogger();
1892 const auto& well_state = groupStateHelper.wellState();
1893 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
1894 this->primary_variables_.update(well_state, stop_or_zero_rate_target, deferred_logger);
1895
1896 // other primary variables related to polymer injection
1897 if constexpr (Base::has_polymermw) {
1898 this->primary_variables_.updatePolyMW(well_state);
1899 }
1900
1901 this->primary_variables_.checkFinite(deferred_logger, "updating from well state");
1902 }
1903
1904
1905
1906
1907 template<typename TypeTag>
1910 getRefDensity() const
1911 {
1912 return cachedRefDensity;
1913 }
1914
1915
1916
1917
1918 template<typename TypeTag>
1919 void
1922 const int perf,
1923 std::vector<EvalWell>& mob,
1924 DeferredLogger& deferred_logger) const
1925 {
1926 const int cell_idx = this->well_cells_[perf];
1927 const auto& int_quant = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
1928 const EvalWell polymer_concentration = this->extendEval(int_quant.polymerConcentration());
1929
1930 // TODO: not sure should based on the well type or injecting/producing peforations
1931 // it can be different for crossflow
1932 if (this->isInjector()) {
1933 // assume fully mixing within injecting wellbore
1934 const auto& visc_mult_table = PolymerModule::plyviscViscosityMultiplierTable(int_quant.pvtRegionIndex());
1935 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1936 mob[waterCompIdx] /= (this->extendEval(int_quant.waterViscosityCorrection()) * visc_mult_table.eval(polymer_concentration, /*extrapolate=*/true) );
1937 }
1938
1939 if (PolymerModule::hasPlyshlog()) {
1940 // we do not calculate the shear effects for injection wells when they do not
1941 // inject polymer.
1942 if (this->isInjector() && this->wpolymer() == 0.) {
1943 return;
1944 }
1945 // compute the well water velocity with out shear effects.
1946 // TODO: do we need to turn on crossflow here?
1947 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1948 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
1949
1950 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.);
1951 PerforationRates<Scalar> perf_rates;
1952 EvalWell trans_mult(0.0);
1953 getTransMult(trans_mult, simulator, cell_idx);
1954 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1955 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1956 this->getTw(Tw, perf, int_quant, trans_mult, wellstate_nupcol);
1957 computePerfRate(int_quant, mob, bhp, Tw, perf, allow_cf, cq_s,
1958 perf_rates, deferred_logger);
1959 // TODO: make area a member
1960 const Scalar area = 2 * std::numbers::pi_v<Scalar> * this->perf_rep_radius_[perf] * this->perf_length_[perf];
1961 const auto& material_law_manager = simulator.problem().materialLawManager();
1962 const auto& scaled_drainage_info =
1963 material_law_manager->oilWaterScaledEpsInfoDrainage(cell_idx);
1964 const Scalar swcr = scaled_drainage_info.Swcr;
1965 const EvalWell poro = this->extendEval(int_quant.porosity());
1966 const EvalWell sw = this->extendEval(int_quant.fluidState().saturation(FluidSystem::waterPhaseIdx));
1967 // guard against zero porosity and no water
1968 const EvalWell denom = max( (area * poro * (sw - swcr)), 1e-12);
1969 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1970 EvalWell water_velocity = cq_s[waterCompIdx] / denom * this->extendEval(int_quant.fluidState().invB(FluidSystem::waterPhaseIdx));
1971
1972 if (PolymerModule::hasShrate()) {
1973 // the equation for the water velocity conversion for the wells and reservoir are from different version
1974 // of implementation. It can be changed to be more consistent when possible.
1975 water_velocity *= PolymerModule::shrate( int_quant.pvtRegionIndex() ) / this->bore_diameters_[perf];
1976 }
1977 const EvalWell shear_factor = PolymerModule::computeShearFactor(polymer_concentration,
1978 int_quant.pvtRegionIndex(),
1979 water_velocity);
1980 // modify the mobility with the shear factor.
1981 mob[waterCompIdx] /= shear_factor;
1982 }
1983 }
1984
1985 template<typename TypeTag>
1986 void
1988 {
1989 this->linSys_.extract(jacobian);
1990 }
1991
1992
1993 template <typename TypeTag>
1994 void
1996 const BVector& weights,
1997 const int pressureVarIndex,
1998 const bool use_well_weights,
1999 const WellStateType& well_state) const
2000 {
2001 this->linSys_.extractCPRPressureMatrix(jacobian,
2002 weights,
2003 pressureVarIndex,
2004 use_well_weights,
2005 *this,
2006 Bhp,
2007 well_state);
2008 }
2009
2010
2011
2012 template<typename TypeTag>
2015 pskinwater(const Scalar throughput,
2016 const EvalWell& water_velocity,
2017 DeferredLogger& deferred_logger) const
2018 {
2019 if constexpr (Base::has_polymermw) {
2020 const int water_table_id = this->polymerWaterTable_();
2021 if (water_table_id <= 0) {
2022 OPM_DEFLOG_THROW(std::runtime_error,
2023 fmt::format("Unused SKPRWAT table id used for well {}", name()),
2024 deferred_logger);
2025 }
2026 const auto& water_table_func = PolymerModule::getSkprwatTable(water_table_id);
2027 const EvalWell throughput_eval{throughput};
2028 // the skin pressure when injecting water, which also means the polymer concentration is zero
2029 EvalWell pskin_water = water_table_func.eval(throughput_eval, water_velocity);
2030 return pskin_water;
2031 } else {
2032 OPM_DEFLOG_THROW(std::runtime_error,
2033 fmt::format("Polymermw is not activated, while injecting "
2034 "skin pressure is requested for well {}", name()),
2035 deferred_logger);
2036 }
2037 }
2038
2039
2040
2041
2042
2043 template<typename TypeTag>
2046 pskin(const Scalar throughput,
2047 const EvalWell& water_velocity,
2048 const EvalWell& poly_inj_conc,
2049 DeferredLogger& deferred_logger) const
2050 {
2051 if constexpr (Base::has_polymermw) {
2052 const Scalar sign = water_velocity >= 0. ? 1.0 : -1.0;
2053 const EvalWell water_velocity_abs = abs(water_velocity);
2054 if (poly_inj_conc == 0.) {
2055 return sign * pskinwater(throughput, water_velocity_abs, deferred_logger);
2056 }
2057 const int polymer_table_id = this->polymerTable_();
2058 if (polymer_table_id <= 0) {
2059 OPM_DEFLOG_THROW(std::runtime_error,
2060 fmt::format("Unavailable SKPRPOLY table id used for well {}", name()),
2061 deferred_logger);
2062 }
2063 const auto& skprpolytable = PolymerModule::getSkprpolyTable(polymer_table_id);
2064 const Scalar reference_concentration = skprpolytable.refConcentration;
2065 const EvalWell throughput_eval{throughput};
2066 // the skin pressure when injecting water, which also means the polymer concentration is zero
2067 const EvalWell pskin_poly = skprpolytable.table_func.eval(throughput_eval, water_velocity_abs);
2068 if (poly_inj_conc == reference_concentration) {
2069 return sign * pskin_poly;
2070 }
2071 // poly_inj_conc != reference concentration of the table, then some interpolation will be required
2072 const EvalWell pskin_water = pskinwater(throughput, water_velocity_abs, deferred_logger);
2073 const EvalWell pskin = pskin_water + (pskin_poly - pskin_water) / reference_concentration * poly_inj_conc;
2074 return sign * pskin;
2075 } else {
2076 OPM_DEFLOG_THROW(std::runtime_error,
2077 fmt::format("Polymermw is not activated, while injecting "
2078 "skin pressure is requested for well {}", name()),
2079 deferred_logger);
2080 }
2081 }
2082
2083
2084
2085
2086
2087 template<typename TypeTag>
2090 wpolymermw(const Scalar throughput,
2091 const EvalWell& water_velocity,
2092 DeferredLogger& deferred_logger) const
2093 {
2094 if constexpr (Base::has_polymermw) {
2095 const int table_id = this->polymerInjTable_();
2096 const auto& table_func = PolymerModule::getPlymwinjTable(table_id);
2097 const EvalWell throughput_eval{throughput};
2098 EvalWell molecular_weight{0.};
2099 if (this->wpolymer() == 0.) { // not injecting polymer
2100 return molecular_weight;
2101 }
2102 molecular_weight = table_func.eval(throughput_eval, abs(water_velocity));
2103 return molecular_weight;
2104 } else {
2105 OPM_DEFLOG_THROW(std::runtime_error,
2106 fmt::format("Polymermw is not activated, while injecting "
2107 "polymer molecular weight is requested for well {}", name()),
2108 deferred_logger);
2109 }
2110 }
2111
2112
2113
2114
2115
2116 template<typename TypeTag>
2117 void
2119 updateWaterThroughput([[maybe_unused]] const double dt,
2120 WellStateType& well_state) const
2121 {
2122 if constexpr (Base::has_polymermw) {
2123 if (!this->isInjector()) {
2124 return;
2125 }
2126
2127 auto& perf_water_throughput = well_state.well(this->index_of_well_)
2128 .perf_data.water_throughput;
2129
2130 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2131 const Scalar perf_water_vel =
2132 this->primary_variables_.value(Bhp + 1 + perf);
2133
2134 // we do not consider the formation damage due to water
2135 // flowing from reservoir into wellbore
2136 if (perf_water_vel > Scalar{0}) {
2137 perf_water_throughput[perf] += perf_water_vel * dt;
2138 }
2139 }
2140 }
2141 }
2142
2143
2144
2145
2146
2147 template<typename TypeTag>
2148 void
2150 handleInjectivityRate(const Simulator& simulator,
2151 const int perf,
2152 std::vector<EvalWell>& cq_s) const
2153 {
2154 const int cell_idx = this->well_cells_[perf];
2155 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2156 const auto& fs = int_quants.fluidState();
2157 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2158 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2159 const int wat_vel_index = Bhp + 1 + perf;
2160 const unsigned water_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2161
2162 // water rate is update to use the form from water velocity, since water velocity is
2163 // a primary variable now
2164 cq_s[water_comp_idx] = area * this->primary_variables_.eval(wat_vel_index) * b_w;
2165 }
2166
2167
2168
2169
2170 template<typename TypeTag>
2171 void
2173 handleInjectivityEquations(const Simulator& simulator,
2174 const WellStateType& well_state,
2175 const int perf,
2176 const EvalWell& water_flux_s,
2177 DeferredLogger& deferred_logger)
2178 {
2179 const int cell_idx = this->well_cells_[perf];
2180 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2181 const auto& fs = int_quants.fluidState();
2182 const EvalWell b_w = this->extendEval(fs.invB(FluidSystem::waterPhaseIdx));
2183 const EvalWell water_flux_r = water_flux_s / b_w;
2184 const Scalar area = std::numbers::pi_v<Scalar> * this->bore_diameters_[perf] * this->perf_length_[perf];
2185 const EvalWell water_velocity = water_flux_r / area;
2186 const int wat_vel_index = Bhp + 1 + perf;
2187
2188 // equation for the water velocity
2189 const EvalWell eq_wat_vel = this->primary_variables_.eval(wat_vel_index) - water_velocity;
2190
2191 const auto& ws = well_state.well(this->index_of_well_);
2192 const auto& perf_data = ws.perf_data;
2193 const auto& perf_water_throughput = perf_data.water_throughput;
2194 const Scalar throughput = perf_water_throughput[perf];
2195 const int pskin_index = Bhp + 1 + this->number_of_local_perforations_ + perf;
2196
2197 const EvalWell poly_conc(this->wpolymer());
2198
2199 // equation for the skin pressure
2200 const EvalWell eq_pskin = this->primary_variables_.eval(pskin_index)
2201 - pskin(throughput, this->primary_variables_.eval(wat_vel_index), poly_conc, deferred_logger);
2202
2204 assembleInjectivityEq(eq_pskin,
2205 eq_wat_vel,
2206 pskin_index,
2207 wat_vel_index,
2208 perf,
2209 this->primary_variables_.numWellEq(),
2210 this->linSys_);
2211 }
2212
2213
2214
2215
2216
2217 template<typename TypeTag>
2218 void
2220 checkConvergenceExtraEqs(const std::vector<Scalar>& res,
2221 ConvergenceReport& report) const
2222 {
2223 // if different types of extra equations are involved, this function needs to be refactored further
2224
2225 // checking the convergence of the extra equations related to polymer injectivity
2226 if constexpr (Base::has_polymermw) {
2227 WellConvergence(*this).
2228 checkConvergencePolyMW(res, Bhp, this->param_.max_residual_allowed_, report);
2229 }
2230 }
2231
2232
2233
2234
2235
2236 template<typename TypeTag>
2237 void
2239 updateConnectionRatePolyMW(const EvalWell& cq_s_poly,
2240 const IntensiveQuantities& int_quants,
2241 const WellStateType& well_state,
2242 const int perf,
2243 std::vector<RateVector>& connectionRates,
2244 DeferredLogger& deferred_logger) const
2245 {
2246 // the source term related to transport of molecular weight
2247 EvalWell cq_s_polymw = cq_s_poly;
2248 if (this->isInjector()) {
2249 const int wat_vel_index = Bhp + 1 + perf;
2250 const EvalWell water_velocity = this->primary_variables_.eval(wat_vel_index);
2251 if (water_velocity > 0.) { // injecting
2252 const auto& ws = well_state.well(this->index_of_well_);
2253 const auto& perf_water_throughput = ws.perf_data.water_throughput;
2254 const Scalar throughput = perf_water_throughput[perf];
2255 const EvalWell molecular_weight = wpolymermw(throughput, water_velocity, deferred_logger);
2256 cq_s_polymw *= molecular_weight;
2257 } else {
2258 // we do not consider the molecular weight from the polymer
2259 // going-back to the wellbore through injector
2260 cq_s_polymw *= 0.;
2261 }
2262 } else if (this->isProducer()) {
2263 if (cq_s_polymw < 0.) {
2264 cq_s_polymw *= this->extendEval(int_quants.polymerMoleWeight() );
2265 } else {
2266 // we do not consider the molecular weight from the polymer
2267 // re-injecting back through producer
2268 cq_s_polymw *= 0.;
2269 }
2270 }
2271 connectionRates[perf][Indices::contiPolymerMWEqIdx] = Base::restrictEval(cq_s_polymw);
2272 }
2273
2274
2275
2276
2277
2278 template<typename TypeTag>
2279 std::optional<typename StandardWell<TypeTag>::Scalar>
2282 const Simulator& simulator,
2283 const GroupStateHelperType& groupStateHelper,
2284 const SummaryState& summary_state) const
2285 {
2286 return computeBhpAtThpLimitProdWithAlq(simulator,
2287 groupStateHelper,
2288 summary_state,
2289 this->getALQ(well_state),
2290 /*iterate_if_no_solution */ true);
2291 }
2292
2293 template<typename TypeTag>
2294 std::optional<typename StandardWell<TypeTag>::Scalar>
2297 const GroupStateHelperType& groupStateHelper,
2298 const SummaryState& summary_state,
2299 const Scalar alq_value,
2300 bool iterate_if_no_solution) const
2301 {
2302 OPM_TIMEFUNCTION();
2303 auto& deferred_logger = groupStateHelper.deferredLogger();
2304 // Make the frates() function.
2305 auto frates = [this, &simulator, &deferred_logger](const Scalar bhp) {
2306 // Not solving the well equations here, which means we are
2307 // calculating at the current Fg/Fw values of the
2308 // well. This does not matter unless the well is
2309 // crossflowing, and then it is likely still a good
2310 // approximation.
2311 std::vector<Scalar> rates(3);
2312 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2313 this->adaptRatesForVFP(rates);
2314 return rates;
2315 };
2316 auto bhpAtLimit = WellBhpThpCalculator(*this).computeBhpAtThpLimitProd(frates,
2317 summary_state,
2318 maxPerfPress(simulator),
2319 this->getRefDensity(),
2320 alq_value,
2321 this->getTHPConstraint(summary_state),
2322 deferred_logger);
2323
2324 if (bhpAtLimit) {
2325 auto v = frates(*bhpAtLimit);
2326 if (std::ranges::all_of(v, [](Scalar i) { return i <= 0; })) {
2327 return bhpAtLimit;
2328 }
2329 }
2330
2331 if (!iterate_if_no_solution)
2332 return std::nullopt;
2333
2334 auto fratesIter = [this, &simulator, &groupStateHelper](const Scalar bhp) {
2335 // Solver the well iterations to see if we are
2336 // able to get a solution with an update
2337 // solution
2338 std::vector<Scalar> rates(3);
2339 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2340 this->adaptRatesForVFP(rates);
2341 return rates;
2342 };
2343
2344 bhpAtLimit = WellBhpThpCalculator(*this).computeBhpAtThpLimitProd(fratesIter,
2345 summary_state,
2346 maxPerfPress(simulator),
2347 this->getRefDensity(),
2348 alq_value,
2349 this->getTHPConstraint(summary_state),
2350 deferred_logger);
2351
2352
2353 if (bhpAtLimit) {
2354 // should we use fratesIter here since fratesIter is used in computeBhpAtThpLimitProd above?
2355 auto v = frates(*bhpAtLimit);
2356 if (std::ranges::all_of(v, [](Scalar i) { return i <= 0; })) {
2357 return bhpAtLimit;
2358 }
2359 }
2360
2361 // we still don't get a valied solution.
2362 return std::nullopt;
2363 }
2364
2365
2366
2367 template<typename TypeTag>
2368 std::optional<typename StandardWell<TypeTag>::Scalar>
2370 computeBhpAtThpLimitInj(const Simulator& simulator,
2371 const GroupStateHelperType& groupStateHelper,
2372 const SummaryState& summary_state) const
2373 {
2374 auto& deferred_logger = groupStateHelper.deferredLogger();
2375 // Make the frates() function.
2376 auto frates = [this, &simulator, &deferred_logger](const Scalar bhp) {
2377 // Not solving the well equations here, which means we are
2378 // calculating at the current Fg/Fw values of the
2379 // well. This does not matter unless the well is
2380 // crossflowing, and then it is likely still a good
2381 // approximation.
2382 std::vector<Scalar> rates(3);
2383 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2384 return rates;
2385 };
2386
2387 return WellBhpThpCalculator(*this).computeBhpAtThpLimitInj(frates,
2388 summary_state,
2389 this->getRefDensity(),
2390 1e-6,
2391 50,
2392 true,
2393 deferred_logger);
2394 }
2395
2396
2397
2398
2399
2400 template<typename TypeTag>
2401 bool
2403 iterateWellEqWithControl(const Simulator& simulator,
2404 const double dt,
2405 const Well::InjectionControls& inj_controls,
2406 const Well::ProductionControls& prod_controls,
2407 const GroupStateHelperType& groupStateHelper,
2408 WellStateType& well_state)
2409 {
2410 auto& deferred_logger = groupStateHelper.deferredLogger();
2411
2412 updatePrimaryVariables(groupStateHelper);
2413
2414 const int max_iter = this->param_.max_inner_iter_wells_;
2415 int it = 0;
2416 const auto solve_scope = this->solveScope(it);
2417 bool converged;
2418 bool relax_convergence = false;
2419 this->regularize_ = false;
2420 do {
2421 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
2422 /*solving_with_zero_rate=*/false);
2423
2424 if (it > this->param_.strict_inner_iter_wells_) {
2425 relax_convergence = true;
2426 this->regularize_ = true;
2427 }
2428
2429 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2430
2431 converged = report.converged();
2432 if (converged) {
2433 break;
2434 }
2435
2436 ++it;
2437 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2438
2439 // TODO: when this function is used for well testing purposes, will need to check the controls, so that we will obtain convergence
2440 // under the most restrictive control. Based on this converged results, we can check whether to re-open the well. Either we refactor
2441 // this function or we use different functions for the well testing purposes.
2442 // We don't allow for switching well controls while computing well potentials and testing wells
2443 // updateWellControl(simulator, well_state, deferred_logger);
2444 } while (it < max_iter);
2445
2446 if (converged) {
2447 std::ostringstream sstr;
2448 sstr << " Well " << this->name() << " converged in " << it << " inner iterations.";
2449 if (relax_convergence)
2450 sstr << " (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ << " iterations)";
2451
2452 // Output "converged in 0 inner iterations" messages only at
2453 // elevated verbosity levels.
2454 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
2455 } else {
2456 std::ostringstream sstr;
2457 sstr << " Well " << this->name() << " did not converge in " << it << " inner iterations.";
2458 deferred_logger.debug(sstr.str());
2459 }
2460
2461 return converged;
2462 }
2463
2464
2465 template<typename TypeTag>
2466 bool
2468 iterateWellEqWithSwitching(const Simulator& simulator,
2469 const double dt,
2470 const Well::InjectionControls& inj_controls,
2471 const Well::ProductionControls& prod_controls,
2472 const GroupStateHelperType& groupStateHelper,
2473 WellStateType& well_state,
2474 const bool fixed_control /*false*/,
2475 const bool fixed_status /*false*/,
2476 const bool solving_with_zero_rate /*false*/)
2477 {
2478 auto& deferred_logger = groupStateHelper.deferredLogger();
2479
2480 updatePrimaryVariables(groupStateHelper);
2481
2482 const int max_iter = this->param_.max_inner_iter_wells_;
2483 int it = 0;
2484 const auto solve_scope = this->solveScope(it);
2485 bool converged = false;
2486 bool relax_convergence = false;
2487 this->regularize_ = false;
2488 const auto& summary_state = groupStateHelper.summaryState();
2489
2490 // Always take a few (more than one) iterations after a switch before allowing a new switch
2491 // The optimal number here is subject to further investigation, but it has been observerved
2492 // that unless this number is >1, we may get stuck in a cycle
2493 constexpr int min_its_after_switch = 4;
2494 // We also want to restrict the number of status switches to avoid oscillation between STOP<->OPEN
2495 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
2496 int its_since_last_switch = min_its_after_switch;
2497 int switch_count= 0;
2498 // if we fail to solve eqs, we reset status/operability before leaving
2499 const auto well_status_orig = this->wellStatus_;
2500 const auto operability_orig = this->operability_status_;
2501 auto well_status_cur = well_status_orig;
2502 int status_switch_count = 0;
2503 // don't allow opening wells that has a stopped well status
2504 const bool allow_open = well_state.well(this->index_of_well_).status == WellStatus::OPEN;
2505 // don't allow switcing for wells under zero rate target or requested fixed status and control
2506 const bool allow_switching =
2507 !this->wellUnderZeroRateTarget(groupStateHelper) &&
2508 (!fixed_control || !fixed_status) && allow_open;
2509
2510 bool changed = false;
2511 bool final_check = false;
2512 // well needs to be set operable or else solving/updating of re-opened wells is skipped
2513 this->operability_status_.resetOperability();
2514 this->operability_status_.solvable = true;
2515 do {
2516 its_since_last_switch++;
2517 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
2518 const Scalar wqTotal = this->primary_variables_.eval(WQTotal).value();
2519 changed = this->updateWellControlAndStatusLocalIteration(
2520 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
2521 well_state, fixed_control, fixed_status,
2522 solving_with_zero_rate
2523 );
2524 if (changed){
2525 its_since_last_switch = 0;
2526 switch_count++;
2527 if (well_status_cur != this->wellStatus_) {
2528 well_status_cur = this->wellStatus_;
2529 status_switch_count++;
2530 }
2531 }
2532 if (!changed && final_check) {
2533 break;
2534 } else {
2535 final_check = false;
2536 }
2537 if (status_switch_count == max_status_switch) {
2538 this->wellStatus_ = well_status_orig;
2539 }
2540 }
2541
2542 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state, solving_with_zero_rate);
2543
2544 if (it > this->param_.strict_inner_iter_wells_) {
2545 relax_convergence = true;
2546 this->regularize_ = true;
2547 }
2548
2549 auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
2550
2551 converged = report.converged();
2552 if (converged) {
2553 // if equations are sufficiently linear they might converge in less than min_its_after_switch
2554 // in this case, make sure all constraints are satisfied before returning
2555 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
2556 final_check = true;
2557 its_since_last_switch = min_its_after_switch;
2558 } else {
2559 break;
2560 }
2561 }
2562
2563 ++it;
2564 solveEqAndUpdateWellState(simulator, groupStateHelper, well_state);
2565
2566 } while (it < max_iter);
2567
2568 if (converged) {
2569 if (allow_switching){
2570 // update operability if status change
2571 const bool is_stopped = this->wellIsStopped();
2572 if (this->wellHasTHPConstraints(summary_state)){
2573 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
2574 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
2575 } else {
2576 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
2577 }
2578 }
2579 std::string message = fmt::format(" Well {} converged in {} inner iterations ("
2580 "{} control/status switches).", this->name(), it, switch_count);
2581 if (relax_convergence) {
2582 message.append(fmt::format(" (A relaxed tolerance was used after {} iterations)",
2583 this->param_.strict_inner_iter_wells_));
2584 }
2585 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
2586
2587 } else {
2588 this->wellStatus_ = well_status_orig;
2589 this->operability_status_ = operability_orig;
2590 const std::string message = fmt::format(" Well {} did not converge in {} inner iterations ("
2591 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
2592 deferred_logger.debug(message);
2593 // add operability here as well ?
2594 }
2595 return converged;
2596 }
2597
2598 template<typename TypeTag>
2599 std::vector<typename StandardWell<TypeTag>::Scalar>
2601 computeCurrentWellRates(const Simulator& simulator,
2602 DeferredLogger& deferred_logger) const
2603 {
2604 // Calculate the rates that follow from the current primary variables.
2605 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.);
2606 const EvalWell& bhp = this->primary_variables_.eval(Bhp);
2607 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2608 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2609 const int cell_idx = this->well_cells_[perf];
2610 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2611 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
2612 getMobility(simulator, perf, mob, deferred_logger);
2613 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
2614 Scalar trans_mult(0.0);
2615 getTransMult(trans_mult, simulator, cell_idx);
2616 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2617 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
2618 this->getTw(Tw, perf, intQuants, trans_mult, wellstate_nupcol);
2619 PerforationRates<Scalar> perf_rates;
2620 computePerfRate(intQuants, mob, bhp.value(), Tw, perf, allow_cf,
2621 cq_s, perf_rates, deferred_logger);
2622 for (int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2623 well_q_s[comp] += cq_s[comp];
2624 }
2625 }
2626 const auto& comm = this->parallel_well_info_.communication();
2627 if (comm.size() > 1)
2628 {
2629 comm.sum(well_q_s.data(), well_q_s.size());
2630 }
2631 return well_q_s;
2632 }
2633
2634
2635
2636 template <typename TypeTag>
2637 std::vector<typename StandardWell<TypeTag>::Scalar>
2639 getPrimaryVars() const
2640 {
2641 const int num_pri_vars = this->primary_variables_.numWellEq();
2642 std::vector<Scalar> retval(num_pri_vars);
2643 for (int ii = 0; ii < num_pri_vars; ++ii) {
2644 retval[ii] = this->primary_variables_.value(ii);
2645 }
2646 return retval;
2647 }
2648
2649
2650
2651
2652
2653 template <typename TypeTag>
2654 int
2656 setPrimaryVars(typename std::vector<Scalar>::const_iterator it)
2657 {
2658 const int num_pri_vars = this->primary_variables_.numWellEq();
2659 for (int ii = 0; ii < num_pri_vars; ++ii) {
2660 this->primary_variables_.setValue(ii, it[ii]);
2661 }
2662 return num_pri_vars;
2663 }
2664
2665
2666 template <typename TypeTag>
2667 void
2669 getScaledWellFractions(std::vector<Scalar>& scaled_fractions,
2670 DeferredLogger& deferred_logger) const
2671 {
2672 this->primary_variables_.scaledWellFractions(scaled_fractions, deferred_logger);
2673 }
2674
2675
2676 template <typename TypeTag>
2679 connectionRateEnergy(const std::vector<EvalWell>& cq_s,
2680 const IntensiveQuantities& intQuants,
2681 DeferredLogger& deferred_logger) const
2682 {
2683 auto fs = intQuants.fluidState();
2684 Eval result = 0;
2685 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2686 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2687 continue;
2688 }
2689
2690 // convert to reservoir conditions
2691 EvalWell cq_r_thermal{0.};
2692 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2693 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2694 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2695 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2696 } else {
2697 // remove dissolved gas and vapporized oil
2698 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2699 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2700 // q_os = q_or * b_o + rv * q_gr * b_g
2701 // q_gs = q_gr * g_g + rs * q_or * b_o
2702 // q_gr = 1 / (b_g * d) * (q_gs - rs * q_os)
2703 // d = 1.0 - rs * rv
2704 const EvalWell d = this->extendEval(1.0 - fs.Rv() * fs.Rs());
2705 if (d <= 0.0) {
2706 deferred_logger.debug(
2707 fmt::format("Problematic d value {} obtained for well {}"
2708 " during calculateSinglePerf with rs {}"
2709 ", rv {}. Continue as if no dissolution (rs = 0) and"
2710 " vaporization (rv = 0) for this connection.",
2711 d, this->name(), fs.Rs(), fs.Rv()));
2712 cq_r_thermal = cq_s[activeCompIdx] / this->extendEval(fs.invB(phaseIdx));
2713 } else {
2714 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2715 cq_r_thermal = (cq_s[gasCompIdx] -
2716 this->extendEval(fs.Rs()) * cq_s[oilCompIdx]) /
2717 (d * this->extendEval(fs.invB(phaseIdx)) );
2718 } else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2719 // q_or = 1 / (b_o * d) * (q_os - rv * q_gs)
2720 cq_r_thermal = (cq_s[oilCompIdx] - this->extendEval(fs.Rv()) *
2721 cq_s[gasCompIdx]) /
2722 (d * this->extendEval(fs.invB(phaseIdx)) );
2723 }
2724 }
2725 }
2726
2727 // change temperature for injecting fluids
2728 if (this->isInjector() && !this->wellIsStopped() && cq_r_thermal > 0.0){
2729 // only handles single phase injection now
2730 assert(this->well_ecl_.injectorType() != InjectorType::MULTI);
2731 fs.setTemperature(this->well_ecl_.inj_temperature());
2732 typedef typename std::decay<decltype(fs)>::type::ValueType FsValueType;
2733 typename FluidSystem::template ParameterCache<FsValueType> paramCache;
2734 const unsigned pvtRegionIdx = intQuants.pvtRegionIndex();
2735 paramCache.setRegionIndex(pvtRegionIdx);
2736 paramCache.updatePhase(fs, phaseIdx);
2737
2738 const auto& rho = FluidSystem::density(fs, paramCache, phaseIdx);
2739 fs.setDensity(phaseIdx, rho);
2740 const auto& h = FluidSystem::enthalpy(fs, paramCache, phaseIdx);
2741 fs.setEnthalpy(phaseIdx, h);
2742 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2743 result += getValue(cq_r_thermal);
2744 } else if (cq_r_thermal > 0.0) {
2745 cq_r_thermal *= getValue(fs.enthalpy(phaseIdx)) * getValue(fs.density(phaseIdx));
2746 result += Base::restrictEval(cq_r_thermal);
2747 } else {
2748 // compute the thermal flux
2749 cq_r_thermal *= this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2750 result += Base::restrictEval(cq_r_thermal);
2751 }
2752 }
2753
2754 return result * this->well_efficiency_factor_;
2755 }
2756
2757 template <typename TypeTag>
2760 maxPerfPress(const Simulator& simulator) const {
2761 Scalar max_pressure = 0.0;
2762 for (int perf = 0; perf < this->number_of_local_perforations_; ++perf) {
2763 const int cell_idx = this->well_cells_[perf];
2764 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2765 const auto& fs = int_quants.fluidState();
2766 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2767 max_pressure = std::max(max_pressure, pressure_cell);
2768 }
2769 const auto& comm = this->parallel_well_info_.communication();
2770 if (comm.size() > 1) {
2771 max_pressure = comm.max(max_pressure);
2772 }
2773 return max_pressure;
2774 }
2775
2776} // namespace Opm
2777
2778#endif
#define OPM_DEFLOG_THROW(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:47
#define OPM_DEFLOG_PROBLEM(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:63
Definition: ConvergenceReport.hpp:38
Definition: DeferredLogger.hpp:57
void debug(const std::string &tag, const std::string &message)
Definition: GroupStateHelper.hpp:56
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:301
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:429
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:510
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:233
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:368
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:345
Definition: GroupState.hpp:41
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
Definition: RatioCalculator.hpp:38
Class handling assemble of the equation system for StandardWell.
Definition: StandardWellAssemble.hpp:44
Scalar pressure_diff(const unsigned perf) const
Returns pressure drop for a given perforation.
Definition: StandardWellConnections.hpp:101
StdWellConnections connections_
Connection level values.
Definition: StandardWellEval.hpp:120
PrimaryVariables primary_variables_
Primary variables for well.
Definition: StandardWellEval.hpp:114
Definition: StandardWell.hpp:55
void getScaledWellFractions(std::vector< Scalar > &scaled_fractions, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2669
EvalWell wpolymermw(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2090
std::vector< Scalar > computeWellPotentialWithTHP(const Simulator &ebosSimulator, const GroupStateHelperType &groupStateHelper, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1633
typename StdWellEval::EvalWell EvalWell
Definition: StandardWell.hpp:116
void updateWellStateFromPrimaryVariables(WellStateType &well_state, const SummaryState &summary_state, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:816
virtual ConvergenceReport getWellConvergence(const GroupStateHelperType &groupStateHelper, const std::vector< Scalar > &B_avg, const bool relax_tolerance) const override
check whether the well equations get converged for this well
Definition: StandardWell_impl.hpp:1232
WellConnectionProps computePropertiesForWellConnectionPressures(const Simulator &simulator, const WellStateType &well_state) const
Definition: StandardWell_impl.hpp:1181
std::optional< Scalar > computeBhpAtThpLimitProdWithAlq(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, const Scalar alq_value, bool iterate_if_no_solution) const override
Definition: StandardWell_impl.hpp:2296
typename StdWellEval::BVectorWell BVectorWell
Definition: StandardWell.hpp:117
void addWellContributions(SparseMatrixAdapter &mat) const override
Definition: StandardWell_impl.hpp:1987
std::vector< Scalar > getPrimaryVars() const override
Definition: StandardWell_impl.hpp:2639
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: StandardWell_impl.hpp:764
void updatePrimaryVariables(const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1887
void solveEqAndUpdateWellState(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1424
void computeWellConnectionDensitesPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const WellConnectionProps &props)
Definition: StandardWell_impl.hpp:1350
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2281
void addWellPressureEquations(PressureMatrix &mat, const BVector &x, const int pressureVarIndex, const bool use_well_weights, const WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:1995
void updateWaterMobilityWithPolymer(const Simulator &simulator, const int perf, std::vector< EvalWell > &mob_water, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:1921
bool iterateWellEqWithControl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:2403
std::vector< Scalar > computeCurrentWellRates(const Simulator &ebosSimulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:2601
void calculateSinglePerf(const Simulator &simulator, const int perf, WellStateType &well_state, std::vector< RateVector > &connectionRates, std::vector< EvalWell > &cq_s, EvalWell &water_flux_s, EvalWell &cq_s_zfrac_effective, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:510
void computeWellConnectionPressures(const Simulator &simulator, const GroupStateHelperType &groupStateHelper)
Definition: StandardWell_impl.hpp:1407
void updatePrimaryVariablesNewton(const BVectorWell &dwells, const bool stop_or_zero_rate_target, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:793
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const bool solving_with_zero_rate) override
Definition: StandardWell_impl.hpp:342
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
void computeWellPotentials(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) override
computing the well potentials for group control
Definition: StandardWell_impl.hpp:1805
StandardWell(const Well &well, const ParallelWellInfo< Scalar > &pw_info, const int time_step, const ModelParameters &param, const RateConverterType &rate_converter, const int pvtRegionIdx, const int num_conservation_quantities, const int num_phases, const int index_of_well, const std::vector< PerforationData< Scalar > > &perf_data)
Definition: StandardWell_impl.hpp:53
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: StandardWell_impl.hpp:2370
typename StdWellEval::StdWellConnections::Properties WellConnectionProps
Definition: StandardWell.hpp:276
void computeWellRatesWithBhpIterations(const Simulator &ebosSimulator, const Scalar &bhp, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const override
Definition: StandardWell_impl.hpp:1562
void updateConnectionRatePolyMW(const EvalWell &cq_s_poly, const IntensiveQuantities &int_quants, const WellStateType &well_state, const int perf, std::vector< RateVector > &connectionRates, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2239
void computeWellRatesWithBhp(const Simulator &ebosSimulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1514
void updateIPRImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:932
void getMobility(const Simulator &simulator, const int perf, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:708
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_indx) const
Definition: StandardWell_impl.hpp:688
void updateIPR(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:840
void handleInjectivityEquations(const Simulator &simulator, const WellStateType &well_state, const int perf, const EvalWell &water_flux_s, DeferredLogger &deferred_logger)
Definition: StandardWell_impl.hpp:2173
virtual void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: StandardWell_impl.hpp:1462
void checkConvergenceExtraEqs(const std::vector< Scalar > &res, ConvergenceReport &report) const
Definition: StandardWell_impl.hpp:2220
void computeWellRatesWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1788
typename StdWellEval::Eval Eval
Definition: StandardWell.hpp:115
Scalar computeWellRatesAndBhpWithThpAlqProd(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, std::vector< Scalar > &potentials, Scalar alq) const
Definition: StandardWell_impl.hpp:1758
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1170
bool computeWellPotentialsImplicit(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) const
Definition: StandardWell_impl.hpp:1669
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: StandardWell_impl.hpp:1494
Scalar maxPerfPress(const Simulator &simulator) const override
Definition: StandardWell_impl.hpp:2760
bool iterateWellEqWithSwitching(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, const bool fixed_control, const bool fixed_status, const bool solving_with_zero_rate) override
Definition: StandardWell_impl.hpp:2468
void assembleWellEqWithoutIterationImpl(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const bool solving_with_zero_rate)
Definition: StandardWell_impl.hpp:369
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: StandardWell_impl.hpp:1128
EvalWell pskin(const Scalar throughput, const EvalWell &water_velocity, const EvalWell &poly_inj_conc, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2046
void computePerfRate(const IntensiveQuantities &intQuants, const std::vector< Value > &mob, const Value &bhp, const std::vector< Value > &Tw, const int perf, const bool allow_cf, std::vector< Value > &cq_s, PerforationRates< Scalar > &perf_rates, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:94
static constexpr int numWellConservationEq
Definition: StandardWell.hpp:92
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: StandardWell_impl.hpp:2656
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: StandardWell_impl.hpp:2119
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &simulator, DeferredLogger &deferred_logger) override
Definition: StandardWell_impl.hpp:1009
EvalWell pskinwater(const Scalar throughput, const EvalWell &water_velocity, DeferredLogger &deferred_logger) const
Definition: StandardWell_impl.hpp:2015
void handleInjectivityRate(const Simulator &simulator, const int perf, std::vector< EvalWell > &cq_s) const
Definition: StandardWell_impl.hpp:2150
virtual void init(const std::vector< Scalar > &depth_arg, const Scalar gravity_arg, const std::vector< Scalar > &B_avg, const bool changed_to_open_this_step) override
Definition: StandardWell_impl.hpp:77
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const override
Definition: StandardWell_impl.hpp:1275
void calculateExplicitQuantities(const Simulator &simulator, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1449
Scalar getRefDensity() const override
Definition: StandardWell_impl.hpp:1910
void checkOperabilityUnderTHPLimit(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper) override
Definition: StandardWell_impl.hpp:1078
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: StandardWell_impl.hpp:1872
EvalWell getQs(const int compIdx) const
Returns scaled rate for a component.
Class for computing BHP limits.
Definition: WellBhpThpCalculator.hpp:41
Scalar calculateThpFromBhp(const std::vector< Scalar > &rates, const Scalar bhp, const Scalar rho, const std::optional< Scalar > &alq, const Scalar thp_limit, DeferredLogger &deferred_logger) const
Calculates THP from BHP.
std::optional< Scalar > computeBhpAtThpLimitProd(const std::function< std::vector< Scalar >(const Scalar)> &frates, const SummaryState &summary_state, const Scalar maxPerfPress, const Scalar rho, const Scalar alq_value, const Scalar thp_limit, DeferredLogger &deferred_logger) const
Compute BHP from THP limit for a producer.
Scalar mostStrictBhpFromBhpLimits(const SummaryState &summaryState) const
Obtain the most strict BHP from BHP limits.
std::optional< Scalar > computeBhpAtThpLimitInj(const std::function< std::vector< Scalar >(const Scalar)> &frates, const SummaryState &summary_state, const Scalar rho, const Scalar flo_rel_tol, const int max_iteration, const bool throwOnError, DeferredLogger &deferred_logger) const
Compute BHP from THP limit for an injector.
Definition: WellConvergence.hpp:38
const int num_conservation_quantities_
Definition: WellInterfaceGeneric.hpp:486
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:474
void onlyKeepBHPandTHPcontrols(const SummaryState &summary_state, WellStateType &well_state, Well::InjectionControls &inj_controls, Well::ProductionControls &prod_controls) const
void resetDampening()
Definition: WellInterfaceGeneric.hpp:412
std::pair< bool, bool > computeWellPotentials(std::vector< Scalar > &well_potentials, const WellStateType &well_state)
Definition: WellInterfaceIndices.hpp:34
Definition: WellInterface.hpp:79
bool solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:735
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:84
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2231
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: WellInterface.hpp:100
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2244
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:89
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:99
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:116
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:86
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:88
GetPropType< TypeTag, Properties::SparseMatrixAdapter > SparseMatrixAdapter
Definition: WellInterface.hpp:91
Definition: WellProdIndexCalculator.hpp:37
Scalar connectionProdIndStandard(const std::size_t connIdx, const Scalar connMobility) const
Definition: WellState.hpp:68
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:315
std::vector< Scalar > & wellRates(std::size_t well_index)
One rate per well and phase.
Definition: WellState.hpp:280
@ NONE
Definition: DeferredLogger.hpp:46
Definition: blackoilbioeffectsmodules.hh:45
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Static data associated with a well perforation.
Definition: PerforationData.hpp:30
Definition: PerforationData.hpp:72
Scalar dis_gas
Definition: PerforationData.hpp:73
Scalar vap_wat
Definition: PerforationData.hpp:76
Scalar vap_oil
Definition: PerforationData.hpp:75
Scalar dis_gas_in_water
Definition: PerforationData.hpp:74