MultisegmentWell_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2017 SINTEF Digital, Mathematics and Cybernetics.
3 Copyright 2017 Statoil ASA.
4
5 This file is part of the Open Porous Media project (OPM).
6
7 OPM is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 OPM is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with OPM. If not, see <http://www.gnu.org/licenses/>.
19*/
20
21// Improve IDE experience
22#ifndef OPM_MULTISEGMENTWELL_IMPL_HEADER_INCLUDED
23#define OPM_MULTISEGMENTWELL_IMPL_HEADER_INCLUDED
24
25#ifndef OPM_MULTISEGMENTWELL_HEADER_INCLUDED
26#include <config.h>
28#endif
29
30#include <opm/common/Exceptions.hpp>
31#include <opm/common/OpmLog/OpmLog.hpp>
32
33#include <opm/input/eclipse/Schedule/MSW/Segment.hpp>
34#include <opm/input/eclipse/Schedule/MSW/Valve.hpp>
35#include <opm/input/eclipse/Schedule/MSW/WellSegments.hpp>
36#include <opm/input/eclipse/Schedule/Well/Connection.hpp>
37#include <opm/input/eclipse/Schedule/Well/WellConnections.hpp>
38
39#include <opm/input/eclipse/Units/Units.hpp>
40
41#include <opm/material/densead/EvaluationFormat.hpp>
42
47
48#include <algorithm>
49#include <cstddef>
50#include <limits>
51#include <string>
52
53#if COMPILE_GPU_BRIDGE && (HAVE_CUDA || HAVE_OPENCL)
55#endif
56
57namespace Opm
58{
59
60
61 template <typename TypeTag>
63 MultisegmentWell(const Well& well,
64 const ParallelWellInfo<Scalar>& pw_info,
65 const int time_step,
66 const ModelParameters& param,
67 const RateConverterType& rate_converter,
68 const int pvtRegionIdx,
69 const int num_conservation_quantities,
70 const int num_phases,
71 const int index_of_well,
72 const std::vector<PerforationData<Scalar>>& perf_data)
73 : Base(well, pw_info, time_step, param, rate_converter, pvtRegionIdx, num_conservation_quantities, num_phases, index_of_well, perf_data)
74 , MSWEval(static_cast<WellInterfaceIndices<FluidSystem,Indices>&>(*this), pw_info)
75 , regularize_(false)
76 , segment_fluid_initial_(this->numberOfSegments(), std::vector<Scalar>(this->num_conservation_quantities_, 0.0))
77 , segment_initial_energy_(this->numberOfSegments(), 0.0)
78 , segment_fluid_state_(this->numberOfSegments(), SegmentFluidState<EvalWell>{})
79 , segment_pvt_(this->numberOfSegments())
80 {
81 // not handling solvent or polymer for now with multisegment well
82 if constexpr (has_solvent) {
83 OPM_THROW(std::runtime_error, "solvent is not supported by multisegment well yet");
84 }
85
86 if constexpr (has_polymer) {
87 OPM_THROW(std::runtime_error, "polymer is not supported by multisegment well yet");
88 }
89
90 if constexpr (Base::has_foam) {
91 OPM_THROW(std::runtime_error, "foam is not supported by multisegment well yet");
92 }
93
94 if constexpr (Base::has_brine) {
95 OPM_THROW(std::runtime_error, "brine is not supported by multisegment well yet");
96 }
97
98 if constexpr (Base::has_watVapor) {
99 OPM_THROW(std::runtime_error, "water evaporation is not supported by multisegment well yet");
100 }
101
102 if constexpr (Base::has_micp) {
103 OPM_THROW(std::runtime_error, "MICP is not supported by multisegment well yet");
104 }
105
106 if(this->rsRvInj() > 0) {
107 OPM_THROW(std::runtime_error,
108 "dissolved gas/ vapporized oil in injected oil/gas not supported by multisegment well yet."
109 " \n See (WCONINJE item 10 / WCONHIST item 8)");
110 }
111
112 this->thp_update_iterations = true;
113 }
114
115
116
117
118
119 template <typename TypeTag>
120 void
122 init(const std::vector<Scalar>& depth_arg,
123 const Scalar gravity_arg,
124 const std::vector< Scalar >& B_avg,
125 const bool changed_to_open_this_step)
126 {
127 Base::init(depth_arg, gravity_arg, B_avg, changed_to_open_this_step);
128
129 // TODO: for StandardWell, we need to update the perf depth here using depth_arg.
130 // for MultisegmentWell, it is much more complicated.
131 // It can be specified directly, it can be calculated from the segment depth,
132 // it can also use the cell center, which is the same for StandardWell.
133 // For the last case, should we update the depth with the depth_arg? For the
134 // future, it can be a source of wrong result with Multisegment well.
135 // An indicator from the opm-parser should indicate what kind of depth we should use here.
136
137 // \Note: we do not update the depth here. And it looks like for now, we only have the option to use
138 // specified perforation depth
139 this->initMatrixAndVectors(this->parallel_well_info_);
140
141 // calculate the depth difference between the perforations and the perforated grid block
142 for (int local_perf_index = 0; local_perf_index < this->number_of_local_perforations_; ++local_perf_index) {
143 // This variable loops over the number_of_local_perforations_ of *this* process, hence it is *local*.
144 const int cell_idx = this->well_cells_[local_perf_index];
145 // Here we need to access the perf_depth_ at the global perforation index though!
146 this->cell_perforation_depth_diffs_[local_perf_index] = depth_arg[cell_idx] - this->perf_depth_[this->parallel_well_info_.localPerfToActivePerf(local_perf_index)];
147 }
148 }
149
150
151
152
153
154 template <typename TypeTag>
155 void
157 updatePrimaryVariables(const GroupStateHelperType& groupStateHelper)
158 {
159 const auto& well_state = groupStateHelper.wellState();
160 const bool stop_or_zero_rate_target = this->stoppedOrZeroRateTarget(groupStateHelper);
161 this->primary_variables_.update(well_state, stop_or_zero_rate_target);
162 }
163
164
165
166
167
168
169 template <typename TypeTag>
170 void
173 {
174 this->scaleSegmentRatesWithWellRates(this->segments_.inlets(),
175 this->segments_.perforations(),
176 well_state);
177 this->scaleSegmentPressuresWithBhp(well_state);
178 }
179
180 template <typename TypeTag>
181 void
184 const GroupStateHelperType& groupStateHelper,
185 WellStateType& well_state) const
186 {
187 Base::updateWellStateWithTarget(simulator, groupStateHelper, well_state);
188 // scale segment rates based on the wellRates
189 // and segment pressure based on bhp
190 this->scaleSegmentRatesWithWellRates(this->segments_.inlets(),
191 this->segments_.perforations(),
192 well_state);
193 this->scaleSegmentPressuresWithBhp(well_state);
194 }
195
196
197
198
199 template <typename TypeTag>
202 getWellConvergence(const GroupStateHelperType& groupStateHelper,
203 const std::vector<Scalar>& B_avg,
204 const bool relax_tolerance) const
205 {
206 const auto& well_state = groupStateHelper.wellState();
207 auto& deferred_logger = groupStateHelper.deferredLogger();
208 return this->MSWEval::getWellConvergence(well_state,
209 B_avg,
210 deferred_logger,
211 this->param_.max_residual_allowed_,
212 this->param_.tolerance_wells_,
213 this->param_.relaxed_tolerance_flow_well_,
214 this->param_.tolerance_pressure_ms_wells_,
215 this->param_.relaxed_tolerance_pressure_ms_well_,
216 relax_tolerance,
217 this->wellIsStopped());
218
219 }
220
221
222
223
224
225 template <typename TypeTag>
226 void
228 apply(const BVector& x, BVector& Ax) const
229 {
230 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
231 return;
232 }
233
234 if (this->param_.matrix_add_well_contributions_) {
235 // Contributions are already in the matrix itself
236 return;
237 }
238
239 this->linSys_.apply(x, Ax);
240 }
241
242
243
244
245
246 template <typename TypeTag>
247 void
249 apply(BVector& r) const
250 {
251 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
252 return;
253 }
254
255 this->linSys_.apply(r);
256 }
257
258
259
260 template <typename TypeTag>
261 void
264 const BVector& x,
265 const GroupStateHelperType& groupStateHelper,
266 WellStateType& well_state)
267 {
268 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) {
269 return;
270 }
271
272 auto& deferred_logger = groupStateHelper.deferredLogger();
273 try {
274 BVectorWell xw(1);
275 this->linSys_.recoverSolutionWell(x, xw);
276
277 updateWellState(simulator, xw, groupStateHelper, well_state);
278 }
279 catch (const NumericalProblem& exp) {
280 // Add information about the well and log to deferred logger
281 // (Logging done inside of recoverSolutionWell() (i.e. by UMFpack) will only be seen if
282 // this is the process with rank zero)
283 deferred_logger.problem("In MultisegmentWell::recoverWellSolutionAndUpdateWellState for well "
284 + this->name() +": "+exp.what());
285 throw;
286 }
287 }
288
289
290
291
292
293 template <typename TypeTag>
294 void
296 computeWellPotentials(const Simulator& simulator,
297 const WellStateType& well_state,
298 const GroupStateHelperType& groupStateHelper,
299 std::vector<Scalar>& well_potentials)
300 {
301 auto& deferred_logger = groupStateHelper.deferredLogger();
302 const auto [compute_potential, bhp_controlled_well] =
304
305 if (!compute_potential) {
306 return;
307 }
308
309 debug_cost_counter_ = 0;
310 bool converged_implicit = false;
311 if (this->param_.local_well_solver_control_switching_) {
312 converged_implicit = computeWellPotentialsImplicit(simulator, groupStateHelper, well_potentials);
313 if (!converged_implicit) {
314 deferred_logger.debug("Implicit potential calculations failed for well "
315 + this->name() + ", reverting to original aproach.");
316 }
317 }
318 if (!converged_implicit) {
319 // does the well have a THP related constraint?
320 const auto& summaryState = simulator.vanguard().summaryState();
321 if (!Base::wellHasTHPConstraints(summaryState) || bhp_controlled_well) {
322 computeWellRatesAtBhpLimit(simulator, groupStateHelper, well_potentials);
323 } else {
324 well_potentials = computeWellPotentialWithTHP(
325 well_state, simulator, groupStateHelper);
326 }
327 }
328 deferred_logger.debug("Cost in iterations of finding well potential for well "
329 + this->name() + ": " + std::to_string(debug_cost_counter_));
330
331 this->checkNegativeWellPotentials(well_potentials,
332 this->param_.check_well_operability_,
333 deferred_logger);
334 }
335
336
337
338
339 template<typename TypeTag>
340 void
343 const GroupStateHelperType& groupStateHelper,
344 std::vector<Scalar>& well_flux) const
345 {
346 if (this->well_ecl_.isInjector()) {
347 const auto controls = this->well_ecl_.injectionControls(simulator.vanguard().summaryState());
348 computeWellRatesWithBhpIterations(simulator, controls.bhp_limit, groupStateHelper, well_flux);
349 } else {
350 const auto controls = this->well_ecl_.productionControls(simulator.vanguard().summaryState());
351 computeWellRatesWithBhpIterations(simulator, controls.bhp_limit, groupStateHelper, well_flux);
352 }
353 }
354
355 template<typename TypeTag>
356 void
358 computeWellRatesWithBhp(const Simulator& simulator,
359 const Scalar& bhp,
360 std::vector<Scalar>& well_flux,
361 DeferredLogger& deferred_logger) const
362 {
363 const int np = this->number_of_phases_;
364
365 well_flux.resize(np, 0.0);
366 const bool allow_cf = this->getAllowCrossFlow();
367 const int nseg = this->numberOfSegments();
368 const WellStateType& well_state = simulator.problem().wellModel().wellState();
369 const auto& ws = well_state.well(this->indexOfWell());
370 auto segments_copy = ws.segments;
371 segments_copy.scale_pressure(bhp);
372 const auto& segment_pressure = segments_copy.pressure;
373 for (int seg = 0; seg < nseg; ++seg) {
374 for (const int perf : this->segments_.perforations()[seg]) {
375 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
376 if (local_perf_index < 0) // then the perforation is not on this process
377 continue;
378 const int cell_idx = this->well_cells_[local_perf_index];
379 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
380 // flux for each perforation
381 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.);
382 getMobility(simulator, local_perf_index, mob, deferred_logger);
383 Scalar trans_mult(0.0);
384 getTransMult(trans_mult, simulator, cell_idx);
385 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
386 std::vector<Scalar> Tw(this->num_conservation_quantities_,
387 this->well_index_[local_perf_index] * trans_mult);
388 this->getTw(Tw, local_perf_index, intQuants, trans_mult, wellstate_nupcol);
389 const Scalar seg_pressure = segment_pressure[seg];
390 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.);
391 Scalar perf_press = 0.0;
392 PerforationRates<Scalar> perf_rates;
393 computePerfRate(intQuants, mob, Tw, seg, perf, seg_pressure,
394 allow_cf, cq_s, perf_press, perf_rates, deferred_logger);
395
396 for(int p = 0; p < np; ++p) {
397 well_flux[FluidSystem::activeCompToActivePhaseIdx(p)] += cq_s[p];
398 }
399 }
400 }
401 this->parallel_well_info_.communication().sum(well_flux.data(), well_flux.size());
402 }
403
404
405 template<typename TypeTag>
406 void
409 const Scalar& bhp,
410 const GroupStateHelperType& groupStateHelper,
411 std::vector<Scalar>& well_flux) const
412 {
413 OPM_TIMEFUNCTION();
414 // creating a copy of the well itself, to avoid messing up the explicit information
415 // during this copy, the only information not copied properly is the well controls
416 MultisegmentWell<TypeTag> well_copy(*this);
417 well_copy.resetDampening();
418
419 well_copy.debug_cost_counter_ = 0;
420
421 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
422 // store a copy of the well state, we don't want to update the real well state
423 WellStateType well_state_copy = groupStateHelper_copy.wellState();
424 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
425 auto& ws = well_state_copy.well(this->index_of_well_);
426
427 // Get the current controls.
428 const auto& summary_state = simulator.vanguard().summaryState();
429 auto inj_controls = well_copy.well_ecl_.isInjector()
430 ? well_copy.well_ecl_.injectionControls(summary_state)
431 : Well::InjectionControls(0);
432 auto prod_controls = well_copy.well_ecl_.isProducer()
433 ? well_copy.well_ecl_.productionControls(summary_state) :
434 Well::ProductionControls(0);
435
436 // Set current control to bhp, and bhp value in state, modify bhp limit in control object.
437 if (well_copy.well_ecl_.isInjector()) {
438 inj_controls.bhp_limit = bhp;
439 ws.injection_cmode = Well::InjectorCMode::BHP;
440 } else {
441 prod_controls.bhp_limit = bhp;
442 ws.production_cmode = Well::ProducerCMode::BHP;
443 }
444 ws.bhp = bhp;
445 well_copy.scaleSegmentPressuresWithBhp(well_state_copy);
446
447 // initialized the well rates with the potentials i.e. the well rates based on bhp
448 const int np = this->number_of_phases_;
449 bool trivial = true;
450 for (int phase = 0; phase < np; ++phase){
451 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
452 }
453 if (!trivial) {
454 const Scalar sign = well_copy.well_ecl_.isInjector() ? 1.0 : -1.0;
455 for (int phase = 0; phase < np; ++phase) {
456 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
457 }
458 }
459 well_copy.scaleSegmentRatesWithWellRates(this->segments_.inlets(),
460 this->segments_.perforations(),
461 well_state_copy);
462
463 well_copy.calculateExplicitQuantities(simulator, groupStateHelper_copy);
464 const double dt = simulator.timeStepSize();
465 // iterate to get a solution at the given bhp.
466 well_copy.iterateWellEqWithControl(simulator, dt, inj_controls, prod_controls, groupStateHelper_copy,
467 well_state_copy);
468
469 // compute the potential and store in the flux vector.
470 well_flux.clear();
471 well_flux.resize(np, 0.0);
472 for (int compIdx = 0; compIdx < this->num_conservation_quantities_; ++compIdx) {
473 const EvalWell rate = well_copy.primary_variables_.getQs(compIdx);
474 well_flux[FluidSystem::activeCompToActivePhaseIdx(compIdx)] = rate.value();
475 }
476 debug_cost_counter_ += well_copy.debug_cost_counter_;
477 }
478
479
480
481 template<typename TypeTag>
482 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
485 const Simulator& simulator,
486 const GroupStateHelperType& groupStateHelper) const
487 {
488 auto& deferred_logger = groupStateHelper.deferredLogger();
489 std::vector<Scalar> potentials(this->number_of_phases_, 0.0);
490 const auto& summary_state = simulator.vanguard().summaryState();
491
492 const auto& well = this->well_ecl_;
493 if (well.isInjector()) {
494 auto bhp_at_thp_limit = computeBhpAtThpLimitInj(simulator, groupStateHelper, summary_state);
495 if (bhp_at_thp_limit) {
496 const auto& controls = well.injectionControls(summary_state);
497 const Scalar bhp = std::min(*bhp_at_thp_limit,
498 static_cast<Scalar>(controls.bhp_limit));
499 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
500 deferred_logger.debug("Converged thp based potential calculation for well "
501 + this->name() + ", at bhp = " + std::to_string(bhp));
502 } else {
503 deferred_logger.warning("FAILURE_GETTING_CONVERGED_POTENTIAL",
504 "Failed in getting converged thp based potential calculation for well "
505 + this->name() + ". Instead the bhp based value is used");
506 const auto& controls = well.injectionControls(summary_state);
507 const Scalar bhp = controls.bhp_limit;
508 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
509 }
510 } else {
511 auto bhp_at_thp_limit = computeBhpAtThpLimitProd(
512 well_state, simulator, groupStateHelper, summary_state);
513 if (bhp_at_thp_limit) {
514 const auto& controls = well.productionControls(summary_state);
515 const Scalar bhp = std::max(*bhp_at_thp_limit,
516 static_cast<Scalar>(controls.bhp_limit));
517 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
518 deferred_logger.debug("Converged thp based potential calculation for well "
519 + this->name() + ", at bhp = " + std::to_string(bhp));
520 } else {
521 deferred_logger.warning("FAILURE_GETTING_CONVERGED_POTENTIAL",
522 "Failed in getting converged thp based potential calculation for well "
523 + this->name() + ". Instead the bhp based value is used");
524 const auto& controls = well.productionControls(summary_state);
525 const Scalar bhp = controls.bhp_limit;
526 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, potentials);
527 }
528 }
529
530 return potentials;
531 }
532
533 template<typename TypeTag>
534 bool
537 const GroupStateHelperType& groupStateHelper,
538 std::vector<Scalar>& well_potentials) const
539 {
540 // Create a copy of the well.
541 // TODO: check if we can avoid taking multiple copies. Call from updateWellPotentials
542 // is allready a copy, but not from other calls.
543 MultisegmentWell<TypeTag> well_copy(*this);
544 well_copy.debug_cost_counter_ = 0;
545
546 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
547 // store a copy of the well state, we don't want to update the real well state
548 WellStateType well_state_copy = groupStateHelper_copy.wellState();
549 auto guard = groupStateHelper_copy.pushWellState(well_state_copy);
550 auto& ws = well_state_copy.well(this->index_of_well_);
551
552 // get current controls
553 const auto& summary_state = simulator.vanguard().summaryState();
554 auto inj_controls = well_copy.well_ecl_.isInjector()
555 ? well_copy.well_ecl_.injectionControls(summary_state)
556 : Well::InjectionControls(0);
557 auto prod_controls = well_copy.well_ecl_.isProducer()
558 ? well_copy.well_ecl_.productionControls(summary_state)
559 : Well::ProductionControls(0);
560
561 // prepare/modify well state and control
562 well_copy.onlyKeepBHPandTHPcontrols(summary_state, well_state_copy, inj_controls, prod_controls);
563
564 well_copy.scaleSegmentPressuresWithBhp(well_state_copy);
565
566 // initialize rates from previous potentials
567 const int np = this->number_of_phases_;
568 bool trivial = true;
569 for (int phase = 0; phase < np; ++phase){
570 trivial = trivial && (ws.well_potentials[phase] == 0.0) ;
571 }
572 if (!trivial) {
573 const Scalar sign = well_copy.well_ecl_.isInjector() ? 1.0 : -1.0;
574 for (int phase = 0; phase < np; ++phase) {
575 ws.surface_rates[phase] = sign * ws.well_potentials[phase];
576 }
577 }
578 well_copy.scaleSegmentRatesWithWellRates(this->segments_.inlets(),
579 this->segments_.perforations(),
580 well_state_copy);
581
582 well_copy.calculateExplicitQuantities(simulator, groupStateHelper_copy);
583 const double dt = simulator.timeStepSize();
584 // solve equations
585 bool converged = false;
586 if (this->well_ecl_.isProducer()) {
587 converged = well_copy.solveWellWithOperabilityCheck(
588 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy
589 );
590 } else {
591 converged = well_copy.iterateWellEqWithSwitching(
592 simulator, dt, inj_controls, prod_controls, groupStateHelper_copy, well_state_copy,
593 /*fixed_control=*/false,
594 /*fixed_status=*/false,
595 /*solving_with_zero_rate=*/false
596 );
597 }
598
599 // fetch potentials (sign is updated on the outside).
600 well_potentials.clear();
601 well_potentials.resize(np, 0.0);
602 for (int compIdx = 0; compIdx < this->num_conservation_quantities_; ++compIdx) {
603 const EvalWell rate = well_copy.primary_variables_.getQs(compIdx);
604 well_potentials[FluidSystem::activeCompToActivePhaseIdx(compIdx)] = rate.value();
605 }
606 debug_cost_counter_ += well_copy.debug_cost_counter_;
607 return converged;
608 }
609
610 template <typename TypeTag>
611 void
614 const GroupStateHelperType& groupStateHelper,
615 WellStateType& well_state)
616 {
617 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
618
619 // We assemble the well equations, then we check the convergence,
620 // which is why we do not put the assembleWellEq here.
621 try{
622 const BVectorWell dx_well = this->linSys_.solve();
623 updateWellState(simulator, dx_well, groupStateHelper, well_state);
624 }
625 catch(const NumericalProblem& exp) {
626 // Add information about the well and log to deferred logger
627 // (Logging done inside of solve() method will only be seen if
628 // this is the process with rank zero)
629 auto& deferred_logger = groupStateHelper.deferredLogger();
630 deferred_logger.problem("In MultisegmentWell::solveEqAndUpdateWellState for well "
631 + this->name() +": "+exp.what());
632 throw;
633 }
634 }
635
636
637
638
639
640 template <typename TypeTag>
641 void
644 {
645 // We call this function on every process for the number_of_local_perforations_ on that process
646 // Each process updates the pressure for his perforations
647 for (int local_perf_index = 0; local_perf_index < this->number_of_local_perforations_; ++local_perf_index) {
648 // This variable loops over the number_of_local_perforations_ of *this* process, hence it is *local*.
649
650 std::vector<Scalar> kr(this->number_of_phases_, 0.0);
651 std::vector<Scalar> density(this->number_of_phases_, 0.0);
652
653 const int cell_idx = this->well_cells_[local_perf_index];
654 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
655 const auto& fs = intQuants.fluidState();
656
657 Scalar sum_kr = 0.;
658
659 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
660 const int water_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::waterPhaseIdx);
661 kr[water_pos] = intQuants.relativePermeability(FluidSystem::waterPhaseIdx).value();
662 sum_kr += kr[water_pos];
663 density[water_pos] = fs.density(FluidSystem::waterPhaseIdx).value();
664 }
665
666 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
667 const int oil_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::oilPhaseIdx);
668 kr[oil_pos] = intQuants.relativePermeability(FluidSystem::oilPhaseIdx).value();
669 sum_kr += kr[oil_pos];
670 density[oil_pos] = fs.density(FluidSystem::oilPhaseIdx).value();
671 }
672
673 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
674 const int gas_pos = FluidSystem::canonicalToActivePhaseIdx(FluidSystem::gasPhaseIdx);
675 kr[gas_pos] = intQuants.relativePermeability(FluidSystem::gasPhaseIdx).value();
676 sum_kr += kr[gas_pos];
677 density[gas_pos] = fs.density(FluidSystem::gasPhaseIdx).value();
678 }
679
680 assert(sum_kr != 0.);
681
682 // calculate the average density
683 Scalar average_density = 0.;
684 for (int p = 0; p < this->number_of_phases_; ++p) {
685 average_density += kr[p] * density[p];
686 }
687 average_density /= sum_kr;
688
689 this->cell_perforation_pressure_diffs_[local_perf_index] = this->gravity_ * average_density * this->cell_perforation_depth_diffs_[local_perf_index];
690 }
691 }
692
693
694
695
696
697 template <typename TypeTag>
698 void
701 {
702 for (int seg = 0; seg < this->numberOfSegments(); ++seg) {
703 const EvalWell volume_ratio =
704 this->segments_.computeVolumeRatio(seg, segmentPvt(segment_fluid_state_[seg]),
705 this->primary_variables_, deferred_logger);
706 const Scalar surface_volume = getSegmentSurfaceVolume(seg, volume_ratio).value();
707 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
708 segment_fluid_initial_[seg][comp_idx] = surface_volume * this->primary_variables_.surfaceVolumeFraction(seg, comp_idx).value();
709 }
710 if constexpr (has_energy) {
711 segment_initial_energy_[seg] = computeSegmentEnergy<Scalar>(seg);
712 }
713 }
714 }
715
716
717
718
719
720 template <typename TypeTag>
721 void
723 updateWellState(const Simulator& simulator,
724 const BVectorWell& dwells,
725 const GroupStateHelperType& groupStateHelper,
726 WellStateType& well_state,
727 const Scalar relaxation_factor)
728 {
729 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
730
731 auto& deferred_logger = groupStateHelper.deferredLogger();
732
733 const Scalar dFLimit = this->param_.dwell_fraction_max_;
734 const Scalar max_pressure_change = this->param_.max_pressure_change_ms_wells_;
735 const bool stop_or_zero_rate_target =
736 this->stoppedOrZeroRateTarget(groupStateHelper);
737 this->primary_variables_.updateNewton(dwells,
738 relaxation_factor,
739 dFLimit,
740 stop_or_zero_rate_target,
741 max_pressure_change);
742
743 const auto& summary_state = simulator.vanguard().summaryState();
744 this->primary_variables_.copyToWellState(*this, getRefDensity(),
745 well_state,
746 summary_state,
747 deferred_logger);
748
749 {
750 auto& ws = well_state.well(this->index_of_well_);
751 this->segments_.copyPhaseDensities(ws.segments);
752 }
753 // For injectors in a co2 storage case or a thermal case
754 // we convert to reservoir rates using the well bhp and temperature
755 const bool isThermal = simulator.vanguard().eclState().getSimulationConfig().isThermal();
756 const bool co2store = simulator.vanguard().eclState().runspec().co2Storage();
757 Base::calculateReservoirRates( (isThermal || co2store), well_state.well(this->index_of_well_));
758 }
759
760
761
762
763
764 template <typename TypeTag>
765 void
768 const GroupStateHelperType& groupStateHelper)
769 {
770 auto& deferred_logger = groupStateHelper.deferredLogger();
771 updatePrimaryVariables(groupStateHelper);
772 computePerfCellPressDiffs(simulator);
773
774 // Refresh the fluid state before computing the initial inventory.
775 const auto info = this->getFirstPerfCellConditions(simulator);
776 updateSegmentFluidState(info, deferred_logger);
777 computeInitialSegmentInventory(deferred_logger);
778 }
779
780
781
782
783
784 template<typename TypeTag>
785 void
787 updateProductivityIndex(const Simulator& simulator,
788 const WellProdIndexCalculator<Scalar>& wellPICalc,
789 WellStateType& well_state,
790 DeferredLogger& deferred_logger) const
791 {
792 auto fluidState = [&simulator, this](const int local_perf_index)
793 {
794 const auto cell_idx = this->well_cells_[local_perf_index];
795 return simulator.model()
796 .intensiveQuantities(cell_idx, /*timeIdx=*/ 0).fluidState();
797 };
798
799 const int np = this->number_of_phases_;
800 auto setToZero = [np](Scalar* x) -> void
801 {
802 std::fill_n(x, np, 0.0);
803 };
804
805 auto addVector = [np](const Scalar* src, Scalar* dest) -> void
806 {
807 std::transform(src, src + np, dest, dest, std::plus<>{});
808 };
809
810 auto& ws = well_state.well(this->index_of_well_);
811 auto& perf_data = ws.perf_data;
812 auto* connPI = perf_data.prod_index.data();
813 auto* wellPI = ws.productivity_index.data();
814
815 setToZero(wellPI);
816
817 const auto preferred_phase = this->well_ecl_.getPreferredPhase();
818 auto subsetPerfID = 0;
819
820 for ( const auto& perf : *this->perf_data_){
821 auto allPerfID = perf.ecl_index;
822
823 auto connPICalc = [&wellPICalc, allPerfID](const Scalar mobility) -> Scalar
824 {
825 return wellPICalc.connectionProdIndStandard(allPerfID, mobility);
826 };
827
828 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
829 // The subsetPerfID loops over 0 .. this->perf_data_->size().
830 // *(this->perf_data_) contains info about the local processes only,
831 // hence subsetPerfID is a local perf id and we can call getMobility
832 // as well as fluidState directly with that.
833 getMobility(simulator, static_cast<int>(subsetPerfID), mob, deferred_logger);
834
835 const auto& fs = fluidState(subsetPerfID);
836 setToZero(connPI);
837
838 if (this->isInjector()) {
839 this->computeConnLevelInjInd(fs, preferred_phase, connPICalc,
840 mob, connPI, deferred_logger);
841 }
842 else { // Production or zero flow rate
843 this->computeConnLevelProdInd(fs, connPICalc, mob, connPI);
844 }
845
846 addVector(connPI, wellPI);
847
848 ++subsetPerfID;
849 connPI += np;
850 }
851
852 // Sum with communication in case of distributed well.
853 const auto& comm = this->parallel_well_info_.communication();
854 if (comm.size() > 1) {
855 comm.sum(wellPI, np);
856 }
857
858 assert (static_cast<int>(subsetPerfID) == this->number_of_local_perforations_ &&
859 "Internal logic error in processing connections for PI/II");
860 }
861
862
863
864
865
866 template<typename TypeTag>
869 connectionDensity(const int globalConnIdx,
870 [[maybe_unused]] const int openConnIdx) const
871 {
872 // Simple approximation: Mixture density at reservoir connection is
873 // mixture density at connection's segment.
874
875 const auto segNum = this->wellEcl()
876 .getConnections()[globalConnIdx].segment();
877
878 const auto segIdx = this->wellEcl()
879 .getSegments().segmentNumberToIndex(segNum);
880
881 return this->segments_.density(segIdx).value();
882 }
883
884
885
886
887
888 template<typename TypeTag>
889 void
892 {
893 if (this->number_of_local_perforations_ == 0) {
894 // If there are no open perforations on this process, there are no contributions to the jacobian.
895 return;
896 }
897 this->linSys_.extract(jacobian);
898 }
899
900
901 template<typename TypeTag>
902 void
905 const BVector& weights,
906 const int pressureVarIndex,
907 const bool use_well_weights,
908 const WellStateType& well_state) const
909 {
910 if (this->number_of_local_perforations_ == 0) {
911 // If there are no open perforations on this process, there are no contributions the cpr pressure matrix.
912 return;
913 }
914 // Add the pressure contribution to the cpr system for the well
915 this->linSys_.extractCPRPressureMatrix(jacobian,
916 weights,
917 pressureVarIndex,
918 use_well_weights,
919 *this,
920 this->SPres,
921 well_state);
922 }
923
924
925 template<typename TypeTag>
926 template<class Value>
927 void
929 computePerfRate(const Value& pressure_cell,
930 const Value& rs,
931 const Value& rv,
932 const std::vector<Value>& b_perfcells,
933 const std::vector<Value>& mob_perfcells,
934 const std::vector<Value>& Tw,
935 const int perf,
936 const Value& segment_pressure,
937 const Value& segment_density,
938 const bool& allow_cf,
939 const std::vector<Value>& cmix_s,
940 std::vector<Value>& cq_s,
941 Value& perf_press,
942 PerforationRates<Scalar>& perf_rates,
943 DeferredLogger& deferred_logger) const
944 {
945 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
946 if (local_perf_index < 0) // then the perforation is not on this process
947 return;
948
949 // pressure difference between the segment and the perforation
950 const Value perf_seg_press_diff = this->gravity() * segment_density *
951 this->segments_.local_perforation_depth_diff(local_perf_index);
952 // pressure difference between the perforation and the grid cell
953 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
954
955 // perforation pressure is the wellbore pressure corrected to perforation depth
956 // (positive sign due to convention in segments_.local_perforation_depth_diff() )
957 perf_press = segment_pressure + perf_seg_press_diff;
958
959 // cell pressure corrected to perforation depth
960 const Value cell_press_at_perf = pressure_cell - cell_perf_press_diff;
961
962 // Pressure drawdown (also used to determine direction of flow)
963 const Value drawdown = cell_press_at_perf - perf_press;
964
965 // producing perforations
966 if (drawdown > 0.0) {
967 // Do nothing if crossflow is not allowed
968 if (!allow_cf && this->isInjector()) {
969 return;
970 }
971
972 // compute component volumetric rates at standard conditions
973 for (int comp_idx = 0; comp_idx < this->numConservationQuantities(); ++comp_idx) {
974 const Value cq_p = - Tw[comp_idx] * (mob_perfcells[comp_idx] * drawdown);
975 cq_s[comp_idx] = b_perfcells[comp_idx] * cq_p;
976 }
977
978 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
979 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
980 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
981 const Value cq_s_oil = cq_s[oilCompIdx];
982 const Value cq_s_gas = cq_s[gasCompIdx];
983 cq_s[gasCompIdx] += rs * cq_s_oil;
984 cq_s[oilCompIdx] += rv * cq_s_gas;
985 }
986 } else { // injecting perforations
987 // Do nothing if crossflow is not allowed
988 if (!allow_cf && this->isProducer()) {
989 return;
990 }
991
992 // for injecting perforations, we use total mobility
993 Value total_mob = mob_perfcells[0];
994 for (int comp_idx = 1; comp_idx < this->numConservationQuantities(); ++comp_idx) {
995 total_mob += mob_perfcells[comp_idx];
996 }
997
998 // compute volume ratio between connection and at standard conditions
999 Value volume_ratio = 0.0;
1000 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1001 const unsigned waterCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
1002 volume_ratio += cmix_s[waterCompIdx] / b_perfcells[waterCompIdx];
1003 }
1004
1005 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1006 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1007 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1008
1009 // Incorporate RS/RV factors if both oil and gas active
1010 // TODO: not sure we use rs rv from the perforation cells when handling injecting perforations
1011 // basically, for injecting perforations, the wellbore is the upstreaming side.
1012 const Value d = 1.0 - rv * rs;
1013
1014 if (getValue(d) == 0.0) {
1015 OPM_DEFLOG_PROBLEM(NumericalProblem,
1016 fmt::format("Zero d value obtained for well {} "
1017 "during flux calculation with rs {} and rv {}",
1018 this->name(), rs, rv),
1019 deferred_logger);
1020 }
1021
1022 const Value tmp_oil = (cmix_s[oilCompIdx] - rv * cmix_s[gasCompIdx]) / d;
1023 volume_ratio += tmp_oil / b_perfcells[oilCompIdx];
1024
1025 const Value tmp_gas = (cmix_s[gasCompIdx] - rs * cmix_s[oilCompIdx]) / d;
1026 volume_ratio += tmp_gas / b_perfcells[gasCompIdx];
1027 } else { // not having gas and oil at the same time
1028 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
1029 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1030 volume_ratio += cmix_s[oilCompIdx] / b_perfcells[oilCompIdx];
1031 }
1032 if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1033 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1034 volume_ratio += cmix_s[gasCompIdx] / b_perfcells[gasCompIdx];
1035 }
1036 }
1037 // injecting connections total volumerates at standard conditions
1038 for (int componentIdx = 0; componentIdx < this->numConservationQuantities(); ++componentIdx) {
1039 const Value cqt_i = - Tw[componentIdx] * (total_mob * drawdown);
1040 Value cqt_is = cqt_i / volume_ratio;
1041 cq_s[componentIdx] = cmix_s[componentIdx] * cqt_is;
1042 }
1043 } // end for injection perforations
1044
1045 // calculating the perforation solution gas rate and solution oil rates
1046 if (this->isProducer()) {
1047 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1048 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1049 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1050 // TODO: the formulations here remain to be tested with cases with strong crossflow through production wells
1051 // s means standard condition, r means reservoir condition
1052 // q_os = q_or * b_o + rv * q_gr * b_g
1053 // q_gs = q_gr * g_g + rs * q_or * b_o
1054 // d = 1.0 - rs * rv
1055 // q_or = 1 / (b_o * d) * (q_os - rv * q_gs)
1056 // q_gr = 1 / (b_g * d) * (q_gs - rs * q_os)
1057
1058 const Scalar d = 1.0 - getValue(rv) * getValue(rs);
1059 // vaporized oil into gas
1060 // rv * q_gr * b_g = rv * (q_gs - rs * q_os) / d
1061 perf_rates.vap_oil = getValue(rv) * (getValue(cq_s[gasCompIdx]) - getValue(rs) * getValue(cq_s[oilCompIdx])) / d;
1062 // dissolved of gas in oil
1063 // rs * q_or * b_o = rs * (q_os - rv * q_gs) / d
1064 perf_rates.dis_gas = getValue(rs) * (getValue(cq_s[oilCompIdx]) - getValue(rv) * getValue(cq_s[gasCompIdx])) / d;
1065 }
1066 }
1067 }
1068
1069 template <typename TypeTag>
1070 template<class Value>
1071 void
1073 computePerfRate(const IntensiveQuantities& int_quants,
1074 const std::vector<Value>& mob_perfcells,
1075 const std::vector<Value>& Tw,
1076 const int seg,
1077 const int perf,
1078 const Value& segment_pressure,
1079 const bool& allow_cf,
1080 std::vector<Value>& cq_s,
1081 Value& perf_press,
1082 PerforationRates<Scalar>& perf_rates,
1083 DeferredLogger& deferred_logger) const
1084
1085 {
1086 auto obtain = [this](const Eval& value)
1087 {
1088 if constexpr (std::is_same_v<Value, Scalar>) {
1089 static_cast<void>(this); // suppress clang warning
1090 return getValue(value);
1091 } else {
1092 return this->extendEval(value);
1093 }
1094 };
1095 auto obtainN = [](const auto& value)
1096 {
1097 if constexpr (std::is_same_v<Value, Scalar>) {
1098 return getValue(value);
1099 } else {
1100 return value;
1101 }
1102 };
1103 const auto& fs = int_quants.fluidState();
1104
1105 const Value pressure_cell = obtain(this->getPerfCellPressure(fs));
1106 const Value rs = obtain(fs.Rs());
1107 const Value rv = obtain(fs.Rv());
1108
1109 // not using number_of_phases_ because of solvent
1110 std::vector<Value> b_perfcells(this->num_conservation_quantities_, 0.0);
1111
1112 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
1113 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1114 continue;
1115 }
1116
1117 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1118 b_perfcells[compIdx] = obtain(fs.invB(phaseIdx));
1119 }
1120
1121 std::vector<Value> cmix_s(this->numConservationQuantities(), 0.0);
1122 for (int comp_idx = 0; comp_idx < this->numConservationQuantities(); ++comp_idx) {
1123 cmix_s[comp_idx] = obtainN(this->primary_variables_.surfaceVolumeFraction(seg, comp_idx));
1124 }
1125
1126 this->computePerfRate(pressure_cell,
1127 rs,
1128 rv,
1129 b_perfcells,
1130 mob_perfcells,
1131 Tw,
1132 perf,
1133 segment_pressure,
1134 obtainN(this->segments_.density(seg)),
1135 allow_cf,
1136 cmix_s,
1137 cq_s,
1138 perf_press,
1139 perf_rates,
1140 deferred_logger);
1141 }
1142
1143 template <typename TypeTag>
1144 void
1146 computeSegmentFluidProperties(const Simulator& simulator, DeferredLogger& deferred_logger)
1147 {
1148 // Rebuild fluid states from the current primary variables before deriving segment
1149 // properties, so both use consistent PVT data.
1150 const FSInfo info = this->getFirstPerfCellConditions(simulator);
1151 updateSegmentFluidState(info, deferred_logger);
1152
1153 for (int seg = 0; seg < this->numberOfSegments(); ++seg) {
1154 segment_pvt_[seg] = segmentPvt(segment_fluid_state_[seg]);
1155 }
1156 this->segments_.computeFluidProperties(segment_pvt_,
1157 this->primary_variables_,
1158 deferred_logger);
1159 }
1160
1161 template <typename TypeTag>
1164 segmentPvt(const SegmentFluidState<EvalWell>& fluid_state) const
1165 {
1166 // Pressure and temperature are the same for all phases in the wellbore, so pick any
1167 // active one to read them from.
1168 const bool waterActive = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx);
1169 const bool oilActive = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx);
1170 const unsigned pressure_phase = waterActive ? FluidSystem::waterPhaseIdx
1171 : oilActive ? FluidSystem::oilPhaseIdx
1172 : FluidSystem::gasPhaseIdx;
1173
1174 SegmentPvt pvt;
1175 pvt.pressure = fluid_state.pressure(pressure_phase);
1176 pvt.temperature = fluid_state.temperature(pressure_phase);
1177 pvt.saltConcentration = fluid_state.saltConcentration();
1178 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
1179 if (FluidSystem::phaseIsActive(phaseIdx)) {
1180 pvt.invB[phaseIdx] = fluid_state.invB(phaseIdx);
1181 }
1182 }
1183 if constexpr (compositionSwitchEnabled) {
1184 pvt.Rs = fluid_state.Rs();
1185 pvt.Rv = fluid_state.Rv();
1186 }
1187 return pvt;
1188 }
1189
1190 template<typename TypeTag>
1191 template<class Value>
1192 void
1194 getTransMult(Value& trans_mult,
1195 const Simulator& simulator,
1196 const int cell_idx) const
1197 {
1198 auto obtain = [this](const Eval& value)
1199 {
1200 if constexpr (std::is_same_v<Value, Scalar>) {
1201 static_cast<void>(this); // suppress clang warning
1202 return getValue(value);
1203 } else {
1204 return this->extendEval(value);
1205 }
1206 };
1207 WellInterface<TypeTag>::getTransMult(trans_mult, simulator, cell_idx, obtain);
1208 }
1209
1210 template <typename TypeTag>
1211 template<class Value>
1212 void
1214 getMobility(const Simulator& simulator,
1215 const int local_perf_index,
1216 std::vector<Value>& mob,
1217 DeferredLogger& deferred_logger) const
1218 {
1219 auto obtain = [this](const Eval& value)
1220 {
1221 if constexpr (std::is_same_v<Value, Scalar>) {
1222 static_cast<void>(this); // suppress clang warning
1223 return getValue(value);
1224 } else {
1225 return this->extendEval(value);
1226 }
1227 };
1228
1229 WellInterface<TypeTag>::getMobility(simulator, local_perf_index, mob, obtain, deferred_logger);
1230
1231 if (this->isInjector() && this->well_ecl_.getInjMultMode() != Well::InjMultMode::NONE) {
1232 const auto perf_ecl_index = this->perforationData()[local_perf_index].ecl_index;
1233 const Connection& con = this->well_ecl_.getConnections()[perf_ecl_index];
1234 const int seg = this->segmentNumberToIndex(con.segment());
1235 // from the reference results, it looks like MSW uses segment pressure instead of BHP here
1236 // Note: this is against the documented definition.
1237 // we can change this depending on what we want
1238 const Scalar segment_pres = this->primary_variables_.getSegmentPressure(seg).value();
1239 const Scalar perf_seg_press_diff = this->gravity() * this->segments_.density(seg).value()
1240 * this->segments_.local_perforation_depth_diff(local_perf_index);
1241 const Scalar perf_press = segment_pres + perf_seg_press_diff;
1242 const Scalar multiplier = this->getInjMult(local_perf_index, segment_pres, perf_press, deferred_logger);
1243 for (std::size_t i = 0; i < mob.size(); ++i) {
1244 mob[i] *= multiplier;
1245 }
1246 }
1247 }
1248
1249
1250
1251 template<typename TypeTag>
1254 getRefDensity() const
1255 {
1256 return this->segments_.getRefDensity();
1257 }
1258
1259 template<typename TypeTag>
1260 void
1262 checkOperabilityUnderBHPLimit(const WellStateType& /*well_state*/,
1263 const Simulator& simulator,
1264 DeferredLogger& deferred_logger)
1265 {
1266 const auto& summaryState = simulator.vanguard().summaryState();
1267 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1268 // Crude but works: default is one atmosphere.
1269 // TODO: a better way to detect whether the BHP is defaulted or not
1270 const bool bhp_limit_not_defaulted = bhp_limit > 1.5 * unit::barsa;
1271 if ( bhp_limit_not_defaulted || !this->wellHasTHPConstraints(summaryState) ) {
1272 // if the BHP limit is not defaulted or the well does not have a THP limit
1273 // we need to check the BHP limit
1274 Scalar total_ipr_mass_rate = 0.0;
1275 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx)
1276 {
1277 if (!FluidSystem::phaseIsActive(phaseIdx)) {
1278 continue;
1279 }
1280
1281 const unsigned compIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
1282 const Scalar ipr_rate = this->ipr_a_[compIdx] - this->ipr_b_[compIdx] * bhp_limit;
1283
1284 const Scalar rho = FluidSystem::referenceDensity( phaseIdx, Base::pvtRegionIdx() );
1285 total_ipr_mass_rate += ipr_rate * rho;
1286 }
1287 if ( (this->isProducer() && total_ipr_mass_rate < 0.) || (this->isInjector() && total_ipr_mass_rate > 0.) ) {
1288 this->operability_status_.operable_under_only_bhp_limit = false;
1289 }
1290
1291 // checking whether running under BHP limit will violate THP limit
1292 if (this->operability_status_.operable_under_only_bhp_limit && this->wellHasTHPConstraints(summaryState)) {
1293 // option 1: calculate well rates based on the BHP limit.
1294 // option 2: stick with the above IPR curve
1295 // we use IPR here
1296 std::vector<Scalar> well_rates_bhp_limit;
1297 computeWellRatesWithBhp(simulator, bhp_limit, well_rates_bhp_limit, deferred_logger);
1298
1299 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1300 const Scalar thp = WellBhpThpCalculator(*this).calculateThpFromBhp(well_rates_bhp_limit,
1301 bhp_limit,
1302 this->getRefDensity(),
1303 this->wellEcl().alq_value(summaryState),
1304 thp_limit,
1305 deferred_logger);
1306 if ( (this->isProducer() && thp < thp_limit) || (this->isInjector() && thp > thp_limit) ) {
1307 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
1308 }
1309 }
1310 } else {
1311 // defaulted BHP and there is a THP constraint
1312 // default BHP limit is about 1 atm.
1313 // when applied the hydrostatic pressure correction dp,
1314 // most likely we get a negative value (bhp + dp)to search in the VFP table,
1315 // which is not desirable.
1316 // we assume we can operate under defaulted BHP limit and will violate the THP limit
1317 // when operating under defaulted BHP limit.
1318 this->operability_status_.operable_under_only_bhp_limit = true;
1319 this->operability_status_.obey_thp_limit_under_bhp_limit = false;
1320 }
1321 }
1322
1323
1324
1325 template<typename TypeTag>
1326 void
1328 updateIPR(const Simulator& simulator, DeferredLogger& deferred_logger) const
1329 {
1330 // TODO: not handling solvent related here for now
1331
1332 // initialize all the values to be zero to begin with
1333 std::ranges::fill(this->ipr_a_, 0.0);
1334 std::ranges::fill(this->ipr_b_, 0.0);
1335
1336 const int nseg = this->numberOfSegments();
1337 std::vector<Scalar> seg_dp(nseg, 0.0);
1338 for (int seg = 0; seg < nseg; ++seg) {
1339 // calculating the perforation rate for each perforation that belongs to this segment
1340 const Scalar dp = this->getSegmentDp(seg,
1341 this->segments_.density(seg).value(),
1342 seg_dp);
1343 seg_dp[seg] = dp;
1344 for (const int perf : this->segments_.perforations()[seg]) {
1345 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
1346 if (local_perf_index < 0) // then the perforation is not on this process
1347 continue;
1348 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
1349
1350 // TODO: maybe we should store the mobility somewhere, so that we only need to calculate it one per iteration
1351 getMobility(simulator, local_perf_index, mob, deferred_logger);
1352
1353 const int cell_idx = this->well_cells_[local_perf_index];
1354 const auto& int_quantities = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
1355 const auto& fs = int_quantities.fluidState();
1356 // pressure difference between the segment and the perforation
1357 const Scalar perf_seg_press_diff = this->segments_.getPressureDiffSegLocalPerf(seg, local_perf_index);
1358 // pressure difference between the perforation and the grid cell
1359 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
1360 const Scalar pressure_cell = this->getPerfCellPressure(fs).value();
1361
1362 // calculating the b for the connection
1363 std::vector<Scalar> b_perf(this->num_conservation_quantities_);
1364 for (std::size_t phase = 0; phase < FluidSystem::numPhases; ++phase) {
1365 if (!FluidSystem::phaseIsActive(phase)) {
1366 continue;
1367 }
1368 const unsigned comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phase));
1369 b_perf[comp_idx] = fs.invB(phase).value();
1370 }
1371
1372 // the pressure difference between the connection and BHP
1373 const Scalar h_perf = cell_perf_press_diff + perf_seg_press_diff + dp;
1374 const Scalar pressure_diff = pressure_cell - h_perf;
1375
1376 // do not take into consideration the crossflow here.
1377 if ( (this->isProducer() && pressure_diff < 0.) || (this->isInjector() && pressure_diff > 0.) ) {
1378 deferred_logger.debug("CROSSFLOW_IPR",
1379 "cross flow found when updateIPR for well " + this->name());
1380 }
1381
1382 // the well index associated with the connection
1383 Scalar trans_mult(0.0);
1384 getTransMult(trans_mult, simulator, cell_idx);
1385 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1386 std::vector<Scalar> tw_perf(this->num_conservation_quantities_, this->well_index_[perf] * trans_mult);
1387 this->getTw(tw_perf, local_perf_index, int_quantities, trans_mult, wellstate_nupcol);
1388 std::vector<Scalar> ipr_a_perf(this->ipr_a_.size());
1389 std::vector<Scalar> ipr_b_perf(this->ipr_b_.size());
1390 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1391 const Scalar tw_mob = tw_perf[comp_idx] * mob[comp_idx] * b_perf[comp_idx];
1392 ipr_a_perf[comp_idx] += tw_mob * pressure_diff;
1393 ipr_b_perf[comp_idx] += tw_mob;
1394 }
1395
1396 // we need to handle the rs and rv when both oil and gas are present
1397 if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
1398 const unsigned oil_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
1399 const unsigned gas_comp_idx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
1400 const Scalar rs = (fs.Rs()).value();
1401 const Scalar rv = (fs.Rv()).value();
1402
1403 const Scalar dis_gas_a = rs * ipr_a_perf[oil_comp_idx];
1404 const Scalar vap_oil_a = rv * ipr_a_perf[gas_comp_idx];
1405
1406 ipr_a_perf[gas_comp_idx] += dis_gas_a;
1407 ipr_a_perf[oil_comp_idx] += vap_oil_a;
1408
1409 const Scalar dis_gas_b = rs * ipr_b_perf[oil_comp_idx];
1410 const Scalar vap_oil_b = rv * ipr_b_perf[gas_comp_idx];
1411
1412 ipr_b_perf[gas_comp_idx] += dis_gas_b;
1413 ipr_b_perf[oil_comp_idx] += vap_oil_b;
1414 }
1415
1416 for (std::size_t comp_idx = 0; comp_idx < ipr_a_perf.size(); ++comp_idx) {
1417 this->ipr_a_[comp_idx] += ipr_a_perf[comp_idx];
1418 this->ipr_b_[comp_idx] += ipr_b_perf[comp_idx];
1419 }
1420 }
1421 }
1422 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
1423 this->parallel_well_info_.communication().sum(this->ipr_b_.data(), this->ipr_b_.size());
1424 }
1425
1426 template<typename TypeTag>
1427 void
1429 updateIPRImplicit(const Simulator& simulator,
1430 const GroupStateHelperType& groupStateHelper,
1431 WellStateType& well_state)
1432 {
1433 auto& deferred_logger = groupStateHelper.deferredLogger();
1434 // Compute IPR based on *converged* well-equation:
1435 // For a component rate r the derivative dr/dbhp is obtained by
1436 // dr/dbhp = - (partial r/partial x) * inv(partial Eq/partial x) * (partial Eq/partial bhp_target)
1437 // where Eq(x)=0 is the well equation setup with bhp control and primary variables x
1438
1439 // We shouldn't have zero rates at this stage, but check
1440 bool zero_rates;
1441 auto rates = well_state.well(this->index_of_well_).surface_rates;
1442 zero_rates = true;
1443 for (std::size_t p = 0; p < rates.size(); ++p) {
1444 zero_rates &= rates[p] == 0.0;
1445 }
1446 auto& ws = well_state.well(this->index_of_well_);
1447 if (zero_rates) {
1448 const auto msg = fmt::format("updateIPRImplicit: Well {} has zero rate, IPRs might be problematic", this->name());
1449 deferred_logger.debug(msg);
1450 /*
1451 // could revert to standard approach here:
1452 updateIPR(simulator, deferred_logger);
1453 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
1454 const int idx = this->activeCompToActivePhaseIdx(comp_idx);
1455 ws.implicit_ipr_a[idx] = this->ipr_a_[comp_idx];
1456 ws.implicit_ipr_b[idx] = this->ipr_b_[comp_idx];
1457 }
1458 return;
1459 */
1460 }
1461
1462 std::ranges::fill(ws.implicit_ipr_a, 0.0);
1463 std::ranges::fill(ws.implicit_ipr_b, 0.0);
1464 //WellState well_state_copy = well_state;
1465 auto inj_controls = Well::InjectionControls(0);
1466 auto prod_controls = Well::ProductionControls(0);
1467 prod_controls.addControl(Well::ProducerCMode::BHP);
1468 prod_controls.bhp_limit = well_state.well(this->index_of_well_).bhp;
1469
1470 // Set current control to bhp, and bhp value in state, modify bhp limit in control object.
1471 const auto cmode = ws.production_cmode;
1472 ws.production_cmode = Well::ProducerCMode::BHP;
1473 const double dt = simulator.timeStepSize();
1474 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls, well_state,
1475 /*solving_with_zero_rate=*/false);
1476
1477 BVectorWell rhs(this->numberOfSegments());
1478 rhs = 0.0;
1479 rhs[0][SPres] = -1.0;
1480
1481 const BVectorWell x_well = this->linSys_.solve(rhs);
1482 constexpr int num_eq = MSWEval::numWellEq;
1483 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx){
1484 const EvalWell comp_rate = this->primary_variables_.getQs(comp_idx);
1485 const int idx = FluidSystem::activeCompToActivePhaseIdx(comp_idx);
1486 for (size_t pvIdx = 0; pvIdx < num_eq; ++pvIdx) {
1487 // well primary variable derivatives in EvalWell start at position Indices::numEq
1488 ws.implicit_ipr_b[idx] -= x_well[0][pvIdx]*comp_rate.derivative(pvIdx+Indices::numEq);
1489 }
1490 ws.implicit_ipr_a[idx] = ws.implicit_ipr_b[idx]*ws.bhp - comp_rate.value();
1491 }
1492 // reset cmode
1493 ws.production_cmode = cmode;
1494 }
1495
1496 template<typename TypeTag>
1497 void
1500 const WellStateType& well_state,
1501 const GroupStateHelperType& groupStateHelper)
1502 {
1503 auto& deferred_logger = groupStateHelper.deferredLogger();
1504 const auto& summaryState = simulator.vanguard().summaryState();
1505 const auto obtain_bhp = this->isProducer()
1506 ? computeBhpAtThpLimitProd(
1507 well_state, simulator, groupStateHelper, summaryState)
1508 : computeBhpAtThpLimitInj(simulator, groupStateHelper, summaryState);
1509
1510 if (obtain_bhp) {
1511 this->operability_status_.can_obtain_bhp_with_thp_limit = true;
1512
1513 const Scalar bhp_limit = WellBhpThpCalculator(*this).mostStrictBhpFromBhpLimits(summaryState);
1514 this->operability_status_.obey_bhp_limit_with_thp_limit = (*obtain_bhp >= bhp_limit);
1515
1516 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1517 if (this->isProducer() && *obtain_bhp < thp_limit) {
1518 const std::string msg = " obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1519 + " bars is SMALLER than thp limit "
1520 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1521 + " bars as a producer for well " + this->name();
1522 deferred_logger.debug(msg);
1523 }
1524 else if (this->isInjector() && *obtain_bhp > thp_limit) {
1525 const std::string msg = " obtained bhp " + std::to_string(unit::convert::to(*obtain_bhp, unit::barsa))
1526 + " bars is LARGER than thp limit "
1527 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1528 + " bars as a injector for well " + this->name();
1529 deferred_logger.debug(msg);
1530 }
1531 } else {
1532 // Shutting wells that can not find bhp value from thp
1533 // when under THP control
1534 this->operability_status_.can_obtain_bhp_with_thp_limit = false;
1535 this->operability_status_.obey_bhp_limit_with_thp_limit = false;
1536 if (!this->wellIsStopped()) {
1537 const Scalar thp_limit = this->getTHPConstraint(summaryState);
1538 deferred_logger.debug(" could not find bhp value at thp limit "
1539 + std::to_string(unit::convert::to(thp_limit, unit::barsa))
1540 + " bar for well " + this->name() + ", the well might need to be closed ");
1541 }
1542 }
1543 }
1544
1545
1546
1547
1548
1549 template<typename TypeTag>
1550 bool
1552 iterateWellEqWithControl(const Simulator& simulator,
1553 const double dt,
1554 const Well::InjectionControls& inj_controls,
1555 const Well::ProductionControls& prod_controls,
1556 const GroupStateHelperType& groupStateHelper,
1557 WellStateType& well_state)
1558 {
1559 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return true;
1560
1561 auto& deferred_logger = groupStateHelper.deferredLogger();
1562
1563 const int max_iter_number = this->param_.max_inner_iter_ms_wells_;
1564
1565 {
1566 // getWellFiniteResiduals returns false for nan/inf residuals
1567 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1568 if(!isFinite)
1569 return false;
1570 }
1571
1572 updatePrimaryVariables(groupStateHelper);
1573
1574 std::vector<std::vector<Scalar> > residual_history;
1575 std::vector<Scalar> measure_history;
1576 int it = 0;
1577 // relaxation factor
1578 Scalar relaxation_factor = 1.;
1579 bool converged = false;
1580 bool relax_convergence = false;
1581 this->regularize_ = false;
1582 for (; it < max_iter_number; ++it, ++debug_cost_counter_) {
1583
1584 if (it > this->param_.strict_inner_iter_wells_) {
1585 relax_convergence = true;
1586 this->regularize_ = true;
1587 }
1588
1589 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
1590 well_state,
1591 /*solving_with_zero_rate=*/false);
1592
1593 const auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
1594 if (report.converged()) {
1595 converged = true;
1596 break;
1597 }
1598
1599 {
1600 // getFinteWellResiduals returns false for nan/inf residuals
1601 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1602 if (!isFinite)
1603 return false;
1604
1605 residual_history.push_back(residuals);
1606 measure_history.push_back(this->getResidualMeasureValue(well_state,
1607 residual_history[it],
1608 this->param_.tolerance_wells_,
1609 this->param_.tolerance_pressure_ms_wells_,
1610 deferred_logger) );
1611 }
1612 bool min_relaxation_reached = this->update_relaxation_factor(measure_history, relaxation_factor, this->regularize_, deferred_logger);
1613 if (min_relaxation_reached || this->repeatedStagnation(measure_history, this->regularize_, deferred_logger)) {
1614 // try last attempt with relaxed tolerances
1615 const auto reportStag = getWellConvergence(groupStateHelper, Base::B_avg_, true);
1616 if (reportStag.converged()) {
1617 converged = true;
1618 std::string message = fmt::format("Well stagnates/oscillates but {} manages to get converged with relaxed tolerances in {} inner iterations."
1619 ,this->name(), it);
1620 deferred_logger.debug(message);
1621 } else {
1622 converged = false;
1623 }
1624 break;
1625 }
1626
1627 BVectorWell dx_well;
1628 try{
1629 dx_well = this->linSys_.solve();
1630 updateWellState(simulator, dx_well, groupStateHelper, well_state, relaxation_factor);
1631 }
1632 catch(const NumericalProblem& exp) {
1633 // Add information about the well and log to deferred logger
1634 // (Logging done inside of solve() method will only be seen if
1635 // this is the process with rank zero)
1636 deferred_logger.problem("In MultisegmentWell::iterateWellEqWithControl for well "
1637 + this->name() +": "+exp.what());
1638 throw;
1639 }
1640 }
1641
1642 // TODO: we should decide whether to keep the updated well_state, or recover to use the old well_state
1643 if (converged) {
1644 std::ostringstream sstr;
1645 sstr << " Well " << this->name() << " converged in " << it << " inner iterations.";
1646 if (relax_convergence)
1647 sstr << " (A relaxed tolerance was used after "<< this->param_.strict_inner_iter_wells_ << " iterations)";
1648
1649 // Output "converged in 0 inner iterations" messages only at
1650 // elevated verbosity levels.
1651 deferred_logger.debug(sstr.str(), OpmLog::defaultDebugVerbosityLevel + (it == 0));
1652 } else {
1653 std::ostringstream sstr;
1654 sstr << " Well " << this->name() << " did not converge in " << it << " inner iterations.";
1655#define EXTRA_DEBUG_MSW 0
1656#if EXTRA_DEBUG_MSW
1657 sstr << "***** Outputting the residual history for well " << this->name() << " during inner iterations:";
1658 for (int i = 0; i < it; ++i) {
1659 const auto& residual = residual_history[i];
1660 sstr << " residual at " << i << "th iteration ";
1661 for (const auto& res : residual) {
1662 sstr << " " << res;
1663 }
1664 sstr << " " << measure_history[i] << " \n";
1665 }
1666#endif
1667#undef EXTRA_DEBUG_MSW
1668 deferred_logger.debug(sstr.str());
1669 }
1670
1671 return converged;
1672 }
1673
1674
1675 template<typename TypeTag>
1676 bool
1678 iterateWellEqWithSwitching(const Simulator& simulator,
1679 const double dt,
1680 const Well::InjectionControls& inj_controls,
1681 const Well::ProductionControls& prod_controls,
1682 const GroupStateHelperType& groupStateHelper,
1683 WellStateType& well_state,
1684 const bool fixed_control /*false*/,
1685 const bool fixed_status /*false*/,
1686 const bool solving_with_zero_rate /*false*/)
1687 {
1688 auto& deferred_logger = groupStateHelper.deferredLogger();
1689
1690 const int max_iter_number = this->param_.max_inner_iter_ms_wells_;
1691
1692 {
1693 // getWellFiniteResiduals returns false for nan/inf residuals
1694 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1695 if(!isFinite)
1696 return false;
1697 }
1698
1699 updatePrimaryVariables(groupStateHelper);
1700
1701 std::vector<std::vector<Scalar> > residual_history;
1702 std::vector<Scalar> measure_history;
1703 int it = 0;
1704 // relaxation factor
1705 Scalar relaxation_factor = 1.;
1706 bool converged = false;
1707 bool relax_convergence = false;
1708 this->regularize_ = false;
1709 const auto& summary_state = groupStateHelper.summaryState();
1710
1711 // Always take a few (more than one) iterations after a switch before allowing a new switch
1712 // The optimal number here is subject to further investigation, but it has been observerved
1713 // that unless this number is >1, we may get stuck in a cycle
1714 const int min_its_after_switch = 3;
1715 // We also want to restrict the number of status switches to avoid oscillation between STOP<->OPEN
1716 const int max_status_switch = this->param_.max_well_status_switch_inner_iter_;
1717 int its_since_last_switch = min_its_after_switch;
1718 int switch_count= 0;
1719 int status_switch_count = 0;
1720 // if we fail to solve eqs, we reset status/operability before leaving
1721 const auto well_status_orig = this->wellStatus_;
1722 const auto operability_orig = this->operability_status_;
1723 auto well_status_cur = well_status_orig;
1724 // don't allow opening wells that has a stopped well status
1725 const bool allow_open = well_state.well(this->index_of_well_).status == WellStatus::OPEN;
1726 // don't allow switcing for wells under zero rate target or requested fixed status and control
1727 const bool allow_switching = !this->wellUnderZeroRateTarget(groupStateHelper) &&
1728 (!fixed_control || !fixed_status) && allow_open;
1729 bool final_check = false;
1730 // well needs to be set operable or else solving/updating of re-opened wells is skipped
1731 this->operability_status_.resetOperability();
1732 this->operability_status_.solvable = true;
1733
1734 for (; it < max_iter_number; ++it, ++debug_cost_counter_) {
1735 ++its_since_last_switch;
1736 if (allow_switching && its_since_last_switch >= min_its_after_switch && status_switch_count < max_status_switch){
1737 const Scalar wqTotal = this->primary_variables_.getWQTotal().value();
1738 bool changed = this->updateWellControlAndStatusLocalIteration(
1739 simulator, groupStateHelper, inj_controls, prod_controls, wqTotal,
1740 well_state, fixed_control, fixed_status,
1741 solving_with_zero_rate
1742 );
1743 if (changed) {
1744 its_since_last_switch = 0;
1745 ++switch_count;
1746 if (well_status_cur != this->wellStatus_) {
1747 well_status_cur = this->wellStatus_;
1748 status_switch_count++;
1749 }
1750 }
1751 if (!changed && final_check) {
1752 break;
1753 } else {
1754 final_check = false;
1755 }
1756 if (status_switch_count == max_status_switch) {
1757 this->wellStatus_ = well_status_orig;
1758 }
1759 }
1760
1761 if (it > this->param_.strict_inner_iter_wells_) {
1762 relax_convergence = true;
1763 this->regularize_ = true;
1764 }
1765
1766 assembleWellEqWithoutIteration(simulator, groupStateHelper, dt, inj_controls, prod_controls,
1767 well_state, solving_with_zero_rate);
1768
1769
1770 const auto report = getWellConvergence(groupStateHelper, Base::B_avg_, relax_convergence);
1771 converged = report.converged();
1772 if (this->parallel_well_info_.communication().size() > 1 &&
1773 this->parallel_well_info_.communication().max(converged) != this->parallel_well_info_.communication().min(converged)) {
1774 OPM_THROW(std::runtime_error, fmt::format("Misalignment of the parallel simulation run in iterateWellEqWithSwitching - the well calculation for well {} succeeded some ranks but failed on other ranks.", this->name()));
1775 }
1776 if (converged) {
1777 // if equations are sufficiently linear they might converge in less than min_its_after_switch
1778 // in this case, make sure all constraints are satisfied before returning
1779 if (switch_count > 0 && its_since_last_switch < min_its_after_switch) {
1780 final_check = true;
1781 its_since_last_switch = min_its_after_switch;
1782 } else {
1783 break;
1784 }
1785 }
1786
1787 // getFinteWellResiduals returns false for nan/inf residuals
1788 {
1789 const auto& [isFinite, residuals] = this->getFiniteWellResiduals(Base::B_avg_, deferred_logger);
1790 if (!isFinite) {
1791 converged = false; // Jump out of loop instead of returning to ensure operability status is recovered
1792 break;
1793 }
1794
1795 residual_history.push_back(residuals);
1796 }
1797
1798 if (!converged) {
1799 measure_history.push_back(this->getResidualMeasureValue(well_state,
1800 residual_history[it],
1801 this->param_.tolerance_wells_,
1802 this->param_.tolerance_pressure_ms_wells_,
1803 deferred_logger));
1804 bool min_relaxation_reached = this->update_relaxation_factor(measure_history, relaxation_factor, this->regularize_, deferred_logger);
1805 if (min_relaxation_reached || this->repeatedStagnation(measure_history, this->regularize_, deferred_logger)) {
1806 converged = false;
1807 break;
1808 }
1809 }
1810 try{
1811 const BVectorWell dx_well = this->linSys_.solve();
1812 updateWellState(simulator, dx_well, groupStateHelper, well_state, relaxation_factor);
1813 }
1814 catch(const NumericalProblem& exp) {
1815 // Add information about the well and log to deferred logger
1816 // (Logging done inside of solve() method will only be seen if
1817 // this is the process with rank zero)
1818 deferred_logger.problem("In MultisegmentWell::iterateWellEqWithSwitching for well "
1819 + this->name() +": "+exp.what());
1820 throw;
1821 }
1822 }
1823
1824 if (converged) {
1825 if (allow_switching){
1826 // update operability if status change
1827 const bool is_stopped = this->wellIsStopped();
1828 if (this->wellHasTHPConstraints(summary_state)){
1829 this->operability_status_.can_obtain_bhp_with_thp_limit = !is_stopped;
1830 this->operability_status_.obey_thp_limit_under_bhp_limit = !is_stopped;
1831 } else {
1832 this->operability_status_.operable_under_only_bhp_limit = !is_stopped;
1833 }
1834 }
1835 std::string message = fmt::format(" Well {} converged in {} inner iterations ("
1836 "{} control/status switches).", this->name(), it, switch_count);
1837 if (relax_convergence) {
1838 message.append(fmt::format(" (A relaxed tolerance was used after {} iterations)",
1839 this->param_.strict_inner_iter_wells_));
1840 }
1841 deferred_logger.debug(message, OpmLog::defaultDebugVerbosityLevel + ((it == 0) && (switch_count == 0)));
1842 } else {
1843 this->wellStatus_ = well_status_orig;
1844 this->operability_status_ = operability_orig;
1845 const std::string message = fmt::format(" Well {} did not converge in {} inner iterations ("
1846 "{} switches, {} status changes).", this->name(), it, switch_count, status_switch_count);
1847 deferred_logger.debug(message);
1848 this->primary_variables_.outputLowLimitPressureSegments(deferred_logger);
1849 }
1850
1851 return converged;
1852 }
1853
1854
1855 template<typename TypeTag>
1856 void
1859 const GroupStateHelperType& groupStateHelper,
1860 const double dt,
1861 const Well::InjectionControls& inj_controls,
1862 const Well::ProductionControls& prod_controls,
1863 WellStateType& well_state,
1864 const bool solving_with_zero_rate)
1865 {
1866 if (!this->isOperableAndSolvable() && !this->wellIsStopped()) return;
1867
1868 auto& deferred_logger = groupStateHelper.deferredLogger();
1869
1870 // update the upwinding segments
1871 this->segments_.updateUpwindingSegments(this->primary_variables_);
1872
1873 // calculate the fluid properties needed.
1874 computeSegmentFluidProperties(simulator, deferred_logger);
1875
1876 // clear all entries
1877 this->linSys_.clear();
1878
1879 auto& ws = well_state.well(this->index_of_well_);
1880 ws.phase_mixing_rates.fill(0.0);
1881 if constexpr (has_energy) {
1882 ws.energy_rate = 0.0;
1883 }
1884
1885 // for the black oil cases, there will be four equations,
1886 // the first three of them are the mass balance equations, the last one is the pressure equations.
1887 //
1888 // but for the top segment, the pressure equation will be the well control equation, and the other three will be the same.
1889
1890 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
1891
1892 const int nseg = this->numberOfSegments();
1893
1894 const Scalar rhow = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) ?
1895 FluidSystem::referenceDensity( FluidSystem::waterPhaseIdx, Base::pvtRegionIdx() ) : 0.0;
1896 const unsigned watCompIdx = FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx) ?
1897 FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx) : 0;
1898
1899 for (int seg = 0; seg < nseg; ++seg) {
1900 // calculating the perforation rate for each perforation that belongs to this segment
1901 const EvalWell seg_pressure = this->primary_variables_.getSegmentPressure(seg);
1902 auto& perf_data = ws.perf_data;
1903 auto& perf_rates = perf_data.phase_rates;
1904 auto& perf_press_state = perf_data.pressure;
1905 for (const int perf : this->segments_.perforations()[seg]) {
1906 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
1907 if (local_perf_index < 0) // then the perforation is not on this process
1908 continue;
1909 const int cell_idx = this->well_cells_[local_perf_index];
1910 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
1911 std::vector<EvalWell> mob(this->num_conservation_quantities_, 0.0);
1912 getMobility(simulator, local_perf_index, mob, deferred_logger);
1913 EvalWell trans_mult(0.0);
1914 getTransMult(trans_mult, simulator, cell_idx);
1915 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
1916 std::vector<EvalWell> Tw(this->num_conservation_quantities_, this->well_index_[local_perf_index] * trans_mult);
1917 this->getTw(Tw, local_perf_index, int_quants, trans_mult, wellstate_nupcol);
1918 std::vector<EvalWell> cq_s(this->num_conservation_quantities_, 0.0);
1919 EvalWell perf_press;
1920 PerforationRates<Scalar> perfRates;
1921 computePerfRate(int_quants, mob, Tw, seg, perf, seg_pressure,
1922 allow_cf, cq_s, perf_press, perfRates, deferred_logger);
1923
1924 // updating the solution gas rate and solution oil rate
1925 if (this->isProducer()) {
1926 ws.phase_mixing_rates[ws.dissolved_gas] += perfRates.dis_gas;
1927 ws.phase_mixing_rates[ws.vaporized_oil] += perfRates.vap_oil;
1928 perf_data.phase_mixing_rates[local_perf_index][ws.dissolved_gas] = perfRates.dis_gas;
1929 perf_data.phase_mixing_rates[local_perf_index][ws.vaporized_oil] = perfRates.vap_oil;
1930 }
1931
1932 // store the perf pressure and rates
1933 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1934 perf_rates[local_perf_index*this->number_of_phases_ + FluidSystem::activeCompToActivePhaseIdx(comp_idx)] = cq_s[comp_idx].value();
1935 }
1936 perf_press_state[local_perf_index] = perf_press.value();
1937
1938 // mass rates, for now only water
1939 if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
1940 perf_data.wat_mass_rates[local_perf_index] = cq_s[watCompIdx].value() * rhow;
1941 }
1942
1943 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1944 // the cq_s entering mass balance equations need to consider the efficiency factors.
1945 const EvalWell cq_s_effective = cq_s[comp_idx] * this->well_efficiency_factor_;
1946
1947 this->connectionRates_[local_perf_index][comp_idx] = Base::restrictEval(cq_s_effective);
1948
1950 assemblePerforationEq(seg, local_perf_index, comp_idx, cq_s_effective, this->linSys_);
1951 }
1952
1953 // assembling the energy equation for the perforation if needed
1954 if constexpr (has_energy) {
1955 assemblePerforationEnergyEq(int_quants, cq_s, seg, local_perf_index, deferred_logger);
1956 // accumulate the well energy rate from the connection source term so that
1957 // summary vectors such as W*RHEA/W*IRHEA/W*PRHEA are reported, mirroring
1958 // the standard-well handling in StandardWell::assembleWellEqWithoutIterationImpl.
1959 ws.energy_rate += getValue(this->connectionRates_[local_perf_index][Indices::contiEnergyEqIdx]);
1960 }
1961 }
1962 }
1963 // Accumulate dissolved gas and vaporized oil flow rates across all ranks sharing this well.
1964 {
1965 const auto& comm = this->parallel_well_info_.communication();
1966 comm.sum(ws.phase_mixing_rates.data(), ws.phase_mixing_rates.size());
1967 if constexpr (has_energy) {
1968 ws.energy_rate = comm.sum(ws.energy_rate);
1969 }
1970 }
1971
1972 if (this->parallel_well_info_.communication().size() > 1) {
1973 // accumulate resWell_ and duneD_ in parallel to get effects of all perforations (might be distributed)
1974 this->linSys_.sumDistributed(this->parallel_well_info_.communication());
1975 }
1976
1977 // Needed to construct the injector wellhead fluid state.
1978 [[maybe_unused]] FSInfo info{};
1979 if constexpr (has_energy) {
1980 info = this->getFirstPerfCellConditions(simulator);
1981 }
1982
1983 for (int seg = 0; seg < nseg; ++seg) {
1984 // calculating the accumulation term
1985 {
1986 // The ratios were refreshed by computeSegmentFluidProperties() above.
1987 const EvalWell segment_surface_volume =
1988 getSegmentSurfaceVolume(seg, this->segments_.volumeRatio(seg));
1989
1990 // Add a regularization_factor to increase the accumulation term
1991 // This will make the system less stiff and help convergence for
1992 // difficult cases
1993 const Scalar regularization_factor = this->regularize_? this->param_.regularization_factor_wells_ : 1.0;
1994 // for each component
1995 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
1996 const EvalWell accumulation_term = regularization_factor * (segment_surface_volume * this->primary_variables_.surfaceVolumeFraction(seg, comp_idx)
1997 - segment_fluid_initial_[seg][comp_idx]) / dt;
1999 assembleAccumulationTerm(seg, comp_idx, accumulation_term, this->linSys_);
2000 }
2001
2002 if constexpr (has_energy) {
2003 const EvalWell segment_energy = this->computeSegmentEnergy(seg);
2004 // scaled to the same magnitude as the mass-balance equations, see energy_scaling_factor_
2005 const EvalWell accumulation_term_energy =
2006 energy_scaling_factor_ * regularization_factor * (segment_energy - segment_initial_energy_[seg]) / dt;
2008 assembleAccumulationTerm(seg, MSWEval::PrimaryVariables::Temperature, accumulation_term_energy, this->linSys_);
2009 }
2010 }
2011 // considering the contributions due to flowing out from the segment
2012 {
2013 const int seg_upwind = this->segments_.upwinding_segment(seg);
2014 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
2015 const EvalWell segment_rate =
2016 this->primary_variables_.getSegmentRateUpwinding(seg,
2017 seg_upwind,
2018 comp_idx) *
2019 this->well_efficiency_factor_;
2021 assembleOutflowTerm(seg, seg_upwind, comp_idx, segment_rate, this->linSys_);
2022 }
2023 if constexpr (has_energy) {
2024 const bool top_injecting_segment = (seg == 0) && this->isInjector();
2025 if (top_injecting_segment) {
2026 this->updateWellHeadCondition(simulator, info.temperature,
2027 info.saltConcentration, deferred_logger);
2028 }
2029
2030 // Energy out toward the outlet, using the upwind segment fluid
2031 // state (the wellhead state for the top injecting segment).
2032 const auto& upwind_fs = top_injecting_segment ? this->wellhead_fluid_state_
2033 : this->segment_fluid_state_[seg_upwind];
2034 assert((top_injecting_segment && seg_upwind == 0) || !top_injecting_segment);
2035
2036 const EvalWell energy_rate =
2037 this->computeSegmentEnergyRate(seg, seg_upwind, upwind_fs,
2038 "energy outflow assembly", deferred_logger);
2040 assembleOutflowTerm(seg, seg_upwind, MSWEval::PrimaryVariables::Temperature, energy_rate, this->linSys_);
2041 }
2042 }
2043
2044 // considering the contributions from the inlet segments
2045 {
2046 for (const int inlet : this->segments_.inlets()[seg]) {
2047 const int inlet_upwind = this->segments_.upwinding_segment(inlet);
2048 for (int comp_idx = 0; comp_idx < this->num_conservation_quantities_; ++comp_idx) {
2049 const EvalWell inlet_rate =
2050 this->primary_variables_.getSegmentRateUpwinding(inlet,
2051 inlet_upwind,
2052 comp_idx) *
2053 this->well_efficiency_factor_;
2055 assembleInflowTerm(seg, inlet, inlet_upwind, comp_idx, inlet_rate, this->linSys_);
2056 }
2057 }
2058 if constexpr (has_energy) {
2059 for (const int inlet : this->segments_.inlets()[seg]) {
2060 const int inlet_upwind = this->segments_.upwinding_segment(inlet);
2061 // Energy in from the inlet, using the upwind segment fluid state.
2062 const auto& upwind_fs = this->segment_fluid_state_[inlet_upwind];
2063 const EvalWell energy_rate =
2064 this->computeSegmentEnergyRate(inlet, inlet_upwind, upwind_fs,
2065 "energy inflow assembly", deferred_logger);
2067 assembleInflowTerm(seg, inlet, inlet_upwind, MSWEval::PrimaryVariables::Temperature, energy_rate, this->linSys_);
2068 }
2069 }
2070 }
2071
2072 // the fourth equation, the pressure drop equation
2073 if (seg == 0) { // top segment, pressure equation is the control equation
2074 const bool stopped_or_zero_target = this->stoppedOrZeroRateTarget(groupStateHelper);
2075 // When solving with zero rate (well isolation), use empty group_state to isolate
2076 // from group constraints in assembly.
2077 // Otherwise, use real group state from groupStateHelper.
2078 GroupState<Scalar> empty_group_state;
2079 // Note: Cannot use 'const auto&' here because pushGroupState() requires a
2080 // non-const reference. GroupStateHelper stores a non-const pointer to GroupState
2081 // and is designed to allow modifications through methods like pushGroupState().
2082 auto& group_state = solving_with_zero_rate
2083 ? empty_group_state
2084 : groupStateHelper.groupState();
2085 GroupStateHelperType groupStateHelper_copy = groupStateHelper;
2086 auto group_guard = groupStateHelper_copy.pushGroupState(group_state);
2087 // For production wells under group control, ensure feasibility before assembling control equation
2088 if (this->wellUnderGroupControl(ws) && this->isProducer() && !stopped_or_zero_target) {
2089 this->updateGroupTargetFallbackFlag(well_state, deferred_logger);
2090 }
2092 assembleControlEq(groupStateHelper_copy,
2093 inj_controls,
2094 prod_controls,
2095 this->getRefDensity(),
2096 this->primary_variables_,
2097 this->linSys_,
2098 stopped_or_zero_target);
2099 } else {
2100 const UnitSystem& unit_system = simulator.vanguard().eclState().getDeckUnitSystem();
2101 const auto& summary_state = simulator.vanguard().summaryState();
2102 this->assemblePressureEq(seg, unit_system, well_state, summary_state, this->param_.use_average_density_ms_wells_, deferred_logger);
2103 }
2104 }
2105
2106 this->parallel_well_info_.communication().sum(this->ipr_a_.data(), this->ipr_a_.size());
2107 this->linSys_.createSolver();
2108 }
2109
2110
2111
2112
2113 template<typename TypeTag>
2114 bool
2116 openCrossFlowAvoidSingularity(const Simulator& simulator) const
2117 {
2118 return !this->getAllowCrossFlow() && allDrawDownWrongDirection(simulator);
2119 }
2120
2121
2122 template<typename TypeTag>
2123 bool
2125 allDrawDownWrongDirection(const Simulator& simulator) const
2126 {
2127 bool all_drawdown_wrong_direction = true;
2128 const int nseg = this->numberOfSegments();
2129
2130 for (int seg = 0; seg < nseg; ++seg) {
2131 const EvalWell segment_pressure = this->primary_variables_.getSegmentPressure(seg);
2132 for (const int perf : this->segments_.perforations()[seg]) {
2133 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2134 if (local_perf_index < 0) // then the perforation is not on this process
2135 continue;
2136
2137 const int cell_idx = this->well_cells_[local_perf_index];
2138 const auto& intQuants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2139 const auto& fs = intQuants.fluidState();
2140
2141 // pressure difference between the segment and the perforation
2142 const EvalWell perf_seg_press_diff = this->segments_.getPressureDiffSegLocalPerf(seg, local_perf_index);
2143 // pressure difference between the perforation and the grid cell
2144 const Scalar cell_perf_press_diff = this->cell_perforation_pressure_diffs_[local_perf_index];
2145
2146 const Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2147 const Scalar perf_press = pressure_cell - cell_perf_press_diff;
2148 // Pressure drawdown (also used to determine direction of flow)
2149 // TODO: not 100% sure about the sign of the seg_perf_press_diff
2150 const EvalWell drawdown = perf_press - (segment_pressure + perf_seg_press_diff);
2151
2152 // for now, if there is one perforation can produce/inject in the correct
2153 // direction, we consider this well can still produce/inject.
2154 // TODO: it can be more complicated than this to cause wrong-signed rates
2155 if ( (drawdown < 0. && this->isInjector()) ||
2156 (drawdown > 0. && this->isProducer()) ) {
2157 all_drawdown_wrong_direction = false;
2158 break;
2159 }
2160 }
2161 }
2162 const auto& comm = this->parallel_well_info_.communication();
2163 if (comm.size() > 1)
2164 {
2165 all_drawdown_wrong_direction =
2166 (comm.min(all_drawdown_wrong_direction ? 1 : 0) == 1);
2167 }
2168
2169 return all_drawdown_wrong_direction;
2170 }
2171
2172
2173
2174
2175 template<typename TypeTag>
2176 void
2178 updateWaterThroughput(const double /*dt*/, WellStateType& /*well_state*/) const
2179 {
2180 }
2181
2182
2183
2184
2185
2186 template<typename TypeTag>
2189 getSegmentSurfaceVolume(const int seg_idx,
2190 const EvalWell& volume_ratio) const
2191 {
2192 const Scalar volume = this->wellEcl().getSegments()[seg_idx].volume();
2193 return volume / volume_ratio;
2194 }
2195
2196
2197 template<typename TypeTag>
2198 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2201 const Simulator& simulator,
2202 const GroupStateHelperType& groupStateHelper,
2203 const SummaryState& summary_state) const
2204 {
2206 simulator,
2207 groupStateHelper,
2208 summary_state,
2209 this->getALQ(well_state),
2210 /*iterate_if_no_solution */ true);
2211 }
2212
2213
2214
2215 template<typename TypeTag>
2216 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2219 const GroupStateHelperType& groupStateHelper,
2220 const SummaryState& summary_state,
2221 const Scalar alq_value,
2222 bool iterate_if_no_solution) const
2223 {
2224 OPM_TIMEFUNCTION();
2225 auto& deferred_logger = groupStateHelper.deferredLogger();
2226 // Make the frates() function.
2227 auto frates = [this, &simulator, &deferred_logger](const Scalar bhp) {
2228 // Not solving the well equations here, which means we are
2229 // calculating at the current Fg/Fw values of the
2230 // well. This does not matter unless the well is
2231 // crossflowing, and then it is likely still a good
2232 // approximation.
2233 std::vector<Scalar> rates(3);
2234 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2235 return rates;
2236 };
2237
2238 auto bhpAtLimit = WellBhpThpCalculator(*this).
2239 computeBhpAtThpLimitProd(frates,
2240 summary_state,
2241 maxPerfPress(simulator),
2242 this->getRefDensity(),
2243 alq_value,
2244 this->getTHPConstraint(summary_state),
2245 deferred_logger);
2246
2247 if (bhpAtLimit)
2248 return bhpAtLimit;
2249
2250 if (!iterate_if_no_solution)
2251 return std::nullopt;
2252
2253 auto fratesIter = [this, &simulator, &groupStateHelper](const Scalar bhp) {
2254 // Solver the well iterations to see if we are
2255 // able to get a solution with an update
2256 // solution
2257 std::vector<Scalar> rates(3);
2258 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2259 return rates;
2260 };
2261
2262 return WellBhpThpCalculator(*this).
2263 computeBhpAtThpLimitProd(fratesIter,
2264 summary_state,
2265 maxPerfPress(simulator),
2266 this->getRefDensity(),
2267 alq_value,
2268 this->getTHPConstraint(summary_state),
2269 deferred_logger);
2270 }
2271
2272 template<typename TypeTag>
2273 std::optional<typename MultisegmentWell<TypeTag>::Scalar>
2275 computeBhpAtThpLimitInj(const Simulator& simulator,
2276 const GroupStateHelperType& groupStateHelper,
2277 const SummaryState& summary_state) const
2278 {
2279 auto& deferred_logger = groupStateHelper.deferredLogger();
2280 // Make the frates() function.
2281 auto frates = [this, &simulator, &deferred_logger](const Scalar bhp) {
2282 // Not solving the well equations here, which means we are
2283 // calculating at the current Fg/Fw values of the
2284 // well. This does not matter unless the well is
2285 // crossflowing, and then it is likely still a good
2286 // approximation.
2287 std::vector<Scalar> rates(3);
2288 computeWellRatesWithBhp(simulator, bhp, rates, deferred_logger);
2289 return rates;
2290 };
2291
2292 auto bhpAtLimit = WellBhpThpCalculator(*this).
2293 computeBhpAtThpLimitInj(frates,
2294 summary_state,
2295 this->getRefDensity(),
2296 0.05,
2297 100,
2298 false,
2299 deferred_logger);
2300
2301 if (bhpAtLimit)
2302 return bhpAtLimit;
2303
2304 auto fratesIter = [this, &simulator, &groupStateHelper](const Scalar bhp) {
2305 // Solver the well iterations to see if we are
2306 // able to get a solution with an update
2307 // solution
2308 std::vector<Scalar> rates(3);
2309 computeWellRatesWithBhpIterations(simulator, bhp, groupStateHelper, rates);
2310 return rates;
2311 };
2312
2313 return WellBhpThpCalculator(*this).
2314 computeBhpAtThpLimitInj(fratesIter,
2315 summary_state,
2316 this->getRefDensity(),
2317 0.05,
2318 100,
2319 false,
2320 deferred_logger);
2321 }
2322
2323
2324
2325
2326
2327 template<typename TypeTag>
2330 maxPerfPress(const Simulator& simulator) const
2331 {
2332 Scalar max_pressure = 0.0;
2333 const int nseg = this->numberOfSegments();
2334 for (int seg = 0; seg < nseg; ++seg) {
2335 for (const int perf : this->segments_.perforations()[seg]) {
2336 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2337 if (local_perf_index < 0) // then the perforation is not on this process
2338 continue;
2339
2340 const int cell_idx = this->well_cells_[local_perf_index];
2341 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2342 const auto& fs = int_quants.fluidState();
2343 Scalar pressure_cell = this->getPerfCellPressure(fs).value();
2344 max_pressure = std::max(max_pressure, pressure_cell);
2345 }
2346 }
2347 max_pressure = this->parallel_well_info_.communication().max(max_pressure);
2348 return max_pressure;
2349 }
2350
2351
2352
2353
2354
2355 template<typename TypeTag>
2356 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
2358 computeCurrentWellRates(const Simulator& simulator,
2359 DeferredLogger& deferred_logger) const
2360 {
2361 // Calculate the rates that follow from the current primary variables.
2362 std::vector<Scalar> well_q_s(this->num_conservation_quantities_, 0.0);
2363 const bool allow_cf = this->getAllowCrossFlow() || openCrossFlowAvoidSingularity(simulator);
2364 const int nseg = this->numberOfSegments();
2365 for (int seg = 0; seg < nseg; ++seg) {
2366 // calculating the perforation rate for each perforation that belongs to this segment
2367 const Scalar seg_pressure = getValue(this->primary_variables_.getSegmentPressure(seg));
2368 for (const int perf : this->segments_.perforations()[seg]) {
2369 const int local_perf_index = this->parallel_well_info_.activePerfToLocalPerf(perf);
2370 if (local_perf_index < 0) // then the perforation is not on this process
2371 continue;
2372
2373 const int cell_idx = this->well_cells_[local_perf_index];
2374 const auto& int_quants = simulator.model().intensiveQuantities(cell_idx, /*timeIdx=*/ 0);
2375 std::vector<Scalar> mob(this->num_conservation_quantities_, 0.0);
2376 getMobility(simulator, local_perf_index, mob, deferred_logger);
2377 Scalar trans_mult(0.0);
2378 getTransMult(trans_mult, simulator, cell_idx);
2379 const auto& wellstate_nupcol = simulator.problem().wellModel().nupcolWellState().well(this->index_of_well_);
2380 std::vector<Scalar> Tw(this->num_conservation_quantities_, this->well_index_[local_perf_index] * trans_mult);
2381 this->getTw(Tw, local_perf_index, int_quants, trans_mult, wellstate_nupcol);
2382 std::vector<Scalar> cq_s(this->num_conservation_quantities_, 0.0);
2383 Scalar perf_press = 0.0;
2384 PerforationRates<Scalar> perf_rates;
2385 computePerfRate(int_quants, mob, Tw, seg, perf, seg_pressure,
2386 allow_cf, cq_s, perf_press, perf_rates, deferred_logger);
2387 for (int comp = 0; comp < this->num_conservation_quantities_; ++comp) {
2388 well_q_s[comp] += cq_s[comp];
2389 }
2390 }
2391 }
2392 const auto& comm = this->parallel_well_info_.communication();
2393 if (comm.size() > 1)
2394 {
2395 comm.sum(well_q_s.data(), well_q_s.size());
2396 }
2397 return well_q_s;
2398 }
2399
2400
2401 template <typename TypeTag>
2402 std::vector<typename MultisegmentWell<TypeTag>::Scalar>
2404 getPrimaryVars() const
2405 {
2406 const int num_seg = this->numberOfSegments();
2407 constexpr int num_eq = MSWEval::numWellEq;
2408 std::vector<Scalar> retval(num_seg * num_eq);
2409 for (int ii = 0; ii < num_seg; ++ii) {
2410 const auto& pv = this->primary_variables_.value(ii);
2411 std::ranges::copy(pv, retval.begin() + ii * num_eq);
2412 }
2413 return retval;
2414 }
2415
2416
2417
2418
2419 template <typename TypeTag>
2420 int
2422 setPrimaryVars(typename std::vector<Scalar>::const_iterator it)
2423 {
2424 const int num_seg = this->numberOfSegments();
2425 constexpr int num_eq = MSWEval::numWellEq;
2426 std::array<Scalar, num_eq> tmp;
2427 for (int ii = 0; ii < num_seg; ++ii) {
2428 const auto start = it + ii * num_eq;
2429 std::copy_n(start, num_eq, tmp.begin());
2430 this->primary_variables_.setValue(ii, tmp);
2431 }
2432 return num_seg * num_eq;
2433 }
2434
2435
2436 template <typename TypeTag>
2437 void
2439 getScaledWellFractions(std::vector<Scalar>& scaled_fractions,
2440 DeferredLogger& deferred_logger) const
2441 {
2442 this->primary_variables_.scaledWellFractions(scaled_fractions, deferred_logger);
2443 }
2444
2445
2446 template <typename TypeTag>
2447 template <typename ValueType>
2450 createFluidState(const std::vector<ValueType>& fluid_composition,
2451 const ValueType& pressure,
2452 const ValueType& temperature,
2453 const ValueType& saltConcentration,
2454 DeferredLogger& deferred_logger) const
2455 {
2456 SegmentFluidState<ValueType> fluid_state;
2457 if constexpr (enable_temperature) {
2458 // Populate temperature for every fluid state that stores it, including thermal
2459 // modes without a fully implicit energy equation.
2460 fluid_state.setTemperature(temperature);
2461 }
2462 if constexpr (has_brine) {
2463 // Set before invB/density/enthalpy are evaluated below (brine PVT).
2464 fluid_state.setSaltConcentration(saltConcentration);
2465 }
2466 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2467 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2468 continue;
2469 }
2470 // we assume there is no capillary pressure in the wellbore
2471 fluid_state.setPressure(phaseIdx, pressure);
2472 }
2473 fluid_state.setPvtRegionIndex(this->pvtRegionIdx());
2474
2475 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx) && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2476
2477 const ValueType zero_value {0.};
2478 // let us handle the dissolution first
2479 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2480 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2481 continue;
2482 }
2483
2484 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2485
2486 switch (phaseIdx) {
2487 case FluidSystem::oilPhaseIdx: {
2488 if constexpr (compositionSwitchEnabled) {
2489 if (both_oil_gas) {
2490 // starting with saturated rs value
2491 ValueType rs = FluidSystem::saturatedDissolutionFactor(fluid_state, phaseIdx, fluid_state.pvtRegionIndex());
2492 if (fluid_composition[activeCompIdx] > 0.0) {
2493 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2494 const ValueType max_possible_rs = fluid_composition[gasCompIdx] / fluid_composition[activeCompIdx];
2495 rs = std::min(rs, max_possible_rs);
2496 }
2497 fluid_state.setRs(rs);
2498 } else {
2499 fluid_state.setRs(zero_value);
2500 }
2501 }
2502 break;
2503 }
2504 case FluidSystem::gasPhaseIdx: {
2505 if constexpr (compositionSwitchEnabled) {
2506 if (both_oil_gas) {
2507 // Starting with the saturated rv value. Note that for the gas phase
2508 // saturatedDissolutionFactor() is the saturated *oil* vaporization
2509 // factor Rv (saturatedVaporizationFactor() would be the saturated
2510 // *water* vaporization factor Rvw, which is zero without vaporized
2511 // water and is not what is needed here).
2512 ValueType rv = FluidSystem::saturatedDissolutionFactor(fluid_state, phaseIdx, fluid_state.pvtRegionIndex());
2513 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2514 if (fluid_composition[activeCompIdx] > 0.0) {
2515 const ValueType max_possible_rv = fluid_composition[oilCompIdx] / fluid_composition[activeCompIdx];
2516 rv = std::min(rv, max_possible_rv);
2517 }
2518 fluid_state.setRv(rv);
2519 } else {
2520 fluid_state.setRv(zero_value);
2521 }
2522 }
2523 break;
2524 }
2525 case FluidSystem::waterPhaseIdx: {
2526 // TODO: handle the water phase dissolution with gas later
2527 break;
2528 }
2529 default: {
2530 throw std::logic_error("Unhandled phase index " + std::to_string(phaseIdx));
2531 }
2532 }
2533 const auto& inv_b = FluidSystem::inverseFormationVolumeFactor(fluid_state, phaseIdx, fluid_state.pvtRegionIndex());
2534 fluid_state.setInvB(phaseIdx, inv_b);
2535 }
2536
2537 std::vector<ValueType> saturations (FluidSystem::numPhases, zero_value);
2538 ValueType sum_saturation {0.0};
2539 // calculate the saturation for all the phases
2540 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2541 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2542 continue;
2543 }
2544 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2545 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2546 saturations[phaseIdx] = fluid_composition[activeCompIdx] / fluid_state.invB(phaseIdx);
2547 sum_saturation += saturations[phaseIdx];
2548 } else {
2549 // remove dissolved gas and vaporized oil
2550 // q_os = q_or * b_o + rv * q_gr * b_g
2551 // q_gs = q_gr * g_g + rs * q_or * b_o
2552 // q_gr = 1 / (b_g * d) * (q_gs - rs * q_os)
2553 // d = 1.0 - rs * rv
2554 const ValueType d = 1.0 - fluid_state.Rv() * fluid_state.Rs();
2555 if (d <= 0.0) {
2556 deferred_logger.debug(
2557 fmt::format("Problematic d value {} obtained for well {}"
2558 " during createFluidState with rs {}"
2559 ", rv {}. Continue as if no dissolution (rs = 0) and"
2560 " vaporization (rv = 0)",
2561 d, this->name(), fluid_state.Rs(), fluid_state.Rv()) );
2562 // Reset Rs/Rv and refresh invB so the fluid state is consistent with the
2563 // "no dissolution/vaporization" fallback used here and in the subsequent
2564 // density/enthalpy evaluations.
2565 if constexpr (compositionSwitchEnabled) {
2566 fluid_state.setRs(zero_value);
2567 fluid_state.setRv(zero_value);
2568 }
2569 fluid_state.setInvB(FluidSystem::oilPhaseIdx,
2570 FluidSystem::inverseFormationVolumeFactor(fluid_state, FluidSystem::oilPhaseIdx, fluid_state.pvtRegionIndex()));
2571 fluid_state.setInvB(FluidSystem::gasPhaseIdx,
2572 FluidSystem::inverseFormationVolumeFactor(fluid_state, FluidSystem::gasPhaseIdx, fluid_state.pvtRegionIndex()));
2573 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2574 saturations[phaseIdx] = fluid_composition[activeCompIdx] / fluid_state.invB(phaseIdx);
2575 } else {
2576 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2577 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2578 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2579 saturations[phaseIdx] = (fluid_composition[gasCompIdx] -
2580 fluid_state.Rs() * fluid_composition[oilCompIdx]) /
2581 (d * fluid_state.invB(phaseIdx));
2582 } else if (FluidSystem::oilPhaseIdx == phaseIdx) {
2583 saturations[phaseIdx] = (fluid_composition[oilCompIdx] -
2584 fluid_state.Rv() * fluid_composition[gasCompIdx]) /
2585 (d * fluid_state.invB(phaseIdx));
2586 }
2587 }
2588 sum_saturation += saturations[phaseIdx];
2589 }
2590 }
2591
2592 typename FluidSystem::template ParameterCache<ValueType> paramCache;
2593 paramCache.setRegionIndex(fluid_state.pvtRegionIndex());
2594 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2595 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2596 continue;
2597 }
2598 fluid_state.setSaturation(phaseIdx, saturations[phaseIdx] / sum_saturation);
2599
2600 paramCache.updatePhase(fluid_state, phaseIdx);
2601 fluid_state.setDensity(phaseIdx, FluidSystem::density(fluid_state, paramCache, phaseIdx));
2602 if constexpr (has_energy) {
2603 fluid_state.setEnthalpy(phaseIdx, FluidSystem::enthalpy(fluid_state, paramCache, phaseIdx));
2604 }
2605 }
2606 return fluid_state;
2607 }
2608
2609 // it looks like these functions should go to MultisegmentWellSegments class
2610 template <typename TypeTag>
2611 MultisegmentWell<TypeTag>::template SegmentFluidState<typename MultisegmentWell<TypeTag>::EvalWell>
2613 DeferredLogger& deferred_logger) const
2614 {
2615 const EvalWell seg_pressure = this->primary_variables_.getSegmentPressure(seg);
2616 const Scalar firstPerfTemperature = info.temperature;
2617 // Salt is not an MSW primary variable: use the constant first-perf value.
2618 const EvalWell seg_salt_concentration = info.saltConcentration;
2619 const EvalWell seg_temperature = has_energy ? this->primary_variables_.getSegmentTemperature(seg) : firstPerfTemperature;
2620
2621 // TODO: with the energy equation joins, the num_conservation_quantities will be challenged
2622 std::vector<EvalWell> fluid_composition(this->numConservationQuantities(), 0.0);
2623 for (int idx = 0; idx < this->numConservationQuantities(); ++idx) {
2624 fluid_composition[idx] = this->primary_variables_.surfaceVolumeFraction(seg, idx);
2625 }
2626
2627 return createFluidState(fluid_composition, seg_pressure, seg_temperature,
2628 seg_salt_concentration, deferred_logger);
2629 }
2630
2631 template <typename TypeTag>
2632 template <typename FluidStateT>
2635 surfaceToReservoirRate(const unsigned phaseIdx,
2636 const FluidStateT& fs,
2637 const std::vector<EvalWell>& surface_rates,
2638 const int seg,
2639 const std::string_view context,
2640 DeferredLogger& deferred_logger) const
2641 {
2642 // A wellbore SegmentFluidState already stores EvalWell properties; a reservoir-cell
2643 // fluid state stores reservoir Eval and must be extended to the well derivative space.
2644 auto asEvalWell = [this](const auto& v) -> EvalWell {
2645 if constexpr (std::is_same_v<std::decay_t<decltype(v)>, EvalWell>) {
2646 return v;
2647 } else {
2648 return this->extendEval(v);
2649 }
2650 };
2651
2652 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2653 const EvalWell invB = asEvalWell(fs.invB(phaseIdx));
2654 const bool both_oil_gas = FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)
2655 && FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx);
2656 if (!both_oil_gas || FluidSystem::waterPhaseIdx == phaseIdx) {
2657 return surface_rates[activeCompIdx] / invB;
2658 }
2659
2660 // remove dissolved gas and vaporized oil
2661 const EvalWell rs = asEvalWell(fs.Rs());
2662 const EvalWell rv = asEvalWell(fs.Rv());
2663 const EvalWell d = 1. - rs * rv;
2664 if (d <= 0.0) {
2665 deferred_logger.debug(
2666 fmt::format("Problematic d value {} obtained for well {}, segment {}"
2667 " during {} with rs {}, rv {}. Continue as if no dissolution"
2668 " (rs = 0) and vaporization (rv = 0) for this connection.",
2669 d, this->name(), seg, context, rs, rv));
2670 return surface_rates[activeCompIdx] / invB;
2671 }
2672 const unsigned oilCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2673 const unsigned gasCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2674 if (FluidSystem::gasPhaseIdx == phaseIdx) {
2675 return (surface_rates[gasCompIdx] - rs * surface_rates[oilCompIdx]) / (d * invB);
2676 }
2677 if (FluidSystem::oilPhaseIdx == phaseIdx) {
2678 return (surface_rates[oilCompIdx] - rv * surface_rates[gasCompIdx]) / (d * invB);
2679 }
2680 return EvalWell{0.0};
2681 }
2682
2683 template <typename TypeTag>
2686 computeSegmentEnergyRate(const int seg,
2687 const int upwind_seg,
2688 const SegmentFluidState<EvalWell>& upwind_fs,
2689 const std::string_view context,
2690 DeferredLogger& deferred_logger) const
2691 {
2692 // surface volumetric rates per active phase, scaled by the well efficiency factor
2693 std::vector<EvalWell> surface_rates(this->num_conservation_quantities_, 0.0);
2694 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2695 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2696 continue;
2697 }
2698 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2699 surface_rates[activeCompIdx] =
2700 this->primary_variables_.getSegmentRateUpwinding(seg,
2701 upwind_seg,
2702 activeCompIdx) *
2703 this->well_efficiency_factor_;
2704 }
2705
2706 EvalWell energy_rate(0.0);
2707 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2708 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2709 continue;
2710 }
2711 const EvalWell reservoir_rate =
2712 this->surfaceToReservoirRate(phaseIdx, upwind_fs, surface_rates,
2713 seg, context, deferred_logger);
2714 energy_rate += reservoir_rate * upwind_fs.enthalpy(phaseIdx) * upwind_fs.density(phaseIdx);
2715 }
2716 // scaled to the same magnitude as the mass-balance equations, see energy_scaling_factor_
2717 return energy_scaling_factor_ * energy_rate;
2718 }
2719
2720 template <typename TypeTag>
2721 void
2724 const std::vector<EvalWell>& cq_s,
2725 const int seg,
2726 const int local_perf_index,
2727 DeferredLogger& deferred_logger)
2728 {
2729 const auto& fs = int_quants.fluidState();
2730 // segment fluid state for wellbore properties (used for injecting connections)
2731 const auto& seg_fs = this->segment_fluid_state_[seg];
2732
2733 // TODO: should we only use the reservoir-cell properties for production cases?
2734 EvalWell energy_flux(0.0);
2735 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2736 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2737 continue;
2738 }
2739
2740 const unsigned activeCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::solventComponentIndex(phaseIdx));
2741 // whether the connection is injecting (fluid flows from wellbore into reservoir)
2742 const bool injecting = cq_s[activeCompIdx] > 0.0;
2743
2744 EvalWell cq_r_thermal(0.0);
2745 if (injecting) {
2746 // use segment (wellbore) fluid properties for the upwind state
2747 cq_r_thermal = this->surfaceToReservoirRate(phaseIdx, seg_fs, cq_s,
2748 seg, "energy assembly (injecting)",
2749 deferred_logger);
2750 // \Note: cq_s calculation uses rs, rv and b from the connection cells, while
2751 // the enthalpy and density is based on the wellbore condition in the wellbore,
2752 // some inconsistency can exist here and remain to be investigated and refined.
2753 energy_flux += cq_r_thermal * seg_fs.enthalpy(phaseIdx) * seg_fs.density(phaseIdx);
2754 } else {
2755 // producing connection: use reservoir cell fluid properties
2756 cq_r_thermal = this->surfaceToReservoirRate(phaseIdx, fs, cq_s,
2757 seg, "energy assembly (producing)",
2758 deferred_logger);
2759 energy_flux += cq_r_thermal * this->extendEval(fs.enthalpy(phaseIdx)) * this->extendEval(fs.density(phaseIdx));
2760 }
2761 }
2762 energy_flux *= this->well_efficiency_factor_;
2763 // Reservoir energy source term: kept raw (the reservoir scales it
2764 // centrally in computeSource(), as for standard wells) — do not pre-scale.
2765 this->connectionRates_[local_perf_index][Indices::contiEnergyEqIdx] = Base::restrictEval(energy_flux);
2766
2767 // The well-side energy equation is scaled onto the mass-balance scale
2768 // (energy_scaling_factor_).
2770 assemblePerforationEq(seg, local_perf_index,
2771 MSWEval::PrimaryVariables::Temperature,
2772 energy_scaling_factor_ * energy_flux,
2773 this->linSys_);
2774 }
2775
2776 template <typename TypeTag>
2777 void
2779 const Scalar first_perf_temperature,
2780 const Scalar first_perf_salt_concentration,
2781 DeferredLogger& deferred_logger)
2782 {
2783 if (!this->well_ecl_.isInjector()) return;
2784
2785 std::vector<EvalWell> fluid_composition(FluidSystem::numPhases, 0.0);
2786
2787 // temperature should be the injecting temperature
2788 // pressure should be the BHP
2789 const EvalWell bhp = this->primary_variables_.getSegmentPressure(0);
2790 // Use WINJTEMP when set, otherwise the reservoir temperature at the first
2791 // perforation (as in WellState::initSingleInjector). Calling inj_temperature()
2792 // unconditionally would warn every assembly iteration, and throw with no default.
2793 const EvalWell inj_temperature = this->well_ecl_.hasInjTemperature()
2794 ? EvalWell{this->well_ecl_.inj_temperature()}
2795 : EvalWell{first_perf_temperature};
2796
2797 const auto controls = this->well_ecl_.injectionControls(simulator.vanguard().summaryState());
2798 switch (controls.injector_type) {
2799 case InjectorType::OIL: {
2800 const unsigned oilActiveCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::oilCompIdx);
2801 fluid_composition[oilActiveCompIdx] = 1.0;
2802 break;
2803 }
2804 case InjectorType::GAS: {
2805 const unsigned gasActiveCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::gasCompIdx);
2806 fluid_composition[gasActiveCompIdx] = 1.0;
2807 break;
2808 }
2809 case InjectorType::WATER: {
2810 const unsigned waterActiveCompIdx = FluidSystem::canonicalToActiveCompIdx(FluidSystem::waterCompIdx);
2811 fluid_composition[waterActiveCompIdx] = 1.0;
2812 break;
2813 }
2814 default: {
2815 throw std::logic_error("Unsupported injection type " + std::to_string(static_cast<int>(controls.injector_type)));
2816 }
2817 }
2818
2819 // No injection-salinity keyword yet; reuse the first-perf salt (as for temperature).
2820 const EvalWell inj_salt_concentration{first_perf_salt_concentration};
2821
2822 this->wellhead_fluid_state_ = createFluidState(fluid_composition, bhp, inj_temperature,
2823 inj_salt_concentration, deferred_logger);
2824 }
2825
2826
2827 template <typename TypeTag>
2828 template <typename ValueType>
2829 ValueType
2831 {
2832 auto obtain = [](const auto& val) {
2833 if constexpr (std::is_same_v<ValueType, Scalar>) {
2834 return getValue(val);
2835 } else {
2836 return val;
2837 }
2838 };
2839
2840 ValueType result {0.};
2841 const auto& segment_fluid_state = this->segment_fluid_state_[seg];
2842 const Scalar segment_volume = this->wellEcl().getSegments()[seg].volume();
2843 for (unsigned phaseIdx = 0; phaseIdx < FluidSystem::numPhases; ++phaseIdx) {
2844 if (!FluidSystem::phaseIsActive(phaseIdx)) {
2845 continue;
2846 }
2847 const auto u = obtain(segment_fluid_state.internalEnergy(phaseIdx));
2848 const auto s = obtain(segment_fluid_state.saturation(phaseIdx));
2849 const auto rho = obtain(segment_fluid_state.density(phaseIdx));
2850 result += segment_volume * u * s * rho;
2851 }
2852 return result;
2853 }
2854
2855
2856 template <typename TypeTag>
2857 void
2859 DeferredLogger& deferred_logger)
2860 {
2861 for (int seg = 0; seg < this->numberOfSegments(); ++seg) {
2862 segment_fluid_state_[seg] = this->createSegmentFluidState(seg, info, deferred_logger);
2863 }
2864 }
2865
2866} // namespace Opm
2867
2868#endif
#define OPM_DEFLOG_PROBLEM(Exception, message, deferred_logger)
Definition: DeferredLoggingErrorHelpers.hpp:63
Definition: ConvergenceReport.hpp:38
Definition: DeferredLogger.hpp:57
void problem(const std::string &tag, const std::string &message)
void debug(const std::string &tag, const std::string &message)
Definition: GroupStateHelper.hpp:56
GroupState< Scalar > & groupState() const
Definition: GroupStateHelper.hpp:301
const SummaryState & summaryState() const
Definition: GroupStateHelper.hpp:429
const WellState< Scalar, IndexTraits > & wellState() const
Definition: GroupStateHelper.hpp:510
DeferredLogger & deferredLogger() const
Get the deferred logger.
Definition: GroupStateHelper.hpp:233
WellStateGuard pushWellState(WellState< Scalar, IndexTraits > &well_state)
Definition: GroupStateHelper.hpp:368
GroupStateGuard pushGroupState(GroupState< Scalar > &group_state)
Definition: GroupStateHelper.hpp:345
Definition: GroupState.hpp:41
Class handling assemble of the equation system for MultisegmentWell.
Definition: MultisegmentWellAssemble.hpp:45
PrimaryVariables primary_variables_
The primary variables.
Definition: MultisegmentWellEval.hpp:163
void scaleSegmentRatesWithWellRates(const std::vector< std::vector< int > > &segment_inlets, const std::vector< std::vector< int > > &segment_perforations, WellState< Scalar, IndexTraits > &well_state) const
void scaleSegmentPressuresWithBhp(WellState< Scalar, IndexTraits > &well_state) const
Definition: MultisegmentWell.hpp:42
bool computeWellPotentialsImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) const
Definition: MultisegmentWell_impl.hpp:536
bool iterateWellEqWithSwitching(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, const bool fixed_control, const bool fixed_status, const bool solving_with_zero_rate) override
Definition: MultisegmentWell_impl.hpp:1678
void updateWellState(const Simulator &simulator, const BVectorWell &dwells, const GroupStateHelperType &groupStateHelper, WellStateType &well_state, const Scalar relaxation_factor=1.0)
Definition: MultisegmentWell_impl.hpp:723
void updateWaterThroughput(const double dt, WellStateType &well_state) const override
Definition: MultisegmentWell_impl.hpp:2178
void addWellPressureEquations(PressureMatrix &mat, const BVector &x, const int pressureVarIndex, const bool use_well_weights, const WellStateType &well_state) const override
Definition: MultisegmentWell_impl.hpp:904
void assembleWellEqWithoutIteration(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, WellStateType &well_state, const bool solving_with_zero_rate) override
Definition: MultisegmentWell_impl.hpp:1858
Scalar connectionDensity(const int globalConnIdx, const int openConnIdx) const override
Definition: MultisegmentWell_impl.hpp:869
void addWellContributions(SparseMatrixAdapter &jacobian) const override
Definition: MultisegmentWell_impl.hpp:891
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_indx) const
Definition: MultisegmentWell_impl.hpp:1194
typename Base::FSInfo FSInfo
Definition: MultisegmentWell.hpp:96
EvalWell surfaceToReservoirRate(unsigned phaseIdx, const FluidStateT &fs, const std::vector< EvalWell > &surface_rates, int seg, std::string_view context, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:2635
std::vector< Scalar > computeWellPotentialWithTHP(const WellStateType &well_state, const Simulator &simulator, const GroupStateHelperType &groupStateHelper) const
Definition: MultisegmentWell_impl.hpp:484
Scalar getRefDensity() const override
Definition: MultisegmentWell_impl.hpp:1254
EvalWell getSegmentSurfaceVolume(const int seg_idx, const EvalWell &volume_ratio) const
Definition: MultisegmentWell_impl.hpp:2189
EvalWell computeSegmentEnergyRate(int seg, int upwind_seg, const SegmentFluidState< EvalWell > &upwind_fs, std::string_view context, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:2686
void updateWellStateWithTarget(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) const override
updating the well state based the current control mode
Definition: MultisegmentWell_impl.hpp:183
std::vector< Scalar > getPrimaryVars() const override
Definition: MultisegmentWell_impl.hpp:2404
void computeWellRatesWithBhpIterations(const Simulator &simulator, const Scalar &bhp, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const override
Definition: MultisegmentWell_impl.hpp:408
void checkOperabilityUnderTHPLimit(const Simulator &ebos_simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper) override
Definition: MultisegmentWell_impl.hpp:1499
bool iterateWellEqWithControl(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: MultisegmentWell_impl.hpp:1552
ValueType computeSegmentEnergy(int seg) const
Definition: MultisegmentWell_impl.hpp:2830
std::vector< Scalar > computeCurrentWellRates(const Simulator &simulator, DeferredLogger &deferred_logger) const override
Definition: MultisegmentWell_impl.hpp:2358
void apply(const BVector &x, BVector &Ax) const override
Ax = Ax - C D^-1 B x.
Definition: MultisegmentWell_impl.hpp:228
MultisegmentWell(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: MultisegmentWell_impl.hpp:63
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
void checkOperabilityUnderBHPLimit(const WellStateType &well_state, const Simulator &ebos_simulator, DeferredLogger &deferred_logger) override
Definition: MultisegmentWell_impl.hpp:1262
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:1214
SegmentPvt segmentPvt(const SegmentFluidState< EvalWell > &fluid_state) const
Definition: MultisegmentWell_impl.hpp:1164
void recoverWellSolutionAndUpdateWellState(const Simulator &simulator, const BVector &x, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: MultisegmentWell_impl.hpp:263
void assemblePerforationEnergyEq(const IntensiveQuantities &int_quants, const std::vector< EvalWell > &cq_s, const int seg, const int local_perf_index, DeferredLogger &deferred_logger)
Definition: MultisegmentWell_impl.hpp:2723
bool openCrossFlowAvoidSingularity(const Simulator &simulator) const
Definition: MultisegmentWell_impl.hpp:2116
void computeSegmentFluidProperties(const Simulator &simulator, DeferredLogger &deferred_logger)
Definition: MultisegmentWell_impl.hpp:1146
int setPrimaryVars(typename std::vector< Scalar >::const_iterator it) override
Definition: MultisegmentWell_impl.hpp:2422
void computeWellRatesWithBhp(const Simulator &simulator, const Scalar &bhp, std::vector< Scalar > &well_flux, DeferredLogger &deferred_logger) const override
Definition: MultisegmentWell_impl.hpp:358
void updateSegmentFluidState(const FSInfo &info, DeferredLogger &deferred_logger)
Definition: MultisegmentWell_impl.hpp:2858
Base::template BlackOilFluidStateType< ValueType > SegmentFluidState
Definition: MultisegmentWell.hpp:107
void scaleSegmentRatesAndPressure(WellStateType &well_state) const override
updating the segment pressure and rates based the current bhp and well rates
Definition: MultisegmentWell_impl.hpp:172
bool allDrawDownWrongDirection(const Simulator &simulator) const
Definition: MultisegmentWell_impl.hpp:2125
int debug_cost_counter_
Definition: MultisegmentWell.hpp:244
void updateProductivityIndex(const Simulator &simulator, const WellProdIndexCalculator< Scalar > &wellPICalc, WellStateType &well_state, DeferredLogger &deferred_logger) const override
Definition: MultisegmentWell_impl.hpp:787
typename MultisegmentWellSegments< FluidSystem, Indices >::SegmentPvt SegmentPvt
Definition: MultisegmentWell.hpp:112
std::optional< Scalar > computeBhpAtThpLimitProd(const WellStateType &well_state, const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: MultisegmentWell_impl.hpp:2200
Scalar maxPerfPress(const Simulator &simulator) const override
Definition: MultisegmentWell_impl.hpp:2330
void computePerfRate(const IntensiveQuantities &int_quants, const std::vector< Value > &mob_perfcells, const std::vector< Value > &Tw, const int seg, const int perf, const Value &segment_pressure, const bool &allow_cf, std::vector< Value > &cq_s, Value &perf_press, PerforationRates< Scalar > &perf_rates, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:1073
SegmentFluidState< EvalWell > createSegmentFluidState(int seg, const FSInfo &info, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:2612
SegmentFluidState< ValueType > createFluidState(const std::vector< ValueType > &fluid_composition, const ValueType &pressure, const ValueType &temperature, const ValueType &saltConcentration, DeferredLogger &deferred_logger) const
Definition: MultisegmentWell_impl.hpp:2450
void computeWellPotentials(const Simulator &simulator, const WellStateType &well_state, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_potentials) override
computing the well potentials for group control
Definition: MultisegmentWell_impl.hpp:296
void calculateExplicitQuantities(const Simulator &simulator, const GroupStateHelperType &groupStateHelper) override
Definition: MultisegmentWell_impl.hpp:767
void computePerfCellPressDiffs(const Simulator &simulator)
Definition: MultisegmentWell_impl.hpp:643
void solveEqAndUpdateWellState(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: MultisegmentWell_impl.hpp:613
void updateWellHeadCondition(const Simulator &simulator, const Scalar first_perf_temperature, const Scalar first_perf_salt_concentration, DeferredLogger &deferred_logger)
Definition: MultisegmentWell_impl.hpp:2778
std::optional< Scalar > computeBhpAtThpLimitInj(const Simulator &ebos_simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state) const
Definition: MultisegmentWell_impl.hpp:2275
void updateIPR(const Simulator &ebos_simulator, DeferredLogger &deferred_logger) const override
Definition: MultisegmentWell_impl.hpp:1328
void computeInitialSegmentInventory(DeferredLogger &deferred_logger)
Definition: MultisegmentWell_impl.hpp:700
ConvergenceReport getWellConvergence(const GroupStateHelperType &groupStateHelper, const std::vector< Scalar > &B_avg, const bool relax_tolerance) const override
check whether the well equations get converged for this well
Definition: MultisegmentWell_impl.hpp:202
void updatePrimaryVariables(const GroupStateHelperType &groupStateHelper) override
Definition: MultisegmentWell_impl.hpp:157
void updateIPRImplicit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, WellStateType &well_state) override
Definition: MultisegmentWell_impl.hpp:1429
void computeWellRatesAtBhpLimit(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, std::vector< Scalar > &well_flux) const
Definition: MultisegmentWell_impl.hpp:342
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: MultisegmentWell_impl.hpp:122
std::optional< Scalar > computeBhpAtThpLimitProdWithAlq(const Simulator &simulator, const GroupStateHelperType &groupStateHelper, const SummaryState &summary_state, const Scalar alq_value, bool iterate_if_no_solution) const override
Definition: MultisegmentWell_impl.hpp:2218
void getScaledWellFractions(std::vector< Scalar > &scaled_fractions, DeferredLogger &deferred_logger) const override
Definition: MultisegmentWell_impl.hpp:2439
EvalWell getQs(const int comp_idx) const
Returns scaled rate for a component.
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:217
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.
Scalar mostStrictBhpFromBhpLimits(const SummaryState &summaryState) const
Obtain the most strict BHP from BHP limits.
Well well_ecl_
Definition: WellInterfaceGeneric.hpp:358
void onlyKeepBHPandTHPcontrols(const SummaryState &summary_state, WellStateType &well_state, Well::InjectionControls &inj_controls, Well::ProductionControls &prod_controls) const
void resetDampening()
Definition: WellInterfaceGeneric.hpp:296
std::pair< bool, bool > computeWellPotentials(std::vector< Scalar > &well_potentials, const WellStateType &well_state)
Definition: WellInterfaceIndices.hpp:34
Definition: WellInterface.hpp:79
bool solveWellWithOperabilityCheck(const Simulator &simulator, const double dt, const Well::InjectionControls &inj_controls, const Well::ProductionControls &prod_controls, const GroupStateHelperType &groupStateHelper, WellStateType &well_state)
Definition: WellInterface_impl.hpp:735
GetPropType< TypeTag, Properties::Simulator > Simulator
Definition: WellInterface.hpp:84
typename WellInterfaceFluidSystem< FluidSystem >::RateConverterType RateConverterType
Definition: WellInterface.hpp:110
void getTransMult(Value &trans_mult, const Simulator &simulator, const int cell_idx, Callback &extendEval) const
Definition: WellInterface_impl.hpp:2218
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, 1, 1 > > PressureMatrix
Definition: WellInterface.hpp:100
void getMobility(const Simulator &simulator, const int local_perf_index, std::vector< Value > &mob, Callback &extendEval, DeferredLogger &deferred_logger) const
Definition: WellInterface_impl.hpp:2231
GetPropType< TypeTag, Properties::IntensiveQuantities > IntensiveQuantities
Definition: WellInterface.hpp:89
GetPropType< TypeTag, Properties::Scalar > Scalar
Definition: WellInterface.hpp:85
Dune::BlockVector< VectorBlockType > BVector
Definition: WellInterface.hpp:99
typename Base::ModelParameters ModelParameters
Definition: WellInterface.hpp:116
GetPropType< TypeTag, Properties::FluidSystem > FluidSystem
Definition: WellInterface.hpp:86
typename Base::Eval Eval
Definition: WellInterface.hpp:98
GetPropType< TypeTag, Properties::Indices > Indices
Definition: WellInterface.hpp:88
GetPropType< TypeTag, Properties::SparseMatrixAdapter > SparseMatrixAdapter
Definition: WellInterface.hpp:91
Definition: WellProdIndexCalculator.hpp:37
Scalar connectionProdIndStandard(const std::size_t connIdx, const Scalar connMobility) const
Definition: WellState.hpp:68
const SingleWellState< Scalar, IndexTraits > & well(std::size_t well_index) const
Definition: WellState.hpp:315
@ NONE
Definition: DeferredLogger.hpp:46
Definition: blackoilbioeffectsmodules.hh:45
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)
Static data associated with a well perforation.
Definition: PerforationData.hpp:30
Definition: PerforationData.hpp:56
Scalar dis_gas
Definition: PerforationData.hpp:57
Scalar vap_oil
Definition: PerforationData.hpp:59