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