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