-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathCpGrid.cpp
More file actions
2858 lines (2546 loc) · 142 KB
/
Copy pathCpGrid.cpp
File metadata and controls
2858 lines (2546 loc) · 142 KB
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
//===========================================================================
//
// File: CpGrid.cpp
//
// Created: Thu Jun 4 12:55:28 2009
//
// Author(s): Atgeirr F Rasmussen <atgeirr@sintef.no>
// B�rd Skaflestad <bard.skaflestad@sintef.no>
// Antonella Ritorto <antonella.ritorto@opm-op.com>
//
// $Date$
//
// $Revision$
//
//===========================================================================
/*
Copyright 2023 Equinor ASA.
Copyright 2009, 2010 SINTEF ICT, Applied Mathematics.
Copyright 2009, 2010 Statoil ASA.
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/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if HAVE_MPI
#include <opm/grid/utility/platform_dependent/disable_warnings.h>
#include <opm/grid/utility/platform_dependent/reenable_warnings.h>
#endif
#if HAVE_OPM_COMMON
#include <opm/input/eclipse/EclipseState/Grid/EclipseGrid.hpp>
#endif
#include <opm/grid/UnstructuredGrid.h>
#include "../CpGrid.hpp"
#include "LgrHelpers.hpp"
#include "ParentToChildrenCellGlobalIdHandle.hpp"
#include "NestedRefinementUtilities.hpp"
#include <opm/grid/common/MetisPartition.hpp>
#include <opm/grid/common/ZoltanPartition.hpp>
#include <opm/grid/GraphOfGridWrappers.hpp>
//#include <opm/grid/common/ZoltanGraphFunctions.hpp>
#include <opm/grid/common/GridPartitioning.hpp>
//#include <opm/grid/common/WellConnections.hpp>
#include <opm/grid/common/CommunicationUtils.hpp>
//#include <fstream>
//#include <iostream>
#include <algorithm>
#include <iomanip>
#include <numeric>
#include <tuple>
namespace
{
#if HAVE_MPI
using AttributeSet = Dune::cpgrid::CpGridData::AttributeSet;
template<typename Tuple, bool first>
void reserveInterface(const std::vector<Tuple>& list, Dune::CpGrid::InterfaceMap& interface,
const std::integral_constant<bool, first>&)
{
std::map<int, std::size_t> proc_to_no_cells;
for(const auto& entry: list)
{
++proc_to_no_cells[std::get<1>(entry)];
}
for(const auto& proc: proc_to_no_cells)
{
auto& entry = interface[proc.first];
if ( first )
entry.first.reserve(proc.second);
else
entry.second.reserve(proc.second);
}
}
void setupSendInterface(const std::vector<std::tuple<int, int, char> >& list, Dune::CpGrid::InterfaceMap& interface)
{
reserveInterface(list, interface, std::integral_constant<bool, true>());
int cellIndex=-1;
int oldIndex = std::numeric_limits<int>::max();
for(const auto& entry: list)
{
auto index = std::get<0>(entry);
assert(oldIndex == std::numeric_limits<int>::max() || index >= oldIndex);
if (index != oldIndex )
{
oldIndex = index;
++cellIndex;
}
interface[std::get<1>(entry)].first.add(cellIndex);
}
}
void setupRecvInterface(const std::vector<std::tuple<int, int, char, int> >& list, Dune::CpGrid::InterfaceMap& interface)
{
reserveInterface(list, interface, std::integral_constant<bool, false>());
for(const auto& entry: list)
{
auto index = std::get<3>(entry);
interface[std::get<1>(entry)].second.add(index);
}
}
#endif // HAVE_MPI
/// Release memory resources from CpGrid::InterfaceMap. Used as custom
/// deleter for std::shared_ptr<InterfaceMap>.
struct FreeInterfaces
{
#if !HAVE_MPI
/// Release memory resources for InterfaceMap object
///
/// \param[in] interfaces Object for which to release memory resources.
void operator()([[maybe_unused]] Dune::CpGrid::InterfaceMap* interfaces) const
{
// Nothing to do in the sequential case as the CpGrid::InterfaceMap
// handles interface deletion in its destructor in this case.
}
#else // HAVE_MPI
/// Release memory resources for InterfaceMap object
///
/// \param[in] interfaces Object for which to release memory resources.
void operator()(Dune::CpGrid::InterfaceMap* interfaces) const
{
if (interfaces == nullptr) {
return;
}
for (auto& interface : *interfaces) {
auto& [scatter, gather] = interface.second;
scatter.free();
gather.free();
}
}
#endif // HAVE_MPI
};
}
namespace Dune
{
CpGrid::CpGrid()
: distributed_data_(),
cell_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
point_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
global_id_set_ptr_()
{
data_.push_back(std::make_shared<cpgrid::CpGridData>(data_));
current_data_ = &data_;
global_id_set_ptr_ = std::make_shared<cpgrid::GlobalIdSet>(*(current_data_->back()));
}
CpGrid::CpGrid(MPIHelper::MPICommunicator comm)
: distributed_data_(),
cell_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
point_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
global_id_set_ptr_()
{
data_.push_back(std::make_shared<cpgrid::CpGridData>(comm, data_));
current_data_ = &data_;
global_id_set_ptr_ = std::make_shared<cpgrid::GlobalIdSet>(*(current_data_->back()));
}
CpGrid::CpGrid(const std::string& filename)
: distributed_data_(),
cell_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
point_scatter_gather_interfaces_(new InterfaceMap, FreeInterfaces{}),
global_id_set_ptr_()
{
data_.push_back(std::make_shared<cpgrid::CpGridData>(data_));
current_data_ = &data_;
global_id_set_ptr_ = std::make_shared<cpgrid::GlobalIdSet>(*(current_data_->back()));
using GridPtr = std::unique_ptr<UnstructuredGrid, decltype(&destroy_grid)>;
GridPtr input_grid(read_grid(filename.c_str()), &destroy_grid);
if (!input_grid) {
OPM_THROW(std::runtime_error,
"Failed to read UnstructuredGrid from file: " + filename);
}
current_data_->back()->processUnstructuredGrid(*input_grid);
}
void CpGrid::readUnstructuredGridFile(const std::string& filename)
{
// Only the root rank reads and processes the file; all other ranks keep
// an empty global-view grid, which is correct for a subsequent
// scatterGrid / loadBalance call.
if (current_data_->back()->ccobj_.rank() == 0) {
using GridPtr = std::unique_ptr<UnstructuredGrid, decltype(&destroy_grid)>;
GridPtr input_grid(read_grid(filename.c_str()), &destroy_grid);
if (!input_grid) {
OPM_THROW(std::runtime_error,
"Failed to read UnstructuredGrid from file: " + filename);
}
current_data_->back()->processUnstructuredGrid(*input_grid);
}
// Broadcast the logical Cartesian size so every rank knows the total
// cell count (mirrors what processEclipseFormat does).
current_data_->back()->ccobj_.broadcast(
current_data_->back()->logical_cartesian_size_.data(),
current_data_->back()->logical_cartesian_size_.size(), 0);
}
std::vector<int>
CpGrid::zoltanPartitionWithoutScatter([[maybe_unused]] const std::vector<cpgrid::OpmWellType>* wells,
[[maybe_unused]] const std::unordered_map<std::string, std::set<int>>& possibleFutureConnections,
[[maybe_unused]] const double* transmissibilities,
[[maybe_unused]] const int numParts,
[[maybe_unused]] const double zoltanImbalanceTol) const
{
#if HAVE_MPI && HAVE_ZOLTAN
const auto met = EdgeWeightMethod(1);
return cpgrid::zoltanGraphPartitionGridForJac(*this, wells, possibleFutureConnections, transmissibilities,
this->data_[0]->ccobj_, met,
0, numParts, zoltanImbalanceTol);
#else
return std::vector<int>(this->numCells(), 0);
#endif
}
std::pair<bool, std::vector<std::pair<std::string,bool> > >
CpGrid::scatterGrid(EdgeWeightMethod method,
[[maybe_unused]] bool ownersFirst,
const std::vector<cpgrid::OpmWellType> * wells,
[[maybe_unused]] const std::unordered_map<std::string, std::set<int>>& possibleFutureConnections,
[[maybe_unused]] bool serialPartitioning,
const double* transmissibilities,
[[maybe_unused]] bool addCornerCells,
int overlapLayers,
[[maybe_unused]] int partitionMethod,
double imbalanceTol,
[[maybe_unused]] bool allowDistributedWells,
[[maybe_unused]] const std::vector<int>& input_cell_part,
int level,
[[maybe_unused]] bool useTransToFilterOverlap)
{
// Silence any unused argument warnings that could occur with various configurations.
static_cast<void>(wells);
static_cast<void>(transmissibilities);
static_cast<void>(overlapLayers);
static_cast<void>(method);
static_cast<void>(imbalanceTol);
static_cast<void>(level);
if(!distributed_data_.empty())
{
std::cerr<<"There is already a distributed version of the grid."
<< " Maybe scatterGrid was called before?"<<std::endl;
return std::make_pair(false, std::vector<std::pair<std::string,bool> >());
}
#if HAVE_MPI
bool validLevel = (level>-1) && (level <= maxLevel());
// If level == -1, leaf grid view should be distributed (with/without LGRs).
// - without LGRs: leaf grid view coincides with level zero grid. Supported.
// - with LGRs: not supported yet. Throw in that case.
int selectedLevel = validLevel? level : 0;
if (validLevel && (level>0)) {
if (comm().rank() == 0) {
OPM_THROW(std::logic_error, "Loadbalancing a refined level grid is not supported, yet.");
}
else {
OPM_THROW_NOLOG(std::logic_error, "Loadbalancing a refined level grid is not supported, yet.");
}
}
if ( (maxLevel()>0) && (level==-1) ) {
if (comm().rank() == 0) {
OPM_THROW(std::logic_error, "Loadbalancing a leaf grid view with local refinement is not supported, yet.");
}
else {
OPM_THROW_NOLOG(std::logic_error, "Loadbalancing a leaf grid view with local refinement is not supported, yet.");
}
}
if ((maxLevel()>0) && (partitionMethod!= Dune::PartitionMethod::zoltanGoG)) {
if (comm().rank() == 0) {
OPM_THROW(std::logic_error, "Loadbalancing level zero grid of a grid with local refinement is supported for ZOLTANGOG.");
}
else {
OPM_THROW_NOLOG(std::logic_error, "Loadbalancing level zero grid of a grid with local refinement is supported for ZOLTANGOG.");
}
}
auto& cc = data_[selectedLevel]->ccobj_;
if (cc.size() > 1)
{
std::vector<int> computedCellPart;
std::vector<std::pair<std::string,bool>> wells_on_proc;
std::vector<std::tuple<int,int,char>> exportList;
std::vector<std::tuple<int,int,char,int>> importList;
cpgrid::WellConnections wellConnections;
auto inputNumParts = input_cell_part.size();
inputNumParts = this->comm().max(inputNumParts);
if ( inputNumParts > 0 )
{
std::vector<int> errors;
std::vector<std::string> errorMessages =
{ "More parts than MPI Communicator can handle",
"Indices of parts need to zero starting",
"Indices of parts need to be consecutive",
"Only rank 0 should provide partitioning information for each cell"};
std::set<int> existingParts;
if (comm().rank() == 0)
{
for(const auto& part: input_cell_part)
{
existingParts.insert(part);
}
if (*input_cell_part.rbegin() >= comm().size())
{
errors.push_back(0);
}
int i = 0;
if (*existingParts.begin() != i)
{
errors.push_back(1);
}
if (std::ranges::any_of(existingParts,
[&i](const auto& part)
{ return part != i++; }))
{
errors.push_back(2);
}
if (std::size_t(size(0)) != input_cell_part.size())
{
errors.push_back(3);
}
}
auto size = errors.size();
comm().broadcast(&size, 1, 0);
errors.resize(size);
if (!errors.empty())
{
comm().broadcast(errors.data(), size, 0);
std::string message("Loadbalance: ");
for ( const auto& e: errors)
{
message.append(errorMessages[e]).append(". ");
}
if (comm().rank() == 0)
{
OPM_THROW(std::logic_error, message);
}
else
{
OPM_THROW_NOLOG(std::logic_error, message);
}
}
// Partitioning given externally
std::tie(computedCellPart, wells_on_proc, exportList, importList, wellConnections) =
cpgrid::createListsFromParts(*this, wells, possibleFutureConnections, /* transmissibilities = */ nullptr, input_cell_part,
/* allowDistributedWells = */ true, /* gridAndWells = */ nullptr, level);
}
else
{
if (partitionMethod == Dune::PartitionMethod::zoltan)
{
#ifdef HAVE_ZOLTAN
std::tie(computedCellPart, wells_on_proc, exportList, importList, wellConnections)
= serialPartitioning
? cpgrid::zoltanSerialGraphPartitionGridOnRoot(*this, wells, possibleFutureConnections, transmissibilities, cc, method, 0, imbalanceTol, allowDistributedWells, partitioningParams)
: cpgrid::zoltanGraphPartitionGridOnRoot(*this, wells, possibleFutureConnections, transmissibilities, cc, method, 0, imbalanceTol, allowDistributedWells, partitioningParams);
#else
OPM_THROW(std::runtime_error, "Parallel runs depend on ZOLTAN if useZoltan is true. Please install!");
#endif // HAVE_ZOLTAN
}
else if (partitionMethod == Dune::PartitionMethod::metis)
{
#ifdef HAVE_METIS
if (!serialPartitioning)
OPM_MESSAGE("Warning: Serial partitioning is set to false and METIS was selected to partition the grid, but METIS is a serial partitioner. Continuing with serial partitioning...");
std::tie(computedCellPart, wells_on_proc, exportList, importList, wellConnections) = cpgrid::metisSerialGraphPartitionGridOnRoot(*this, wells, possibleFutureConnections, transmissibilities, cc, method, 0, imbalanceTol, allowDistributedWells, partitioningParams);
#else
OPM_THROW(std::runtime_error, "Parallel runs depend on METIS if useMetis is true. Please install!");
#endif // HAVE_METIS
}
else if (partitionMethod == Dune::PartitionMethod::zoltanGoG)
{
#ifdef HAVE_ZOLTAN
std::tie(computedCellPart, wells_on_proc, exportList, importList, wellConnections)
= serialPartitioning
? Opm::zoltanSerialPartitioningWithGraphOfGrid(*this, wells, possibleFutureConnections, transmissibilities, cc, method, 0, imbalanceTol, allowDistributedWells, partitioningParams)
: Opm::zoltanPartitioningWithGraphOfGrid(*this, wells, possibleFutureConnections, transmissibilities, cc, method, 0, imbalanceTol, allowDistributedWells, partitioningParams, level);
#else
OPM_THROW(std::runtime_error, "Parallel runs depend on ZOLTAN if useZoltan is true. Please install!");
#endif // HAVE_ZOLTAN
}
else
{
std::tie(computedCellPart, wells_on_proc, exportList, importList, wellConnections) =
cpgrid::vanillaPartitionGridOnRoot(*this, wells, possibleFutureConnections, transmissibilities, allowDistributedWells);
}
}
comm().barrier();
// first create the overlap
auto noImportedOwner = addOverlapLayer(*this,
computedCellPart,
exportList,
importList,
cc,
addCornerCells,
transmissibilities,
useTransToFilterOverlap,
1 /*layers*/,
level);
// importList contains all the indices that will be here.
auto compareImport = [](const std::tuple<int,int,char,int>& t1,
const std::tuple<int,int,char,int>&t2)
{
return std::get<0>(t1) < std::get<0>(t2);
};
if ( ! ownersFirst )
{
// merge owner and overlap sorted by global index
std::inplace_merge(importList.begin(), importList.begin()+noImportedOwner,
importList.end(), compareImport);
}
// assign local indices
int localIndex = 0;
for(auto&& entry: importList)
std::get<3>(entry) = localIndex++;
if ( ownersFirst )
{
// merge owner and overlap sorted by global index
std::inplace_merge(importList.begin(), importList.begin()+noImportedOwner,
importList.end(), compareImport);
}
int procsWithZeroCells{};
if (cc.rank()==0)
{
// Print some statistics without communication
std::vector<int> ownedCells(cc.size(), 0);
std::vector<int> overlapCells(cc.size(), 0);
for (const auto& entry: exportList)
{
if(std::get<2>(entry) == AttributeSet::owner)
{
++ownedCells[std::get<1>(entry)];
}
else
{
++overlapCells[std::get<1>(entry)];
}
}
procsWithZeroCells =
std::accumulate(ownedCells.begin(), ownedCells.end(), 0,
[](const auto acc, const auto cellsOnProc)
{ return acc + (cellsOnProc == 0); });
std::ostringstream ostr;
ostr << "\nLoad balancing distributes level " << selectedLevel << " with " << data_[selectedLevel]->size(0)
<< " active cells on " << cc.size() << " processes as follows:\n";
ostr << " rank owned cells overlap cells total cells\n";
ostr << "--------------------------------------------------\n";
for (int i = 0; i < cc.size(); ++i) {
ostr << std::setw(6) << i
<< std::setw(14) << ownedCells[i]
<< std::setw(16) << overlapCells[i]
<< std::setw(14) << ownedCells[i] + overlapCells[i] << "\n";
}
ostr << "--------------------------------------------------\n";
ostr << " sum";
auto sumOwned = std::accumulate(ownedCells.begin(), ownedCells.end(), 0);
ostr << std::setw(14) << sumOwned;
auto sumOverlap = std::accumulate(overlapCells.begin(), overlapCells.end(), 0);
ostr << std::setw(16) << sumOverlap;
ostr << std::setw(14) << (sumOwned + sumOverlap) << "\n";
Opm::OpmLog::info(ostr.str());
}
// Print well distribution
std::vector<std::pair<int,int> > procWellPairs;
// range filters would be nice here. so C++20.
procWellPairs.reserve(std::ranges::count_if(wells_on_proc,
[](const auto& p)
{ return p.second; }));
int wellIndex = 0;
for ( const auto& well: wells_on_proc)
{
if ( well.second )
{
procWellPairs.emplace_back(cc.rank(), wellIndex);
}
++wellIndex;
}
std::tie(procWellPairs, std::ignore) = Opm::gatherv(procWellPairs, cc, 0);
if (cc.rank() == 0)
{
std::ranges::sort(procWellPairs,
[](const std::pair<int,int>& p1, const std::pair<int,int>& p2)
{ return p1.second < p2.second;});
std::ostringstream ostr;
ostr << "\nLoad balancing distributed the wells as follows:\n"
<< " well name ranks with perforated cells\n"
<< "---------------------------------------------------\n";
auto procWellPair = std::begin(procWellPairs);
auto endProcWellPair = std::end(procWellPairs);
int wellIdx = 0;
for ( const auto& well: wells_on_proc)
{
ostr << std::setw(16) << well.first;
while (procWellPair != endProcWellPair && procWellPair->second < wellIdx)
{
++procWellPair;
}
for ( ; procWellPair != endProcWellPair && procWellPair->second == wellIdx;
++procWellPair)
{
ostr << " "<< std::setw(7) << procWellPair->first;
}
ostr << "\n";
++wellIdx;
}
Opm::OpmLog::info(ostr.str());
}
procsWithZeroCells = cc.sum(procsWithZeroCells);
if (procsWithZeroCells) {
std::string msg = "At least one process has zero cells. Aborting. \n"
" Try decreasing the imbalance tolerance with the argument \n"
" --imbalance-tol. The current value is "
+ std::to_string(imbalanceTol);
if (cc.rank()==0)
{
OPM_THROW(std::runtime_error, msg );
}
else
{
OPM_THROW_NOLOG(std::runtime_error, msg);
}
}
// distributed_data should be empty at this point.
distributed_data_.push_back(std::make_shared<cpgrid::CpGridData>(cc, distributed_data_));
distributed_data_[0]->setUniqueBoundaryIds(data_[selectedLevel]->uniqueBoundaryIds());
// Just to be sure we assume that only master knows
cc.broadcast(&distributed_data_[0]->use_unique_boundary_ids_, 1, 0);
// Create indexset
distributed_data_[0]->cellIndexSet().beginResize();
for(const auto& entry: importList)
{
distributed_data_[0]->cellIndexSet()
.add(std::get<0>(entry),ParallelIndexSet::LocalIndex(std::get<3>(entry),AttributeSet(std::get<2>(entry)), true));
}
distributed_data_[0]->cellIndexSet().endResize();
// add an interface for gathering/scattering data with communication
// forward direction will be scatter and backward gather
// Interface will communicate from owner to all
setupSendInterface(exportList, *cell_scatter_gather_interfaces_);
setupRecvInterface(importList, *cell_scatter_gather_interfaces_);
distributed_data_[0]->distributeGlobalGrid(*this,*this->data_[selectedLevel], computedCellPart);
(*global_id_set_ptr_).insertIdSet(*distributed_data_[0]);
distributed_data_[0]-> index_set_.reset(new cpgrid::IndexSet(distributed_data_[0]->cell_to_face_.size(),
distributed_data_[0]-> geomVector<3>().size()));
current_data_ = &distributed_data_;
return std::make_pair(true, wells_on_proc);
}
else
{
std::cerr << "CpGrid::scatterGrid() only makes sense in a parallel run. "
<< "This run only uses one process.\n";
return std::make_pair(false, std::vector<std::pair<std::string,bool>>());
}
#else // #if HAVE_MPI
std::cerr << "CpGrid::scatterGrid() is non-trivial only with "
<< "MPI support and if the target Dune platform is "
<< "sufficiently recent.\n";
return std::make_pair(false, std::vector<std::pair<std::string,bool>>());
#endif
}
void CpGrid::createCartesian(const std::array<int, 3>& dims,
const std::array<double, 3>& cellsize,
const std::array<int, 3>& shift)
{
if ( current_data_->back()->ccobj_.rank() != 0 )
{
// global grid only on rank 0
current_data_->back()->ccobj_.broadcast(current_data_->back()->logical_cartesian_size_.data(),
current_data_->back()->logical_cartesian_size_.size(),
0);
return;
}
// Make the grdecl format arrays.
// Pillar coords.
std::vector<double> coord;
coord.reserve(6*(dims[0] + 1)*(dims[1] + 1));
double bot = 0.0+shift[2]*cellsize[2];
double top = (dims[2]+shift[2])*cellsize[2];
// i runs fastest for the pillars.
for (int j = 0; j < dims[1] + 1; ++j) {
double y = (j+shift[1])*cellsize[1];
for (int i = 0; i < dims[0] + 1; ++i) {
double x = (i+shift[0])*cellsize[0];
double pillar[6] = { x, y, bot, x, y, top };
coord.insert(coord.end(), pillar, pillar + 6);
}
}
std::vector<double> zcorn(8*dims[0]*dims[1]*dims[2]);
const int num_per_layer = 4*dims[0]*dims[1];
double* offset = &zcorn[0];
for (int k = 0; k < dims[2]; ++k) {
double zlow = (k+shift[2])*cellsize[2];
std::fill_n(offset, num_per_layer, zlow);
offset += num_per_layer;
double zhigh = (k+1+shift[2])*cellsize[2];
std::fill_n(offset, num_per_layer, zhigh);
offset += num_per_layer;
}
std::vector<int> actnum(dims[0]*dims[1]*dims[2], 1);
// Process them.
grdecl g;
g.dims[0] = dims[0];
g.dims[1] = dims[1];
g.dims[2] = dims[2];
g.coord = &coord[0];
g.zcorn = &zcorn[0];
g.actnum = &actnum[0];
using NNCMap = std::set<std::pair<int, int>>;
using NNCMaps = std::array<NNCMap, 2>;
NNCMaps nnc;
// Note: This is a Cartesian, matching grid which is edge-conforming
// regardless of the edge_conformal flag.
current_data_->back()->processEclipseFormat(g,
#if HAVE_OPM_COMMON
/* ecl_state = */ nullptr,
#endif
nnc,
/* remove_ij_boundary = */ false,
/* turn_normals = */ false,
/* pinchActive = */ false,
/* tolerance_unique_ponts = */ 0.0,
/* edge_conformal = */ false);
// global grid only on rank 0
current_data_->back()->ccobj_.broadcast(current_data_->back()->logical_cartesian_size_.data(),
current_data_->back()->logical_cartesian_size_.size(),
0);
}
const std::array<int, 3>& CpGrid::logicalCartesianSize() const
{
// Temporary. For a grid with LGRs, we set the logical cartesian size of the LeafGridView as the one for level 0.
// Goal: CartesianIndexMapper well-defined for CpGrid LeafView with LGRs.
return current_data_->front() -> logical_cartesian_size_;
}
const std::vector<std::shared_ptr<Dune::cpgrid::CpGridData>>& CpGrid::currentData() const
{
return *current_data_;
}
std::vector<std::shared_ptr<Dune::cpgrid::CpGridData>>& CpGrid::currentData()
{
return *current_data_;
}
const Dune::cpgrid::CpGridData& CpGrid::currentLeafData() const
{
return *current_data_->back();
}
Dune::cpgrid::CpGridData& CpGrid::currentLeafData()
{
return *current_data_->back();
}
const std::vector<int>& CpGrid::globalCell() const
{
// Temporary. For a grid with LGRs, we set the globalCell() of the as the one for level 0.
// Goal: CartesianIndexMapper well-defined for CpGrid LeafView with LGRs.
return currentLeafData().global_cell_;
}
void CpGrid::computeGlobalCellLgr(const int& level, const std::array<int,3>& startIJK, std::vector<int>& global_cell_lgr)
{
assert(level);
for (const auto& element : elements(levelGridView(level))) {
// Element belogns to an LGR, therefore has a father. Get IJK of the father in the level grid the father was born.
// For CARFIN, parent cells belong to level 0.
std::array<int,3> parentIJK = {0,0,0};
currentData()[element.father().level()]->getIJK(element.father().index(), parentIJK);
// Each parent cell has been refined in cells_per_dim[0]*cells_per_dim[1]*cells_per_dim[2] child cells.
// element has certain 'position' inside its parent cell that can be described with 'IJK' indices, let's denote them by ijk,
// where 0<= i < cells_per_dim[0], 0<= j < cells_per_dim[1], 0<= k < cells_per_dim[2].
const auto& cells_per_dim = currentData()[level]->cells_per_dim_;
//
// Refined cell (here 'element') has "index in parent cell": k*cells_per_dim[0]*cells_per_dim[1] + j*cells_per_dim[0] + i
// and it's stored in cell_to_idxInParentCell_.
auto idx_in_parent_cell = currentData()[level]-> cell_to_idxInParentCell_[element.index()];
// Find ijk.
std::array<int,3> childIJK = Opm::Lgr::getIJK(idx_in_parent_cell, cells_per_dim);
// The corresponding lgrIJK can be computed as follows:
const std::array<int,3>& lgrIJK = { ( (parentIJK[0] - startIJK[0])*cells_per_dim[0] ) + childIJK[0], // Shift parent index according to the startIJK of the LGR.
( (parentIJK[1] - startIJK[1])*cells_per_dim[1] ) + childIJK[1],
( (parentIJK[2] - startIJK[2])*cells_per_dim[2] ) + childIJK[2] };
// Dimensions of the "patch of cells" formed when providing startIJK and endIJK for an LGR
const auto& lgr_logical_cartesian_size = currentData()[level]->logical_cartesian_size_;
global_cell_lgr[element.index()] = (lgrIJK[2]*lgr_logical_cartesian_size[0]*lgr_logical_cartesian_size[1]) + (lgrIJK[1]*lgr_logical_cartesian_size[0]) + lgrIJK[0];
}
}
void CpGrid::computeGlobalCellLeafGridViewWithLgrs(std::vector<int>& global_cell_leaf)
{
for (const auto& element: elements(leafGridView())) {
// In the context of allowed nested refinement, we lookup for the oldest ancestor, belonging to level-zero-grid.
auto ancestor = element.getOrigin();
int origin_in_level_zero = ancestor.index();
assert(origin_in_level_zero < currentData().front()->size(0));
global_cell_leaf[element.index()] = currentData().front()-> global_cell_[origin_in_level_zero];
}
}
std::vector<std::unordered_map<std::size_t, std::size_t>> CpGrid::mapLocalCartesianIndexSetsToLeafIndexSet() const
{
std::vector<std::unordered_map<std::size_t, std::size_t>> localCartesianIdxSets_to_leafIdx(maxLevel()+1); // Plus level 0
for (const auto& element : elements(leafGridView())) {
const auto& global_cell_level = currentData()[element.level()]->globalCell()[element.getLevelElem().index()];
localCartesianIdxSets_to_leafIdx[element.level()][global_cell_level] = element.index();
}
return localCartesianIdxSets_to_leafIdx;
}
std::vector<std::array<int,2>> CpGrid::mapLeafIndexSetToLocalCartesianIndexSets() const
{
std::vector<std::array<int,2>> leafIdx_to_localCartesianIdxSets(currentLeafData().size(0));
for (const auto& element : elements(leafGridView())) {
const auto& global_cell_level = currentData()[element.level()]->globalCell()[element.getLevelElem().index()];
leafIdx_to_localCartesianIdxSets[element.index()] = {element.level(), global_cell_level};
}
return leafIdx_to_localCartesianIdxSets;
}
void CpGrid::getIJK(const int c, std::array<int,3>& ijk) const
{
current_data_->back()->getIJK(c, ijk);
}
bool CpGrid::uniqueBoundaryIds() const
{
return current_data_->back()->uniqueBoundaryIds();
}
void CpGrid::setUniqueBoundaryIds(bool uids)
{
current_data_->back()->setUniqueBoundaryIds(uids);
}
std::string CpGrid::name() const
{
return "CpGrid";
}
int CpGrid::maxLevel() const
{
if (currentData().size() == 1){
return 0; // "GLOBAL" grid is the unique one
}
else { // There are multiple LGRs
return this -> currentData().size() - 2; // last entry is leafView, and it starts in level 0 = GLOBAL grid.
}
}
template<int codim>
typename CpGridTraits::template Codim<codim>::LevelIterator CpGrid::lbegin (int level) const
{
if (level<0 || level>maxLevel())
DUNE_THROW(GridError, "levelIndexSet of nonexisting level " << level << " requested!");
return cpgrid::Iterator<codim, All_Partition>( *(*current_data_)[level], 0, true);
}
template typename CpGridTraits::template Codim<0>::LevelIterator CpGrid::lbegin<0>(int) const;
template typename CpGridTraits::template Codim<1>::LevelIterator CpGrid::lbegin<1>(int) const;
template typename CpGridTraits::template Codim<3>::LevelIterator CpGrid::lbegin<3>(int) const;
template<int codim>
typename CpGridTraits::template Codim<codim>::LevelIterator CpGrid::lend (int level) const
{
if (level<0 || level>maxLevel())
DUNE_THROW(GridError, "levelIndexSet of nonexisting level " << level << " requested!");
return cpgrid::Iterator<codim, All_Partition>( *(*current_data_)[level], size(level, codim), true);
}
template typename CpGridTraits::template Codim<0>::LevelIterator CpGrid::lend<0>(int) const;
template typename CpGridTraits::template Codim<1>::LevelIterator CpGrid::lend<1>(int) const;
template typename CpGridTraits::template Codim<3>::LevelIterator CpGrid::lend<3>(int) const;
template<int codim>
typename CpGridTraits::template Codim<codim>::LeafIterator CpGrid::leafbegin() const
{
return cpgrid::Iterator<codim, All_Partition>(*(current_data_->back()), 0, true);
}
template typename CpGridTraits::template Codim<0>::LeafIterator CpGrid::leafbegin<0>() const;
template typename CpGridTraits::template Codim<1>::LeafIterator CpGrid::leafbegin<1>() const;
template typename CpGridTraits::template Codim<3>::LeafIterator CpGrid::leafbegin<3>() const;
template<int codim>
typename CpGridTraits::template Codim<codim>::LeafIterator CpGrid::leafend() const
{
return cpgrid::Iterator<codim, All_Partition>(*(current_data_->back()), size(codim), true);
}
template typename CpGridTraits::template Codim<0>::LeafIterator CpGrid::leafend<0>() const;
template typename CpGridTraits::template Codim<1>::LeafIterator CpGrid::leafend<1>() const;
template typename CpGridTraits::template Codim<3>::LeafIterator CpGrid::leafend<3>() const;
template<int codim, PartitionIteratorType PiType>
typename CpGridTraits::template Codim<codim>::template Partition<PiType>::LevelIterator CpGrid::lbegin (int level) const
{
if (level<0 || level>maxLevel())
DUNE_THROW(GridError, "levelIndexSet of nonexisting level " << level << " requested!");
return cpgrid::Iterator<codim, PiType>( *(*current_data_)[level], 0, true);
}
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lbegin<0,Dune::Ghost_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lbegin<1,Dune::Ghost_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lbegin<3,Dune::Ghost_Partition>(int) const;
template<int codim, PartitionIteratorType PiType>
typename CpGridTraits::template Codim<codim>::template Partition<PiType>::LevelIterator CpGrid::lend (int level) const
{
if (level<0 || level>maxLevel())
DUNE_THROW(GridError, "levelIndexSet of nonexisting level " << level << " requested!");
return cpgrid::Iterator<codim, PiType>( *(*current_data_)[level], size(level, codim), true);
}
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lend<0,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lend<0,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lend<0,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lend<0,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lend<0,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lend<0,Dune::Ghost_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lend<1,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lend<1,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lend<1,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lend<1,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lend<1,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lend<1,Dune::Ghost_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Interior_Partition>::LevelIterator
CpGrid::lend<3,Dune::Interior_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::InteriorBorder_Partition>::LevelIterator
CpGrid::lend<3,Dune::InteriorBorder_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Overlap_Partition>::LevelIterator
CpGrid::lend<3,Dune::Overlap_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::OverlapFront_Partition>::LevelIterator
CpGrid::lend<3,Dune::OverlapFront_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::All_Partition>::LevelIterator
CpGrid::lend<3,Dune::All_Partition>(int) const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Ghost_Partition>::LevelIterator
CpGrid::lend<3,Dune::Ghost_Partition>(int) const;
template<int codim, PartitionIteratorType PiType>
typename CpGridFamily::Traits::template Codim<codim>::template Partition<PiType>::LeafIterator CpGrid::leafbegin() const
{
return cpgrid::Iterator<codim, PiType>(*(current_data_->back()), 0, true);
}
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Interior_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::Interior_Partition>() const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::InteriorBorder_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::InteriorBorder_Partition>() const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Overlap_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::Overlap_Partition>() const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::OverlapFront_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::OverlapFront_Partition>() const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::All_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::All_Partition>() const;
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Ghost_Partition>::LeafIterator
CpGrid::leafbegin<0,Dune::Ghost_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Interior_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::Interior_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::InteriorBorder_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::InteriorBorder_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Overlap_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::Overlap_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::OverlapFront_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::OverlapFront_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::All_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::All_Partition>() const;
template typename CpGridTraits::template Codim<1>::template Partition<Dune::Ghost_Partition>::LeafIterator
CpGrid::leafbegin<1,Dune::Ghost_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Interior_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::Interior_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::InteriorBorder_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::InteriorBorder_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Overlap_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::Overlap_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::OverlapFront_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::OverlapFront_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::All_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::All_Partition>() const;
template typename CpGridTraits::template Codim<3>::template Partition<Dune::Ghost_Partition>::LeafIterator
CpGrid::leafbegin<3,Dune::Ghost_Partition>() const;
template<int codim, PartitionIteratorType PiType>
typename CpGridFamily::Traits::template Codim<codim>::template Partition<PiType>::LeafIterator CpGrid::leafend() const
{
return cpgrid::Iterator<codim, PiType>(*(current_data_->back()), size(codim), true);
}
template typename CpGridTraits::template Codim<0>::template Partition<Dune::Interior_Partition>::LeafIterator
CpGrid::leafend<0,Dune::Interior_Partition>() const;