-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathBlackoilWellModelGeneric.cpp
2129 lines (1871 loc) · 86.7 KB
/
BlackoilWellModelGeneric.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2016 SINTEF ICT, Applied Mathematics.
Copyright 2016 - 2017 Statoil ASA.
Copyright 2017 Dr. Blatt - HPC-Simulation-Software & Services
Copyright 2016 - 2018 IRIS AS
This file is part of the Open Porous Media project (OPM).
OPM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OPM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <opm/simulators/wells/BlackoilWellModelGeneric.hpp>
#include <opm/common/ErrorMacros.hpp>
#include <opm/common/TimingMacros.hpp>
#include <opm/output/data/GuideRateValue.hpp>
#include <opm/output/data/Groups.hpp>
#include <opm/output/data/Wells.hpp>
#include <opm/output/eclipse/RestartValue.hpp>
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/input/eclipse/Schedule/Action/SimulatorUpdate.hpp>
#include <opm/input/eclipse/Schedule/Group/GConSale.hpp>
#include <opm/input/eclipse/Schedule/Group/GroupEconProductionLimits.hpp>
#include <opm/input/eclipse/Schedule/Group/GConSump.hpp>
#include <opm/input/eclipse/Schedule/Group/GuideRateConfig.hpp>
#include <opm/input/eclipse/Schedule/Group/GuideRate.hpp>
#include <opm/input/eclipse/Schedule/Network/Balance.hpp>
#include <opm/input/eclipse/Schedule/Network/ExtNetwork.hpp>
#include <opm/input/eclipse/Schedule/Schedule.hpp>
#include <opm/input/eclipse/Schedule/ScheduleTypes.hpp>
#include <opm/input/eclipse/Schedule/Well/WellConnections.hpp>
#include <opm/input/eclipse/Schedule/Well/WellTestConfig.hpp>
#include <opm/input/eclipse/Units/Units.hpp>
#include <opm/models/utils/parametersystem.hpp>
#include <opm/simulators/utils/DeferredLogger.hpp>
#include <opm/simulators/wells/BlackoilWellModelConstraints.hpp>
#include <opm/simulators/wells/BlackoilWellModelGuideRates.hpp>
#include <opm/simulators/wells/BlackoilWellModelRestart.hpp>
#include <opm/simulators/wells/GasLiftStage2.hpp>
#include <opm/simulators/wells/GroupEconomicLimitsChecker.hpp>
#include <opm/simulators/wells/ParallelWBPCalculation.hpp>
#include <opm/simulators/wells/VFPProperties.hpp>
#include <opm/simulators/wells/WellFilterCake.hpp>
#include <opm/simulators/wells/WellGroupHelpers.hpp>
#include <opm/simulators/wells/WellInterfaceGeneric.hpp>
#include <opm/simulators/wells/WellState.hpp>
#if HAVE_MPI
#include <opm/simulators/utils/MPISerializer.hpp>
#endif
#include <algorithm>
#include <cassert>
#include <functional>
#include <stdexcept>
#include <sstream>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <fmt/format.h>
// #include <opm/input/eclipse/Schedule/WellTraj/RigEclipseWellLogExtractor.hpp>
// #include <external/resinsight/ReservoirDataModel/RigWellLogExtractionTools.h>
// #include <external/resinsight/ReservoirDataModel/RigWellPath.h>
// #include <external/resinsight/ReservoirDataModel/cvfGeometryTools.h>
// #include <external/resinsight/ReservoirDataModel/RigWellLogExtractor.h>
// #include <external/resinsight/ReservoirDataModel/RigCellGeometryTools.h>
// #include <external/resinsight/CommonCode/cvfStructGrid.h>
// #include <external/resinsight/LibGeometry/cvfBoundingBox.h>
// #include <opm/grid/common/CartesianIndexMapper.hpp>
// #include <dune/geometry/referenceelements.hh>
// #include <dune/grid/common/mcmgmapper.hh>
// #include <dune/grid/common/gridenums.hh>
#include <opm/input/eclipse/Schedule/WellTraj/RigEclipseWellLogExtractorGrid.hpp>
#include <opm/input/eclipse/Schedule/WellTraj/RigEclipseWellLogExtractorGrid_impl.hpp>//hack
#include "BoundingBoxTree.hpp"
namespace Opm {
template<class Scalar>
BlackoilWellModelGeneric<Scalar>::
BlackoilWellModelGeneric(Schedule& schedule,
const SummaryState& summaryState,
const EclipseState& eclState,
const PhaseUsage& phase_usage,
const Parallel::Communication& comm)
: schedule_(schedule)
, summaryState_(summaryState)
, eclState_(eclState)
, comm_(comm)
, wbp_(*this)
, phase_usage_(phase_usage)
, terminal_output_(comm_.rank() == 0 &&
Parameters::Get<Parameters::EnableTerminalOutput>())
, guideRate_(schedule)
, active_wgstate_(phase_usage)
, last_valid_wgstate_(phase_usage)
, nupcol_wgstate_(phase_usage)
{
const auto numProcs = comm_.size();
this->not_on_process_ = [this, numProcs](const Well& well) {
if (numProcs == decltype(numProcs){1})
return false;
// Recall: false indicates NOT active!
const auto value = std::make_pair(well.name(), true);
auto candidate = std::lower_bound(this->parallel_well_info_.begin(),
this->parallel_well_info_.end(),
value);
return (candidate == this->parallel_well_info_.end())
|| (*candidate != value);
};
const auto& node_pressures = eclState.getRestartNetworkPressures();
if (node_pressures.has_value()) {
if constexpr (std::is_same_v<Scalar,double>) {
this->node_pressures_ = node_pressures.value();
} else {
for (const auto& it : node_pressures.value()) {
this->node_pressures_[it.first] = it.second;
}
}
}
}
template<class Scalar>
int BlackoilWellModelGeneric<Scalar>::
numLocalWells() const
{
return wells_ecl_.size();
}
template<class Scalar>
int BlackoilWellModelGeneric<Scalar>::
numPhases() const
{
return phase_usage_.num_phases;
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
hasLocalWell(const std::string& wname) const
{
return std::any_of(this->wells_ecl_.begin(),
this->wells_ecl_.end(),
[&wname](const Well& well)
{
return well.name() == wname;
});
}
template<class Scalar>
bool
BlackoilWellModelGeneric<Scalar>::
hasOpenLocalWell(const std::string& wname) const
{
return std::any_of(well_container_generic_.begin(),
well_container_generic_.end(),
[&wname](const auto* elem) -> bool
{
return elem->name() == wname;
});
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
wellsActive() const
{
return wells_active_;
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
networkActive() const
{
return network_active_;
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
anyMSWellOpenLocal() const
{
for (const auto& well : wells_ecl_) {
if (well.isMultiSegment()) {
return true;
}
}
return false;
}
template<class Scalar>
const Well& BlackoilWellModelGeneric<Scalar>::
getWellEcl(const std::string& well_name) const
{
// finding the iterator of the well in wells_ecl
auto well_ecl = std::find_if(wells_ecl_.begin(),
wells_ecl_.end(),
[&well_name](const Well& elem)->bool {
return elem.name() == well_name;
});
assert(well_ecl != wells_ecl_.end());
return *well_ecl;
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
initFromRestartFile(const RestartValue& restartValues,
std::unique_ptr<WellTestState> wtestState,
const std::size_t numCells,
bool handle_ms_well)
{
// The restart step value is used to identify wells present at the given
// time step. Wells that are added at the same time step as RESTART is initiated
// will not be present in a restart file. Use the previous time step to retrieve
// wells that have information written to the restart file.
const int report_step = std::max(eclState_.getInitConfig().getRestartStep() - 1, 0);
const auto& config = this->schedule()[report_step].guide_rate();
// wells_ecl_ should only contain wells on this processor.
wells_ecl_ = getLocalWells(report_step);
this->local_parallel_well_info_ = createLocalParallelWellInfo(wells_ecl_);
this->initializeWellProdIndCalculators();
initializeWellPerfData();
handle_ms_well &= anyMSWellOpenLocal();
// Resize for restart step
this->wellState().resize(this->wells_ecl_, this->local_parallel_well_info_,
this->schedule(), handle_ms_well, numCells,
this->well_perf_data_, this->summaryState_);
BlackoilWellModelRestart(*this).
loadRestartData(restartValues.wells,
restartValues.grp_nwrk,
handle_ms_well,
this->wellState(),
this->groupState());
if (config.has_model()) {
BlackoilWellModelRestart(*this).
loadRestartGuideRates(report_step,
config.model().target(),
restartValues.wells,
this->guideRate_);
BlackoilWellModelRestart(*this).
loadRestartGuideRates(report_step,
config,
restartValues.grp_nwrk.groupData,
this->guideRate_);
this->guideRate_.updateGuideRateExpiration(this->schedule().seconds(report_step), report_step);
}
this->active_wgstate_.wtest_state(std::move(wtestState));
this->commitWGState();
initial_step_ = false;
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
prepareDeserialize(int report_step, const std::size_t numCells, bool handle_ms_well)
{
// wells_ecl_ should only contain wells on this processor.
wells_ecl_ = getLocalWells(report_step);
this->local_parallel_well_info_ = createLocalParallelWellInfo(wells_ecl_);
this->initializeWellProdIndCalculators();
initializeWellPerfData();
if (! this->wells_ecl_.empty()) {
handle_ms_well &= anyMSWellOpenLocal();
this->wellState().resize(this->wells_ecl_, this->local_parallel_well_info_,
this->schedule(), handle_ms_well, numCells,
this->well_perf_data_, this->summaryState_);
}
this->wellState().clearWellRates();
this->commitWGState();
this->updateNupcolWGState();
}
template<class Scalar>
std::vector<Well> BlackoilWellModelGeneric<Scalar>::
getLocalWells(const int timeStepIdx) const
{
auto w = schedule().getWells(timeStepIdx);
w.erase(std::remove_if(w.begin(), w.end(), not_on_process_), w.end());
return w;
}
template<class Scalar>
std::vector<std::reference_wrapper<ParallelWellInfo<Scalar>>>
BlackoilWellModelGeneric<Scalar>::
createLocalParallelWellInfo(const std::vector<Well>& wells)
{
std::vector<std::reference_wrapper<ParallelWellInfo<Scalar>>> local_parallel_well_info;
local_parallel_well_info.reserve(wells.size());
for (const auto& well : wells)
{
auto wellPair = std::make_pair(well.name(), true);
auto pwell = std::lower_bound(parallel_well_info_.begin(),
parallel_well_info_.end(),
wellPair);
assert(pwell != parallel_well_info_.end() &&
*pwell == wellPair);
local_parallel_well_info.push_back(std::ref(*pwell));
}
return local_parallel_well_info;
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
initializeWellProdIndCalculators()
{
this->prod_index_calc_.clear();
this->prod_index_calc_.reserve(this->wells_ecl_.size());
for (const auto& well : this->wells_ecl_) {
this->prod_index_calc_.emplace_back(well);
}
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
initializeWellPerfData(Dune::CpGrid* cpgrid)
{
well_perf_data_.resize(wells_ecl_.size());
this->conn_idx_map_.clear();
this->conn_idx_map_.reserve(wells_ecl_.size());
int well_index = 0;
for (auto& well : wells_ecl_) {
int connection_index = 0;
// INVALID_ECL_INDEX marks no above perf available
int connection_index_above = ParallelWellInfo<Scalar>::INVALID_ECL_INDEX;
bool recalculated = false;
auto& connections = well.getConnections();
if( ! (cpgrid == NULL) && connections.hasTraj()){
// recalculate connections
external::cvf::ref<external::cvf::BoundingBoxTree> cellSearchTree;
external::buildBoundingBoxTree(cellSearchTree, *cpgrid);
connections.recomputeConnections(*cpgrid,cellSearchTree);
recalculated = true;
}
well_perf_data_[well_index].clear();
well_perf_data_[well_index].reserve(well.getConnections().size());
auto& connIdxMap = this->conn_idx_map_
.emplace_back(well.getConnections().size());
CheckDistributedWellConnections checker {
well, this->local_parallel_well_info_[well_index].get()
};
bool hasFirstConnection = false;
bool firstOpenConnection = true;
auto& parallelWellInfo = this->local_parallel_well_info_[well_index].get();
parallelWellInfo.beginReset();
for (const auto& connection : well.getConnections()) {
int active_index;
if(!recalculated){
active_index =
this->compressedIndexForInterior(connection.global_index()); // completly strang for LGR
} else {
active_index = connection.global_index();
}
const auto connIsOpen =
connection.state() == Connection::State::OPEN;
if (active_index >= 0) {
connIdxMap.addActiveConnection(connection_index, connIsOpen);
}
if ((connIsOpen && (active_index >= 0)) || !connIsOpen) {
checker.connectionFound(connection_index);
}
if (connIsOpen) {
if (active_index >= 0) {
if (firstOpenConnection) {
hasFirstConnection = true;
}
auto& pd = well_perf_data_[well_index].emplace_back();
pd.cell_index = active_index;
pd.connection_transmissibility_factor = connection.CF();
pd.satnum_id = connection.satTableId();
pd.ecl_index = connection_index;
parallelWellInfo.pushBackEclIndex(connection_index_above,
connection_index);
}
firstOpenConnection = false;
// Next time this index is the one above as each open
// connection is stored somewhere.
connection_index_above = connection_index;
}
else if (connection.state() != Connection::State::SHUT) {
OPM_THROW(std::runtime_error,
fmt::format("Connection state '{}' not handled",
Connection::State2String(connection.state())));
}
// Note: we rely on the connections being filtered! I.e., there
// are only connections to active cells in the global grid.
++connection_index;
}
parallelWellInfo.endReset();
checker.checkAllConnectionsFound();
parallelWellInfo.communicateFirstPerforation(hasFirstConnection);
++well_index;
}
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
checkGEconLimits(
const Group& group,
const double simulation_time,
const int report_step_idx,
DeferredLogger& deferred_logger)
{
// call recursively down the group hiearchy
for (const std::string& group_name : group.groups()) {
checkGEconLimits( schedule().getGroup(group_name, report_step_idx),
simulation_time, report_step_idx, deferred_logger);
}
// check if gecon is used for this group
if (!schedule()[report_step_idx].gecon().has_group(group.name())) {
return;
}
GroupEconomicLimitsChecker<Scalar> checker {
*this, wellTestState(), group, simulation_time, report_step_idx, deferred_logger
};
if (checker.minOilRate() || checker.minGasRate()) {
checker.closeWells();
}
else if (checker.waterCut() || checker.GOR() || checker.WGR()) {
checker.doWorkOver();
}
if (checker.endRun() && (checker.numProducersOpenInitially() >= 1)
&& (checker.numProducersOpen() == 0))
{
checker.activateEndRun();
}
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
checkGconsaleLimits(const Group& group,
WellState<Scalar>& well_state,
const int reportStepIdx,
DeferredLogger& deferred_logger)
{
// call recursively down the group hiearchy
for (const std::string& groupName : group.groups()) {
checkGconsaleLimits( schedule().getGroup(groupName, reportStepIdx), well_state, reportStepIdx, deferred_logger);
}
// only for groups with gas injection controls
if (!group.hasInjectionControl(Phase::GAS)) {
return;
}
// check if gconsale is used for this group
if (!schedule()[reportStepIdx].gconsale().has(group.name()))
return;
std::string ss;
const auto& gconsale = schedule()[reportStepIdx].gconsale().get(group.name(), summaryState_);
const Group::ProductionCMode& oldProductionControl = this->groupState().production_control(group.name());
int gasPos = phase_usage_.phase_pos[BlackoilPhases::Vapour];
Scalar production_rate = WellGroupHelpers<Scalar>::sumWellSurfaceRates(group,
schedule(),
well_state,
reportStepIdx,
gasPos,
/*isInjector*/false);
Scalar injection_rate = WellGroupHelpers<Scalar>::sumWellSurfaceRates(group,
schedule(),
well_state,
reportStepIdx,
gasPos,
/*isInjector*/true);
// sum over all nodes
injection_rate = comm_.sum(injection_rate);
production_rate = comm_.sum(production_rate);
Scalar sales_rate = production_rate - injection_rate;
Scalar production_target = gconsale.sales_target + injection_rate;
// add import rate and subtract consumption rate for group for gas
if (phase_usage_.phase_used[BlackoilPhases::Vapour]) {
const auto& [consumption_rate, import_rate] = this->groupState().gconsump_rates(group.name());
sales_rate += import_rate;
sales_rate -= consumption_rate;
production_target -= import_rate;
production_target += consumption_rate;
}
if (sales_rate > gconsale.max_sales_rate) {
switch (gconsale.max_proc) {
case GConSale::MaxProcedure::NONE: {
if (oldProductionControl != Group::ProductionCMode::GRAT && oldProductionControl != Group::ProductionCMode::NONE) {
ss = fmt::format("Group sales exceed maximum limit, but the action is NONE for {}. Nothing happens",
group.name());
}
break;
}
case GConSale::MaxProcedure::CON: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit CON not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::CON_P: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit CON_P not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::WELL: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit WELL not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::PLUG: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit PLUG not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::MAXR: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit MAXR not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::END: {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + "GCONSALE exceed limit END not implemented", deferred_logger);
break;
}
case GConSale::MaxProcedure::RATE: {
this->groupState().production_control(group.name(), Group::ProductionCMode::GRAT);
ss = fmt::format("Maximum GCONSALE limit violated for {}. "
"The group is switched from {} to {} "
"and limited by the maximum sales rate after "
"consumption and import are considered",
group.name(),
Group::ProductionCMode2String(oldProductionControl),
Group::ProductionCMode2String(Group::ProductionCMode::GRAT));
this->groupState().update_grat_sales_target(group.name(), production_target);
break;
}
default:
throw("Invalid procedure for maximum rate limit selected for group" + group.name());
}
}
if (sales_rate < gconsale.min_sales_rate) {
const Group::ProductionCMode& currentProductionControl = this->groupState().production_control(group.name());
if ( currentProductionControl == Group::ProductionCMode::GRAT ) {
ss = fmt::format("Group {} has sale rate less then minimum permitted value and is under GRAT control.\n"
"The GRAT is increased to meet the sales minimum rate.",
group.name());
this->groupState().update_grat_sales_target(group.name(), production_target);
//} else if () {//TODO add action for WGASPROD
//} else if () {//TODO add action for drilling queue
} else {
ss = fmt::format("Group {} has sale rate less then minimum permitted value but cannot increase the group production rate \n"
"or adjust gas production using WGASPROD or drill new wells to meet the sales target. \n"
"Note that WGASPROD and drilling queues are not implemented in Flow. No action is taken.",
group.name());
}
}
if (gconsale.sales_target < 0.0) {
OPM_DEFLOG_THROW(std::runtime_error, "Group " + group.name() + " has sale rate target less then zero. Not implemented in Flow" , deferred_logger);
}
if (!ss.empty() && comm_.rank() == 0)
deferred_logger.info(ss);
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
checkGroupHigherConstraints(const Group& group,
DeferredLogger& deferred_logger,
const int reportStepIdx,
const int max_number_of_group_switch)
{
// Set up coefficients for RESV <-> surface rate conversion.
// Use the pvtRegionIdx from the top cell of the first well.
// TODO fix this!
// This is only used for converting RESV rates.
// What is the proper approach?
const int fipnum = 0;
int pvtreg = well_perf_data_.empty() || well_perf_data_[0].empty()
? pvt_region_idx_[0]
: pvt_region_idx_[well_perf_data_[0][0].cell_index];
bool changed = false;
if ( comm_.size() > 1)
{
// Just like in the sequential case the pvtregion is determined
// by the first cell of the first well. What is the first well
// is decided by the order in the Schedule using Well::seqIndex()
int firstWellIndex = well_perf_data_.empty() ?
std::numeric_limits<int>::max() : wells_ecl_[0].seqIndex();
auto regIndexPair = std::make_pair(pvtreg, firstWellIndex);
std::vector<decltype(regIndexPair)> pairs(comm_.size());
comm_.allgather(®IndexPair, 1, pairs.data());
pvtreg = std::min_element(pairs.begin(), pairs.end(),
[](const auto& p1, const auto& p2){ return p1.second < p2.second;})
->first;
}
std::vector<Scalar> rates(phase_usage_.num_phases, 0.0);
bool isField = group.name() == "FIELD";
if (!isField && group.isInjectionGroup()) {
// Obtain rates for group.
std::vector<Scalar> resv_coeff_inj(phase_usage_.num_phases, 0.0);
calcInjResvCoeff(fipnum, pvtreg, resv_coeff_inj);
// checkGroupConstraintsInj considers 'available' rates (e.g., group rates minus reduction rates).
// So when checking constraints, current groups rate must also be subtracted it's reduction rate
const std::vector<Scalar> reduction_rates = this->groupState().injection_reduction_rates(group.name());
for (int phasePos = 0; phasePos < phase_usage_.num_phases; ++phasePos) {
const Scalar local_current_rate = WellGroupHelpers<Scalar>::sumWellSurfaceRates(group,
schedule(),
this->wellState(),
reportStepIdx,
phasePos,
/* isInjector */ true);
// Sum over all processes
rates[phasePos] = comm_.sum(local_current_rate) - reduction_rates[phasePos];
}
const Phase all[] = { Phase::WATER, Phase::OIL, Phase::GAS };
for (Phase phase : all) {
bool group_is_oscillating = false;
if (auto groupPos = switched_inj_groups_.find(group.name()); groupPos != switched_inj_groups_.end()) {
auto& ctrls = groupPos->second[static_cast<std::underlying_type_t<Phase>>(phase)];
for (const auto& ctrl : ctrls) {
if (std::count(ctrls.begin(), ctrls.end(), ctrl) <= max_number_of_group_switch) {
continue;
}
if (ctrls.back() != *(ctrls.end() - 2)) {
if (comm_.rank() == 0 ) {
std::ostringstream os;
os << phase;
const std::string msg =
fmt::format("Group control for {} injector group {} is oscillating. Group control kept at {}.",
std::move(os).str(),
group.name(),
Group::InjectionCMode2String(ctrl));
deferred_logger.info(msg);
}
ctrls.push_back(ctrl);
}
group_is_oscillating = true;
break;
}
}
if (group_is_oscillating) {
continue;
}
// Check higher up only if under individual (not FLD) control.
auto currentControl = this->groupState().injection_control(group.name(), phase);
if (currentControl != Group::InjectionCMode::FLD && group.injectionGroupControlAvailable(phase)) {
const Group& parentGroup = schedule().getGroup(group.parent(), reportStepIdx);
const auto [is_changed, scaling_factor] =
WellGroupHelpers<Scalar>::checkGroupConstraintsInj(group.name(),
group.parent(),
parentGroup,
this->wellState(),
this->groupState(),
reportStepIdx,
&guideRate_,
rates.data(),
phase,
phase_usage_,
group.getGroupEfficiencyFactor(),
schedule(),
summaryState_,
resv_coeff_inj,
deferred_logger);
if (is_changed) {
switched_inj_groups_[group.name()][static_cast<std::underlying_type_t<Phase>>(phase)].push_back(Group::InjectionCMode::FLD);
BlackoilWellModelConstraints(*this).
actionOnBrokenConstraints(group, Group::InjectionCMode::FLD,
phase, this->groupState(),
deferred_logger);
WellGroupHelpers<Scalar>::updateWellRatesFromGroupTargetScale(scaling_factor,
group,
schedule(),
reportStepIdx,
/* isInjector */ true,
this->groupState(),
this->wellState());
changed = true;
}
}
}
}
if (!isField && group.isProductionGroup()) {
// Obtain rates for group.
// checkGroupConstraintsProd considers 'available' rates (e.g., group rates minus reduction rates).
// So when checking constraints, current groups rate must also be subtracted it's reduction rate
const std::vector<Scalar> reduction_rates = this->groupState().production_reduction_rates(group.name());
if (auto groupPos = switched_prod_groups_.find(group.name()); groupPos != switched_prod_groups_.end()) {
auto& ctrls = groupPos->second;
for (const auto& ctrl : ctrls) {
if (std::count(ctrls.begin(), ctrls.end(), ctrl) <= max_number_of_group_switch) {
continue;
}
if (ctrls.back() != *(ctrls.end() - 2)) {
if (comm_.rank() == 0) {
const std::string msg =
fmt::format("Group control for production group {} is oscillating. Group control kept at {}.",
group.name(),
Group::ProductionCMode2String(ctrl));
deferred_logger.info(msg);
}
ctrls.push_back(ctrl);
}
return false;
}
}
for (int phasePos = 0; phasePos < phase_usage_.num_phases; ++phasePos) {
const Scalar local_current_rate = WellGroupHelpers<Scalar>::sumWellSurfaceRates(group,
schedule(),
this->wellState(),
reportStepIdx,
phasePos,
/* isInjector */ false);
// Sum over all processes
rates[phasePos] = -comm_.sum(local_current_rate) - reduction_rates[phasePos];
}
std::vector<Scalar> resv_coeff(phase_usage_.num_phases, 0.0);
calcResvCoeff(fipnum, pvtreg, this->groupState().production_rates(group.name()), resv_coeff);
// Check higher up only if under individual (not FLD) control.
const Group::ProductionCMode& currentControl = this->groupState().production_control(group.name());
if (currentControl != Group::ProductionCMode::FLD && group.productionGroupControlAvailable()) {
const Group& parentGroup = schedule().getGroup(group.parent(), reportStepIdx);
const auto [is_changed, scaling_factor] =
WellGroupHelpers<Scalar>::checkGroupConstraintsProd(group.name(),
group.parent(),
parentGroup,
this->wellState(),
this->groupState(),
reportStepIdx,
&guideRate_,
rates.data(),
phase_usage_,
group.getGroupEfficiencyFactor(),
schedule(),
summaryState_,
resv_coeff,
deferred_logger);
if (is_changed) {
const auto group_limit_action = group.productionControls(summaryState_).group_limit_action;
std::optional<std::string> worst_offending_well = std::nullopt;
changed = BlackoilWellModelConstraints(*this).
actionOnBrokenConstraints(group, reportStepIdx, group_limit_action,
Group::ProductionCMode::FLD,
this->wellState(),
worst_offending_well,
this->groupState(),
deferred_logger);
if (changed) {
switched_prod_groups_[group.name()].push_back(Group::ProductionCMode::FLD);
WellGroupHelpers<Scalar>::updateWellRatesFromGroupTargetScale(scaling_factor,
group,
schedule(),
reportStepIdx,
/* isInjector */ false,
this->groupState(),
this->wellState());
}
}
}
}
return changed;
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
updateEclWells(const int timeStepIdx,
const SimulatorUpdate& sim_update,
const SummaryState& st)
{
this->updateEclWellsConstraints(timeStepIdx, sim_update, st);
if (! sim_update.well_structure_changed &&
! this->wellStructureChangedDynamically_)
{
this->updateEclWellsCTFFromAction(timeStepIdx, sim_update);
}
if (sim_update.well_structure_changed) {
// Note: Record change if this update triggered a well structure
// change. Otherwise, we risk setting ChangedDynamically_ to false
// if a subsequent action at the same time step does *not* change
// the well topology.
this->wellStructureChangedDynamically_ = true;
}
}
template<class Scalar>
template<typename Iter, typename Body>
void BlackoilWellModelGeneric<Scalar>::
wellUpdateLoop(Iter first, Iter last, const int timeStepIdx, Body&& body)
{
std::for_each(first, last,
[this, timeStepIdx,
loopBody = std::forward<Body>(body)]
(const auto& wname)
{
auto well_iter = std::find_if(this->wells_ecl_.begin(),
this->wells_ecl_.end(),
[&wname](const auto& well)
{ return well.name() == wname; });
if (well_iter == this->wells_ecl_.end()) {
return;
}
const auto wellIdx =
std::distance(this->wells_ecl_.begin(), well_iter);
const auto& well = this->wells_ecl_[wellIdx] =
this->schedule_.getWell(wname, timeStepIdx);
loopBody(wellIdx, well);
});
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
updateEclWellsConstraints(const int timeStepIdx,
const SimulatorUpdate& sim_update,
const SummaryState& st)
{
this->wellUpdateLoop(sim_update.affected_wells.begin(),
sim_update.affected_wells.end(),
timeStepIdx,
[this, &st]
(const auto wellIdx, const auto& well)
{
auto& ws = this->wellState().well(wellIdx);
ws.updateStatus(well.getStatus());
ws.update_targets(well, st);
});
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
updateEclWellsCTFFromAction(const int timeStepIdx,
const SimulatorUpdate& sim_update)
{
this->wellUpdateLoop(sim_update.welpi_wells.begin(),
sim_update.welpi_wells.end(),
timeStepIdx,
[this](const auto wellIdx, const auto& well)
{
auto& pd = this->well_perf_data_[wellIdx];
{
auto pdIter = pd.begin();
for (const auto& conn : well.getConnections()) {
if (conn.state() != Connection::State::SHUT) {
pdIter->connection_transmissibility_factor = conn.CF();
++pdIter;
}
}
}
this->wellState().well(wellIdx).reset_connection_factors(pd);
this->prod_index_calc_[wellIdx].reInit(well);
});
}
template<class Scalar>
Scalar BlackoilWellModelGeneric<Scalar>::
wellPI(const int well_index) const
{
const auto& pu = this->phase_usage_;
const auto& pi = this->wellState().well(well_index).productivity_index;
const auto preferred = this->wells_ecl_[well_index].getPreferredPhase();
switch (preferred) { // Should really have LIQUID = OIL + WATER here too...
case Phase::WATER:
return pu.phase_used[BlackoilPhases::PhaseIndex::Aqua]
? pi[pu.phase_pos[BlackoilPhases::PhaseIndex::Aqua]]
: 0.0;
case Phase::OIL:
return pu.phase_used[BlackoilPhases::PhaseIndex::Liquid]
? pi[pu.phase_pos[BlackoilPhases::PhaseIndex::Liquid]]
: 0.0;
case Phase::GAS:
return pu.phase_used[BlackoilPhases::PhaseIndex::Vapour]
? pi[pu.phase_pos[BlackoilPhases::PhaseIndex::Vapour]]
: 0.0;
default:
throw std::invalid_argument {
"Unsupported preferred phase " +
std::to_string(static_cast<int>(preferred))
};
}
}
template<class Scalar>
Scalar BlackoilWellModelGeneric<Scalar>::
wellPI(const std::string& well_name) const
{
auto well_iter = std::find_if(this->wells_ecl_.begin(), this->wells_ecl_.end(),
[&well_name](const Well& well)
{
return well.name() == well_name;
});
if (well_iter == this->wells_ecl_.end()) {
throw std::logic_error { "Could not find well: " + well_name };
}
auto well_index = std::distance(this->wells_ecl_.begin(), well_iter);
return this->wellPI(well_index);
}
template<class Scalar>
bool BlackoilWellModelGeneric<Scalar>::
wasDynamicallyShutThisTimeStep(const int well_index) const
{
return wasDynamicallyShutThisTimeStep(this->wells_ecl_[well_index].name());
}
template<class Scalar>
bool
BlackoilWellModelGeneric<Scalar>::
wasDynamicallyShutThisTimeStep(const std::string& well_name) const
{
return this->closed_this_step_.find(well_name) !=
this->closed_this_step_.end();
}
template<class Scalar>
void BlackoilWellModelGeneric<Scalar>::
updateWsolvent(const Group& group,
const int reportStepIdx,
const WellState<Scalar>& wellState)
{