My Project
WellInterface_impl.hpp
1 /*
2  Copyright 2017 SINTEF Digital, Mathematics and Cybernetics.
3  Copyright 2017 Statoil ASA.
4  Copyright 2018 IRIS
5 
6  This file is part of the Open Porous Media project (OPM).
7 
8  OPM is free software: you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation, either version 3 of the License, or
11  (at your option) any later version.
12 
13  OPM is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17 
18  You should have received a copy of the GNU General Public License
19  along with OPM. If not, see <http://www.gnu.org/licenses/>.
20 */
21 
22 #include <opm/parser/eclipse/EclipseState/Schedule/ScheduleTypes.hpp>
23 #include <opm/simulators/utils/DeferredLoggingErrorHelpers.hpp>
24 #include <opm/simulators/wells/GroupState.hpp>
25 #include <opm/simulators/wells/TargetCalculator.hpp>
26 
27 #include <dune/common/version.hh>
28 
29 namespace Opm
30 {
31 
32 
33  template<typename TypeTag>
35  WellInterface(const Well& well,
36  const ParallelWellInfo& pw_info,
37  const int time_step,
38  const ModelParameters& param,
39  const RateConverterType& rate_converter,
40  const int pvtRegionIdx,
41  const int num_components,
42  const int num_phases,
43  const int index_of_well,
44  const std::vector<PerforationData>& perf_data)
45  : WellInterfaceIndices<FluidSystem,Indices,Scalar>(well,
46  pw_info,
47  time_step,
48  rate_converter,
49  pvtRegionIdx,
50  num_components,
51  num_phases,
52  index_of_well,
53  perf_data)
54  , param_(param)
55  {
56  connectionRates_.resize(this->number_of_perforations_);
57 
58  if constexpr (has_solvent || has_zFraction) {
59  if (well.isInjector()) {
60  auto injectorType = this->well_ecl_.injectorType();
61  if (injectorType == InjectorType::GAS) {
62  this->wsolvent_ = this->well_ecl_.getSolventFraction();
63  }
64  }
65  }
66  }
67 
68 
69  template<typename TypeTag>
70  void
72  init(const PhaseUsage* phase_usage_arg,
73  const std::vector<double>& /* depth_arg */,
74  const double gravity_arg,
75  const int /* num_cells */,
76  const std::vector< Scalar >& B_avg)
77  {
78  this->phase_usage_ = phase_usage_arg;
79  this->gravity_ = gravity_arg;
80  B_avg_ = B_avg;
81  }
82 
83 
84 
85 
86  template<typename TypeTag>
87  double
88  WellInterface<TypeTag>::
89  wpolymer() const
90  {
91  if constexpr (has_polymer) {
92  auto injectorType = this->well_ecl_.injectorType();
93 
94  if (injectorType == InjectorType::WATER) {
95  WellPolymerProperties polymer = this->well_ecl_.getPolymerProperties();
96  const double polymer_injection_concentration = polymer.m_polymerConcentration;
97  return polymer_injection_concentration;
98  } else {
99  // Not a water injection well => no polymer.
100  return 0.0;
101  }
102  }
103 
104  return 0.0;
105  }
106 
107 
108 
109 
110 
111  template<typename TypeTag>
112  double
113  WellInterface<TypeTag>::
114  wfoam() const
115  {
116  if constexpr (has_foam) {
117  auto injectorType = this->well_ecl_.injectorType();
118 
119  if (injectorType == InjectorType::GAS) {
120  WellFoamProperties fprop = this->well_ecl_.getFoamProperties();
121  return fprop.m_foamConcentration;
122  } else {
123  // Not a gas injection well => no foam.
124  return 0.0;
125  }
126  }
127 
128  return 0.0;
129  }
130 
131 
132 
133  template<typename TypeTag>
134  double
135  WellInterface<TypeTag>::
136  wsalt() const
137  {
138  if constexpr (has_brine) {
139  auto injectorType = this->well_ecl_.injectorType();
140 
141  if (injectorType == InjectorType::WATER) {
142  WellBrineProperties fprop = this->well_ecl_.getBrineProperties();
143  return fprop.m_saltConcentration;
144  } else {
145  // Not a water injection well => no salt (?).
146  return 0.0;
147  }
148  }
149 
150  return 0.0;
151  }
152 
153  template<typename TypeTag>
154  double
155  WellInterface<TypeTag>::
156  wmicrobes() const
157  {
158  if constexpr (has_micp) {
159  auto injectorType = this->well_ecl_.injectorType();
160 
161  if (injectorType == InjectorType::WATER) {
162  WellMICPProperties microbes = this->well_ecl_.getMICPProperties();
163  const double microbial_injection_concentration = microbes.m_microbialConcentration;
164  return microbial_injection_concentration;
165  } else {
166  // Not a water injection well => no microbes.
167  return 0.0;
168  }
169  }
170 
171  return 0.0;
172  }
173 
174  template<typename TypeTag>
175  double
176  WellInterface<TypeTag>::
177  woxygen() const
178  {
179  if constexpr (has_micp) {
180  auto injectorType = this->well_ecl_.injectorType();
181 
182  if (injectorType == InjectorType::WATER) {
183  WellMICPProperties oxygen = this->well_ecl_.getMICPProperties();
184  const double oxygen_injection_concentration = oxygen.m_oxygenConcentration;
185  return oxygen_injection_concentration;
186  } else {
187  // Not a water injection well => no oxygen.
188  return 0.0;
189  }
190  }
191 
192  return 0.0;
193  }
194 
195  // The urea injection concentration is scaled down by a factor of 10, since its value
196  // can be much bigger than 1 (not doing this slows the simulations). The
197  // corresponding values are scaled accordingly in blackoilmicpmodules.hh when computing
198  // the reactions and also when writing the output files (vtk and eclipse format, i.e.,
199  // vtkblackoilmicpmodule.hh and ecloutputblackoilmodel.hh respectively).
200 
201  template<typename TypeTag>
202  double
203  WellInterface<TypeTag>::
204  wurea() const
205  {
206  if constexpr (has_micp) {
207  auto injectorType = this->well_ecl_.injectorType();
208 
209  if (injectorType == InjectorType::WATER) {
210  WellMICPProperties urea = this->well_ecl_.getMICPProperties();
211  const double urea_injection_concentration = urea.m_ureaConcentration / 10.; //Dividing by scaling factor 10
212  return urea_injection_concentration;
213  } else {
214  // Not a water injection well => no urea.
215  return 0.0;
216  }
217  }
218 
219  return 0.0;
220  }
221 
222  template<typename TypeTag>
223  bool
224  WellInterface<TypeTag>::
225  updateWellControl(const Simulator& ebos_simulator,
226  const IndividualOrGroup iog,
227  WellState& well_state,
228  const GroupState& group_state,
229  DeferredLogger& deferred_logger) /* const */
230  {
231  if (this->wellIsStopped()) {
232  return false;
233  }
234 
235  const auto& summaryState = ebos_simulator.vanguard().summaryState();
236  const auto& schedule = ebos_simulator.vanguard().schedule();
237  const auto& well = this->well_ecl_;
238  auto& ws = well_state.well(this->index_of_well_);
239  std::string from;
240  if (well.isInjector()) {
241  from = Well::InjectorCMode2String(ws.injection_cmode);
242  } else {
243  from = Well::ProducerCMode2String(ws.production_cmode);
244  }
245  bool oscillating = std::count(this->well_control_log_.begin(), this->well_control_log_.end(), from) >= param_.max_number_of_well_switches_;
246 
247  if (oscillating) {
248  // only output frist time
249  bool output = std::count(this->well_control_log_.begin(), this->well_control_log_.end(), from) == param_.max_number_of_well_switches_;
250  if (output) {
251  std::ostringstream ss;
252  ss << " The control model for well " << this->name()
253  << " is oscillating\n"
254  << " We don't allow for more than "
255  << param_.max_number_of_well_switches_
256  << " switches. The control is kept at " << from;
257  deferred_logger.info(ss.str());
258  // add one more to avoid outputting the same info again
259  this->well_control_log_.push_back(from);
260  }
261  return false;
262  }
263  bool changed = false;
264  if (iog == IndividualOrGroup::Individual) {
265  changed = this->checkIndividualConstraints(ws, summaryState);
266  } else if (iog == IndividualOrGroup::Group) {
267  changed = this->checkGroupConstraints(well_state, group_state, schedule, summaryState, deferred_logger);
268  } else {
269  assert(iog == IndividualOrGroup::Both);
270  changed = this->checkConstraints(well_state, group_state, schedule, summaryState, deferred_logger);
271  }
272  Parallel::Communication cc = ebos_simulator.vanguard().grid().comm();
273  // checking whether control changed
274  if (changed) {
275  std::string to;
276  if (well.isInjector()) {
277  to = Well::InjectorCMode2String(ws.injection_cmode);
278  } else {
279  to = Well::ProducerCMode2String(ws.production_cmode);
280  }
281  std::ostringstream ss;
282  ss << " Switching control mode for well " << this->name()
283  << " from " << from
284  << " to " << to;
285  if (cc.size() > 1) {
286  ss << " on rank " << cc.rank();
287  }
288  deferred_logger.debug(ss.str());
289 
290  this->well_control_log_.push_back(from);
291  updateWellStateWithTarget(ebos_simulator, group_state, well_state, deferred_logger);
292  updatePrimaryVariables(well_state, deferred_logger);
293  }
294 
295  return changed;
296  }
297 
298 
299 
300  template<typename TypeTag>
301  void
302  WellInterface<TypeTag>::
303  wellTesting(const Simulator& simulator,
304  const double simulation_time,
305  /* const */ WellState& well_state,
306  const GroupState& group_state,
307  WellTestState& well_test_state,
308  DeferredLogger& deferred_logger)
309  {
310  deferred_logger.info(" well " + this->name() + " is being tested");
311 
312  WellState well_state_copy = well_state;
313  auto& ws = well_state_copy.well(this->indexOfWell());
314 
315  updateWellStateWithTarget(simulator, group_state, well_state_copy, deferred_logger);
316  calculateExplicitQuantities(simulator, well_state_copy, deferred_logger);
317  updatePrimaryVariables(well_state_copy, deferred_logger);
318  initPrimaryVariablesEvaluation();
319 
320  WellTestState welltest_state_temp;
321 
322  bool testWell = true;
323  // if a well is closed because all completions are closed, we need to check each completion
324  // individually. We first open all completions, then we close one by one by calling updateWellTestState
325  // untill the number of closed completions do not increase anymore.
326  while (testWell) {
327  const size_t original_number_closed_completions = welltest_state_temp.num_closed_completions();
328  bool converged = solveWellForTesting(simulator, well_state_copy, group_state, deferred_logger);
329  if (!converged) {
330  const auto msg = fmt::format("WTEST: Well {} is not solvable (physical)", this->name());
331  deferred_logger.debug(msg);
332  return;
333  }
334 
335  updateWellOperability(simulator, well_state_copy, deferred_logger);
336  if ( !this->isOperableAndSolvable() ) {
337  const auto msg = fmt::format("WTEST: Well {} is not operable (physical)", this->name());
338  deferred_logger.debug(msg);
339  return;
340  }
341 
342  std::vector<double> potentials;
343  try {
344  computeWellPotentials(simulator, well_state_copy, potentials, deferred_logger);
345  } catch (const std::exception& e) {
346  const std::string msg = std::string("well ") + this->name() + std::string(": computeWellPotentials() failed during testing for re-opening: ") + e.what();
347  deferred_logger.info(msg);
348  return;
349  }
350  const int np = well_state_copy.numPhases();
351  for (int p = 0; p < np; ++p) {
352  ws.well_potentials[p] = std::abs(potentials[p]);
353  }
354  this->updateWellTestState(well_state_copy.well(this->indexOfWell()), simulation_time, /*writeMessageToOPMLog=*/ false, welltest_state_temp, deferred_logger);
355  this->closeCompletions(welltest_state_temp);
356 
357  // Stop testing if the well is closed or shut due to all completions shut
358  // Also check if number of completions has increased. If the number of closed completions do not increased
359  // we stop the testing.
360  // TODO: it can be tricky here, if the well is shut/closed due to other reasons
361  if ( welltest_state_temp.num_closed_wells() > 0 ||
362  (original_number_closed_completions == welltest_state_temp.num_closed_completions()) ) {
363  testWell = false; // this terminates the while loop
364  }
365  }
366 
367  // update wellTestState if the well test succeeds
368  if (!welltest_state_temp.well_is_closed(this->name())) {
369  well_test_state.open_well(this->name());
370 
371  std::string msg = std::string("well ") + this->name() + std::string(" is re-opened");
372  deferred_logger.info(msg);
373 
374  // also reopen completions
375  for (auto& completion : this->well_ecl_.getCompletions()) {
376  if (!welltest_state_temp.completion_is_closed(this->name(), completion.first))
377  well_test_state.open_completion(this->name(), completion.first);
378  }
379  // set the status of the well_state to open
380  ws.open();
381  well_state = well_state_copy;
382  }
383  }
384 
385 
386 
387 
388  template<typename TypeTag>
389  bool
390  WellInterface<TypeTag>::
391  iterateWellEquations(const Simulator& ebosSimulator,
392  const double dt,
393  WellState& well_state,
394  const GroupState& group_state,
395  DeferredLogger& deferred_logger)
396  {
397  const auto& summary_state = ebosSimulator.vanguard().summaryState();
398  const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
399  const auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
400  bool converged = false;
401  try {
402  converged = this->iterateWellEqWithControl(ebosSimulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
403  } catch (NumericalIssue& e ) {
404  const std::string msg = "Inner well iterations failed for well " + this->name() + " Treat the well as unconverged. ";
405  deferred_logger.warning("INNER_ITERATION_FAILED", msg);
406  converged = false;
407  }
408  return converged;
409  }
410 
411 
412  template<typename TypeTag>
413  bool
414  WellInterface<TypeTag>::
415  solveWellForTesting(const Simulator& ebosSimulator, WellState& well_state, const GroupState& group_state,
416  DeferredLogger& deferred_logger)
417  {
418  // keep a copy of the original well state
419  const WellState well_state0 = well_state;
420  const double dt = ebosSimulator.timeStepSize();
421  const bool converged = iterateWellEquations(ebosSimulator, dt, well_state, group_state, deferred_logger);
422  if (converged) {
423  deferred_logger.debug("WellTest: Well equation for well " + this->name() + " converged");
424  return true;
425  }
426  const int max_iter = param_.max_welleq_iter_;
427  deferred_logger.debug("WellTest: Well equation for well " + this->name() + " failed converging in "
428  + std::to_string(max_iter) + " iterations");
429  well_state = well_state0;
430  return false;
431  }
432 
433 
434  template<typename TypeTag>
435  void
436  WellInterface<TypeTag>::
437  solveWellEquation(const Simulator& ebosSimulator,
438  WellState& well_state,
439  const GroupState& group_state,
440  DeferredLogger& deferred_logger)
441  {
442  if (!this->isOperableAndSolvable())
443  return;
444 
445  // keep a copy of the original well state
446  const WellState well_state0 = well_state;
447  const double dt = ebosSimulator.timeStepSize();
448  const bool converged = iterateWellEquations(ebosSimulator, dt, well_state, group_state, deferred_logger);
449  if (!converged) {
450  const int max_iter = param_.max_welleq_iter_;
451  deferred_logger.debug("Compute initial well solution for well " + this->name() + ". Failed to converge in "
452  + std::to_string(max_iter) + " iterations");
453  well_state = well_state0;
454  }
455  }
456 
457 
458 
459  template <typename TypeTag>
460  void
461  WellInterface<TypeTag>::
462  assembleWellEq(const Simulator& ebosSimulator,
463  const double dt,
464  WellState& well_state,
465  const GroupState& group_state,
466  DeferredLogger& deferred_logger)
467  {
468  const bool old_well_operable = this->operability_status_.isOperableAndSolvable();
469 
470  if (param_.check_well_operability_iter_)
471  checkWellOperability(ebosSimulator, well_state, deferred_logger);
472 
473  // only use inner well iterations for the first newton iterations.
474  const int iteration_idx = ebosSimulator.model().newtonMethod().numIterations();
475  if (iteration_idx < param_.max_niter_inner_well_iter_) {
476  this->operability_status_.solvable = true;
477  bool converged = this->iterateWellEquations(ebosSimulator, dt, well_state, group_state, deferred_logger);
478 
479  // unsolvable wells are treated as not operable and will not be solved for in this iteration.
480  if (!converged) {
481  if (this->shutUnsolvableWells())
482  this->operability_status_.solvable = false;
483  }
484  }
485 
486  const bool well_operable = this->operability_status_.isOperableAndSolvable();
487  if (!well_operable && old_well_operable) {
488  if (this->well_ecl_.getAutomaticShutIn()) {
489  deferred_logger.info(" well " + this->name() + " gets SHUT during iteration ");
490  } else {
491  if (!this->wellIsStopped()) {
492  deferred_logger.info(" well " + this->name() + " gets STOPPED during iteration ");
493  this->stopWell();
494  changed_to_stopped_this_step_ = true;
495  }
496  }
497  } else if (well_operable && !old_well_operable) {
498  deferred_logger.info(" well " + this->name() + " gets REVIVED during iteration ");
499  this->openWell();
500  changed_to_stopped_this_step_ = false;
501  }
502 
503  const auto& summary_state = ebosSimulator.vanguard().summaryState();
504  const auto inj_controls = this->well_ecl_.isInjector() ? this->well_ecl_.injectionControls(summary_state) : Well::InjectionControls(0);
505  const auto prod_controls = this->well_ecl_.isProducer() ? this->well_ecl_.productionControls(summary_state) : Well::ProductionControls(0);
506  assembleWellEqWithoutIteration(ebosSimulator, dt, inj_controls, prod_controls, well_state, group_state, deferred_logger);
507  }
508 
509 
510 
511  template<typename TypeTag>
512  void
513  WellInterface<TypeTag>::addCellRates(RateVector& rates, int cellIdx) const
514  {
515  for (int perfIdx = 0; perfIdx < this->number_of_perforations_; ++perfIdx) {
516  if (this->cells()[perfIdx] == cellIdx) {
517  for (int i = 0; i < RateVector::dimension; ++i) {
518  rates[i] += connectionRates_[perfIdx][i];
519  }
520  }
521  }
522  }
523 
524  template<typename TypeTag>
525  typename WellInterface<TypeTag>::Scalar
526  WellInterface<TypeTag>::volumetricSurfaceRateForConnection(int cellIdx, int phaseIdx) const {
527  for (int perfIdx = 0; perfIdx < this->number_of_perforations_; ++perfIdx) {
528  if (this->cells()[perfIdx] == cellIdx) {
529  const unsigned activeCompIdx = Indices::canonicalToActiveComponentIndex(FluidSystem::solventComponentIndex(phaseIdx));
530  return connectionRates_[perfIdx][activeCompIdx].value();
531  }
532  }
533  // this is not thread safe
534  OPM_THROW(std::invalid_argument, "The well with name " + this->name()
535  + " does not perforate cell " + std::to_string(cellIdx));
536  return 0.0;
537  }
538 
539 
540 
541 
542  template<typename TypeTag>
543  void
544  WellInterface<TypeTag>::
545  checkWellOperability(const Simulator& ebos_simulator,
546  const WellState& well_state,
547  DeferredLogger& deferred_logger)
548  {
549 
550  if (!param_.check_well_operability_) {
551  return;
552  }
553 
554  // focusing on PRODUCER for now
555  if (this->isInjector()) {
556  return;
557  }
558 
559  if (!this->underPredictionMode() ) {
560  return;
561  }
562 
563  if (this->wellIsStopped() && !changed_to_stopped_this_step_) {
564  return;
565  }
566 
567  updateWellOperability(ebos_simulator, well_state, deferred_logger);
568  }
569 
570 
571  template<typename TypeTag>
572  bool
573  WellInterface<TypeTag>::
574  shutUnsolvableWells() const
575  {
576  bool shut_unsolvable_wells = param_.shut_unsolvable_wells_;
577  // the well operability system currently works only for producers in prediction mode
578  return shut_unsolvable_wells && !this->isInjector() && this->underPredictionMode();
579  }
580 
581 
582 
583 
584 
585  template<typename TypeTag>
586  void
587  WellInterface<TypeTag>::
588  updateWellOperability(const Simulator& ebos_simulator,
589  const WellState& well_state,
590  DeferredLogger& deferred_logger)
591  {
592  this->operability_status_.resetOperability();
593 
594  auto current_control = well_state.well(this->index_of_well_).production_cmode;
595  // Operability checking is not free
596  // Only check wells under BHP and THP control
597  if(current_control == Well::ProducerCMode::BHP || current_control == Well::ProducerCMode::THP) {
598  updateIPR(ebos_simulator, deferred_logger);
599  checkOperabilityUnderBHPLimitProducer(well_state, ebos_simulator, deferred_logger);
600  }
601  // we do some extra checking for wells under THP control.
602  if (current_control == Well::ProducerCMode::THP) {
603  checkOperabilityUnderTHPLimitProducer(ebos_simulator, well_state, deferred_logger);
604  }
605  }
606 
607 
608  template<typename TypeTag>
609  void
610  WellInterface<TypeTag>::
611  updateWellStateWithTarget(const Simulator& ebos_simulator,
612  const GroupState& group_state,
613  WellState& well_state,
614  DeferredLogger& deferred_logger) const
615  {
616 
617  // only bhp and wellRates are used to initilize the primaryvariables for standard wells
618  const auto& well = this->well_ecl_;
619  const int well_index = this->index_of_well_;
620  auto& ws = well_state.well(well_index);
621  const auto& pu = this->phaseUsage();
622  const int np = well_state.numPhases();
623  const auto& summaryState = ebos_simulator.vanguard().summaryState();
624  const auto& schedule = ebos_simulator.vanguard().schedule();
625 
626  if (this->wellIsStopped()) {
627  for (int p = 0; p<np; ++p) {
628  ws.surface_rates[p] = 0;
629  }
630  ws.thp = 0;
631  return;
632  }
633 
634  if (this->isInjector() )
635  {
636  const auto& controls = well.injectionControls(summaryState);
637 
638  InjectorType injectorType = controls.injector_type;
639  int phasePos;
640  switch (injectorType) {
641  case InjectorType::WATER:
642  {
643  phasePos = pu.phase_pos[BlackoilPhases::Aqua];
644  break;
645  }
646  case InjectorType::OIL:
647  {
648  phasePos = pu.phase_pos[BlackoilPhases::Liquid];
649  break;
650  }
651  case InjectorType::GAS:
652  {
653  phasePos = pu.phase_pos[BlackoilPhases::Vapour];
654  break;
655  }
656  default:
657  OPM_DEFLOG_THROW(std::runtime_error, "Expected WATER, OIL or GAS as type for injectors " + this->name(), deferred_logger );
658  }
659 
660  const auto current = ws.injection_cmode;
661 
662  switch(current) {
663  case Well::InjectorCMode::RATE:
664  {
665  ws.surface_rates[phasePos] = controls.surface_rate;
666  break;
667  }
668 
669  case Well::InjectorCMode::RESV:
670  {
671  std::vector<double> convert_coeff(this->number_of_phases_, 1.0);
672  this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, convert_coeff);
673  const double coeff = convert_coeff[phasePos];
674  ws.surface_rates[phasePos] = controls.reservoir_rate/coeff;
675  break;
676  }
677 
678  case Well::InjectorCMode::THP:
679  {
680  auto rates = ws.surface_rates;
681  double bhp = this->calculateBhpFromThp(well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
682  ws.bhp = bhp;
683 
684  // if the total rates are negative or zero
685  // we try to provide a better intial well rate
686  // using the well potentials
687  double total_rate = std::accumulate(rates.begin(), rates.end(), 0.0);
688  if (total_rate <= 0.0)
689  ws.surface_rates = ws.well_potentials;
690 
691  break;
692  }
693  case Well::InjectorCMode::BHP:
694  {
695  ws.bhp = controls.bhp_limit;
696  double total_rate = 0.0;
697  for (int p = 0; p<np; ++p) {
698  total_rate += ws.surface_rates[p];
699  }
700  // if the total rates are negative or zero
701  // we try to provide a better intial well rate
702  // using the well potentials
703  if (total_rate <= 0.0)
704  ws.surface_rates = ws.well_potentials;
705 
706  break;
707  }
708  case Well::InjectorCMode::GRUP:
709  {
710  assert(well.isAvailableForGroupControl());
711  const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
712  const double efficiencyFactor = well.getEfficiencyFactor();
713  std::optional<double> target =
714  this->getGroupInjectionTargetRate(group,
715  well_state,
716  group_state,
717  schedule,
718  summaryState,
719  injectorType,
720  efficiencyFactor,
721  deferred_logger);
722  if (target)
723  ws.surface_rates[phasePos] = *target;
724  break;
725  }
726  case Well::InjectorCMode::CMODE_UNDEFINED:
727  {
728  OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name(), deferred_logger );
729  }
730 
731  }
732  }
733  //Producer
734  else
735  {
736  const auto current = ws.production_cmode;
737  const auto& controls = well.productionControls(summaryState);
738  switch (current) {
739  case Well::ProducerCMode::ORAT:
740  {
741  double current_rate = -ws.surface_rates[ pu.phase_pos[Oil] ];
742  // for trivial rates or opposite direction we don't just scale the rates
743  // but use either the potentials or the mobility ratio to initial the well rates
744  if (current_rate > 0.0) {
745  for (int p = 0; p<np; ++p) {
746  ws.surface_rates[p] *= controls.oil_rate/current_rate;
747  }
748  } else {
749  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
750  double control_fraction = fractions[pu.phase_pos[Oil]];
751  if (control_fraction != 0.0) {
752  for (int p = 0; p<np; ++p) {
753  ws.surface_rates[p] = - fractions[p] * controls.oil_rate/control_fraction;
754  }
755  }
756  }
757  break;
758  }
759  case Well::ProducerCMode::WRAT:
760  {
761  double current_rate = -ws.surface_rates[ pu.phase_pos[Water] ];
762  // for trivial rates or opposite direction we don't just scale the rates
763  // but use either the potentials or the mobility ratio to initial the well rates
764  if (current_rate > 0.0) {
765  for (int p = 0; p<np; ++p) {
766  ws.surface_rates[p] *= controls.water_rate/current_rate;
767  }
768  } else {
769  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
770  double control_fraction = fractions[pu.phase_pos[Water]];
771  if (control_fraction != 0.0) {
772  for (int p = 0; p<np; ++p) {
773  ws.surface_rates[p] = - fractions[p] * controls.water_rate/control_fraction;
774  }
775  }
776  }
777  break;
778  }
779  case Well::ProducerCMode::GRAT:
780  {
781  double current_rate = -ws.surface_rates[pu.phase_pos[Gas] ];
782  // or trivial rates or opposite direction we don't just scale the rates
783  // but use either the potentials or the mobility ratio to initial the well rates
784  if (current_rate > 0.0) {
785  for (int p = 0; p<np; ++p) {
786  ws.surface_rates[p] *= controls.gas_rate/current_rate;
787  }
788  } else {
789  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
790  double control_fraction = fractions[pu.phase_pos[Gas]];
791  if (control_fraction != 0.0) {
792  for (int p = 0; p<np; ++p) {
793  ws.surface_rates[p] = - fractions[p] * controls.gas_rate/control_fraction;
794  }
795  }
796  }
797 
798  break;
799 
800  }
801  case Well::ProducerCMode::LRAT:
802  {
803  double current_rate = -ws.surface_rates[ pu.phase_pos[Water] ]
804  - ws.surface_rates[ pu.phase_pos[Oil] ];
805  // or trivial rates or opposite direction we don't just scale the rates
806  // but use either the potentials or the mobility ratio to initial the well rates
807  if (current_rate > 0.0) {
808  for (int p = 0; p<np; ++p) {
809  ws.surface_rates[p] *= controls.liquid_rate/current_rate;
810  }
811  } else {
812  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
813  double control_fraction = fractions[pu.phase_pos[Water]] + fractions[pu.phase_pos[Oil]];
814  if (control_fraction != 0.0) {
815  for (int p = 0; p<np; ++p) {
816  ws.surface_rates[p] = - fractions[p] * controls.liquid_rate / control_fraction;
817  }
818  }
819  }
820  break;
821  }
822  case Well::ProducerCMode::CRAT:
823  {
824  OPM_DEFLOG_THROW(std::runtime_error, "CRAT control not supported " << this->name(), deferred_logger);
825  }
826  case Well::ProducerCMode::RESV:
827  {
828  std::vector<double> convert_coeff(this->number_of_phases_, 1.0);
829  this->rateConverter_.calcCoeff(/*fipreg*/ 0, this->pvtRegionIdx_, convert_coeff);
830  double total_res_rate = 0.0;
831  for (int p = 0; p<np; ++p) {
832  total_res_rate -= ws.surface_rates[p] * convert_coeff[p];
833  }
834  if (controls.prediction_mode) {
835  // or trivial rates or opposite direction we don't just scale the rates
836  // but use either the potentials or the mobility ratio to initial the well rates
837  if (total_res_rate > 0.0) {
838  for (int p = 0; p<np; ++p) {
839  ws.surface_rates[p] *= controls.resv_rate/total_res_rate;
840  }
841  } else {
842  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
843  for (int p = 0; p<np; ++p) {
844  ws.surface_rates[p] = - fractions[p] * controls.resv_rate / convert_coeff[p];
845  }
846  }
847  } else {
848  std::vector<double> hrates(this->number_of_phases_,0.);
849  if (FluidSystem::phaseIsActive(FluidSystem::waterPhaseIdx)) {
850  hrates[pu.phase_pos[Water]] = controls.water_rate;
851  }
852  if (FluidSystem::phaseIsActive(FluidSystem::oilPhaseIdx)) {
853  hrates[pu.phase_pos[Oil]] = controls.oil_rate;
854  }
855  if (FluidSystem::phaseIsActive(FluidSystem::gasPhaseIdx)) {
856  hrates[pu.phase_pos[Gas]] = controls.gas_rate;
857  }
858  std::vector<double> hrates_resv(this->number_of_phases_,0.);
859  this->rateConverter_.calcReservoirVoidageRates(/*fipreg*/ 0, this->pvtRegionIdx_, hrates, hrates_resv);
860  double target = std::accumulate(hrates_resv.begin(), hrates_resv.end(), 0.0);
861  // or trivial rates or opposite direction we don't just scale the rates
862  // but use either the potentials or the mobility ratio to initial the well rates
863  if (total_res_rate > 0.0) {
864  for (int p = 0; p<np; ++p) {
865  ws.surface_rates[p] *= target/total_res_rate;
866  }
867  } else {
868  const std::vector<double> fractions = initialWellRateFractions(ebos_simulator, well_state);
869  for (int p = 0; p<np; ++p) {
870  ws.surface_rates[p] = - fractions[p] * target / convert_coeff[p];
871  }
872  }
873 
874  }
875  break;
876  }
877  case Well::ProducerCMode::BHP:
878  {
879  ws.bhp = controls.bhp_limit;
880  double total_rate = 0.0;
881  for (int p = 0; p<np; ++p) {
882  total_rate -= ws.surface_rates[p];
883  }
884  // if the total rates are negative or zero
885  // we try to provide a better intial well rate
886  // using the well potentials
887  if (total_rate <= 0.0){
888  for (int p = 0; p<np; ++p) {
889  ws.surface_rates[p] = -ws.well_potentials[p];
890  }
891  }
892  break;
893  }
894  case Well::ProducerCMode::THP:
895  {
896  auto rates = ws.surface_rates;
897  double bhp = this->calculateBhpFromThp(well_state, rates, well, summaryState, this->getRefDensity(), deferred_logger);
898  ws.bhp = bhp;
899 
900  // if the total rates are negative or zero
901  // we try to provide a better intial well rate
902  // using the well potentials
903  double total_rate = -std::accumulate(rates.begin(), rates.end(), 0.0);
904  if (total_rate <= 0.0){
905  for (int p = 0; p<np; ++p) {
906  ws.surface_rates[p] = -ws.well_potentials[p];
907  }
908  }
909  break;
910  }
911  case Well::ProducerCMode::GRUP:
912  {
913  assert(well.isAvailableForGroupControl());
914  const auto& group = schedule.getGroup(well.groupName(), this->currentStep());
915  const double efficiencyFactor = well.getEfficiencyFactor();
916  double scale = this->getGroupProductionTargetRate(group,
917  well_state,
918  group_state,
919  schedule,
920  summaryState,
921  efficiencyFactor);
922 
923  // we don't want to scale with zero and get zero rates.
924  if (scale > 0) {
925  for (int p = 0; p<np; ++p) {
926  ws.surface_rates[p] *= scale;
927  }
928  }
929  break;
930  }
931  case Well::ProducerCMode::CMODE_UNDEFINED:
932  case Well::ProducerCMode::NONE:
933  {
934  OPM_DEFLOG_THROW(std::runtime_error, "Well control must be specified for well " + this->name() , deferred_logger);
935  }
936 
937  break;
938  } // end of switch
939  }
940  }
941 
942  template<typename TypeTag>
943  std::vector<double>
944  WellInterface<TypeTag>::
945  initialWellRateFractions(const Simulator& ebosSimulator, const WellState& well_state) const
946  {
947  const int np = this->number_of_phases_;
948  std::vector<double> scaling_factor(np);
949  const auto& ws = well_state.well(this->index_of_well_);
950 
951  double total_potentials = 0.0;
952  for (int p = 0; p<np; ++p) {
953  total_potentials += ws.well_potentials[p];
954  }
955  if (total_potentials > 0) {
956  for (int p = 0; p<np; ++p) {
957  scaling_factor[p] = ws.well_potentials[p] / total_potentials;
958  }
959  return scaling_factor;
960  }
961  // if we don't have any potentials we weight it using the mobilites
962  // We only need approximation so we don't bother with the vapporized oil and dissolved gas
963  double total_tw = 0;
964  const int nperf = this->number_of_perforations_;
965  for (int perf = 0; perf < nperf; ++perf) {
966  total_tw += this->well_index_[perf];
967  }
968  for (int perf = 0; perf < nperf; ++perf) {
969  const int cell_idx = this->well_cells_[perf];
970  const auto& intQuants = *(ebosSimulator.model().cachedIntensiveQuantities(cell_idx, /*timeIdx=*/0));
971  const auto& fs = intQuants.fluidState();
972  const double well_tw_fraction = this->well_index_[perf] / total_tw;
973  double total_mobility = 0.0;
974  for (int p = 0; p < np; ++p) {
975  int ebosPhaseIdx = this->flowPhaseToEbosPhaseIdx(p);
976  total_mobility += fs.invB(ebosPhaseIdx).value() * intQuants.mobility(ebosPhaseIdx).value();
977  }
978  for (int p = 0; p < np; ++p) {
979  int ebosPhaseIdx = this->flowPhaseToEbosPhaseIdx(p);
980  scaling_factor[p] += well_tw_fraction * fs.invB(ebosPhaseIdx).value() * intQuants.mobility(ebosPhaseIdx).value() / total_mobility;
981  }
982  }
983  return scaling_factor;
984  }
985 
986 
987 
988  template <typename TypeTag>
989  void
991  updateWellStateRates(const Simulator& ebosSimulator,
992  WellState& well_state,
993  DeferredLogger& deferred_logger) const
994  {
995  // Check if the rates of this well only are single-phase, do nothing
996  // if more than one nonzero rate.
997  auto& ws = well_state.well(this->index_of_well_);
998  int nonzero_rate_index = -1;
999  for (int p = 0; p < this->number_of_phases_; ++p) {
1000  if (ws.surface_rates[p] != 0.0) {
1001  if (nonzero_rate_index == -1) {
1002  nonzero_rate_index = p;
1003  } else {
1004  // More than one nonzero rate.
1005  return;
1006  }
1007  }
1008  }
1009  if (nonzero_rate_index == -1) {
1010  // No nonzero rates.
1011  return;
1012  }
1013 
1014  // Calculate the rates that follow from the current primary variables.
1015  std::vector<double> well_q_s = computeCurrentWellRates(ebosSimulator, deferred_logger);
1016 
1017  // Set the currently-zero phase flows to be nonzero in proportion to well_q_s.
1018  const double initial_nonzero_rate = ws.surface_rates[nonzero_rate_index];
1019  const int comp_idx_nz = this->flowPhaseToEbosCompIdx(nonzero_rate_index);
1020  for (int p = 0; p < this->number_of_phases_; ++p) {
1021  if (p != nonzero_rate_index) {
1022  const int comp_idx = this->flowPhaseToEbosCompIdx(p);
1023  double& rate = ws.surface_rates[p];
1024  rate = (initial_nonzero_rate/well_q_s[comp_idx_nz]) * (well_q_s[comp_idx]);
1025  }
1026  }
1027  }
1028 
1029 
1030 } // namespace Opm
Definition: DeferredLogger.hpp:57
Class encapsulating some information about parallel wells.
Definition: ParallelWellInfo.hpp:252
Definition: WellInterfaceIndices.hpp:35
Definition: WellInterface.hpp:71
void updateWellStateRates(const Simulator &ebosSimulator, WellState &well_state, DeferredLogger &deferred_logger) const
Modify the well_state's rates if there is only one nonzero rate.
Definition: WellInterface_impl.hpp:991
WellInterface(const Well &well, const ParallelWellInfo &pw_info, const int time_step, const ModelParameters &param, const RateConverterType &rate_converter, const int pvtRegionIdx, const int num_components, const int num_phases, const int index_of_well, const std::vector< PerforationData > &perf_data)
Constructor.
Definition: WellInterface_impl.hpp:35
The state of a set of wells, tailored for use by the fully implicit blackoil simulator.
Definition: WellState.hpp:56
This file contains a set of helper functions used by VFPProd / VFPInj.
Definition: BlackoilPhases.hpp:26
PhaseUsage phaseUsage(const Phases &phases)
Determine the active phases.
Definition: phaseUsageFromDeck.cpp:33
Solver parameters for the BlackoilModel.
Definition: BlackoilModelParametersEbos.hpp:327
Definition: BlackoilPhases.hpp:45