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