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