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