-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathprocessEclipseFormat.cpp
More file actions
1502 lines (1311 loc) · 64.6 KB
/
Copy pathprocessEclipseFormat.cpp
File metadata and controls
1502 lines (1311 loc) · 64.6 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: readEclipseFormat.cpp
//
// Created: Fri Jun 12 09:16:59 2009
//
// Author(s): Atgeirr F Rasmussen <atgeirr@sintef.no>
// B�rd Skaflestad <bard.skaflestad@sintef.no>
//
// $Date$
//
// $Revision$
//
//===========================================================================
/*
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/>.
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <opm/grid/cpgrid/CpGridData.hpp>
#include <opm/grid/common/GeometryHelpers.hpp>
#include <opm/grid/cpgpreprocess/preprocess.h>
#include <opm/grid/MinpvProcessor.hpp>
#include <opm/grid/RepairZCORN.hpp>
#include <opm/grid/utility/OpmLog.hpp>
#include <opm/grid/utility/StopWatch.hpp>
#include <opm/grid/cpgrid/Entity.hpp>
#include <opm/grid/cpgrid/Geometry.hpp>
#include <opm/grid/cpgrid/Indexsets.hpp>
#if HAVE_OPM_COMMON
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/EclipseState/Grid/FaceDir.hpp>
#endif
#include <algorithm>
#include <array>
#include <cstddef>
#include <fstream>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <numeric>
#include <set>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
namespace Dune
{
using NNCMap = std::set<std::pair<int, int>>;
using NNCMaps = std::array<NNCMap, 2>;
enum NNCMapsIndex { PinchNNC = 0,
ExplicitNNC = 1 };
// Forward declarations.
namespace
{
#if HAVE_OPM_COMMON
std::vector<double>
getSanitizedZCORN(const ::Opm::EclipseGrid& ecl_grid,
const ::std::vector<int>& actnum);
typedef std::array<int, 3> coord_t;
typedef std::array<double, 8> cellz_t;
cellz_t getCellZvals(const coord_t& c, const coord_t& n, const double* z);
void addOuterCellLayer(const grdecl& original,
std::vector<double>& new_coord,
std::vector<double>& new_zcorn,
std::vector<int>& new_actnum,
grdecl& output);
#endif
void removeOuterCellLayer(processed_grid& grid);
// void removeUnusedNodes(processed_grid& grid); // NOTE: not deleted, see comment at definition.
void buildTopo(const processed_grid& output,
const NNCMaps& nnc,
std::vector<int>& global_cell,
cpgrid::OrientedEntityTable<0, 1>& c2f,
cpgrid::OrientedEntityTable<1, 0>& f2c,
Opm::SparseTable<int>& f2p,
std::vector<std::array<int,8> >& c2p,
std::vector<int>& face_to_output_face);
void buildGeom(const processed_grid& output,
const cpgrid::OrientedEntityTable<0, 1>& c2f,
const std::vector<std::array<int,8> >& c2p,
const std::vector<int>& face_to_output_face,
const std::unordered_map<std::size_t, double>& aquifer_cell_volumes,
cpgrid::EntityVariable<cpgrid::Geometry<3, 3>, 0>& cell_geom,
cpgrid::EntityVariable<cpgrid::Geometry<2, 3>, 1>& face_geom,
std::shared_ptr<cpgrid::EntityVariable<cpgrid::Geometry<0, 3>, 3>> point_geom,
cpgrid::SignedEntityVariable<FieldVector<double, 3> , 1>& normals,
bool turn_normals);
} // anon namespace
namespace cpgrid
{
#if HAVE_OPM_COMMON
std::vector<std::size_t>
CpGridData::processEclipseFormat(const Opm::EclipseGrid* ecl_grid_ptr,
Opm::EclipseState* ecl_state,
const bool periodic_extension,
const bool turn_normals,
const bool clip_z,
const bool pinchActive,
const bool edge_conformal)
{
if (ccobj_.rank() != 0) {
if (ecl_state != nullptr) {
// Handle potential exception during MINPV processing
//
// Needed because later there is collective communication
// that will otherwise deadlock
int success = 1;
ccobj_.broadcast(&success, 1, 0);
if (success == 0) {
throw std::runtime_error("Error during MINPV processing");
}
}
// Store global grid only on rank 0
return {};
}
const Opm::EclipseGrid& ecl_grid = *ecl_grid_ptr;
std::vector<double> coordData = ecl_grid.getCOORD();
std::vector<int> actnumData = ecl_grid.getACTNUM();
// Mutable because grdecl::zcorn is non-const.
auto zcornData = getSanitizedZCORN(ecl_grid, actnumData);
// Make input struct for processing code.
grdecl g;
g.dims[0] = ecl_grid.getNX();
g.dims[1] = ecl_grid.getNY();
g.dims[2] = ecl_grid.getNZ();
g.coord = &coordData[0];
g.zcorn = &zcornData[0];
g.actnum = actnumData.empty() ? nullptr : &actnumData[0];
Opm::MinpvProcessor::Result minpv_result;
double tolerance_unique_points = 0;
NNCMaps nnc_cells;
// Possibly process MINPV and PINCH
// This even needs to be done if neither of them is specified.
if (ecl_state ) {
bool pinchOptionALL = false;
const size_t cartGridSize = g.dims[0] * g.dims[1] * g.dims[2];
const auto& fp = ecl_state->fieldProps();
const auto& permZ = [&fp, cartGridSize](){
if(fp.has_double("PERMZ")) return fp.get_global_double("PERMZ");
if(fp.has_double("PERMY")) return fp.get_global_double("PERMY");
if(fp.has_double("PERMX")) return fp.get_global_double("PERMX");
// Make this part run without PERM* for some tests
return std::vector<double>(cartGridSize, 1);
}();
try {
Opm::MinpvProcessor mp(g.dims[0], g.dims[1], g.dims[2]);
std::vector<double> thickness(cartGridSize);
for (size_t i = 0; i < cartGridSize; ++i) {
thickness[i] = ecl_grid.getCellThickness(i);
}
const double z_tolerance = ecl_grid.isPinchActive() ? ecl_grid.getPinchThresholdThickness() : 0.0;
const bool nogap = !pinchActive || ecl_grid.getPinchGapMode() == Opm::PinchMode::NOGAP;
const auto& poreVolume = ecl_state->fieldProps().porv(true);
pinchOptionALL = ecl_grid.getPinchOption() == Opm::PinchMode::ALL;
const auto& transMult = ecl_state->getTransMult();
auto multZ =[ &transMult] (int cartindex) {
return transMult.getMultiplier(cartindex, ::Opm::FaceDir::ZPlus) *
transMult.getMultiplier(cartindex, ::Opm::FaceDir::ZMinus);
};
minpv_result = mp.process(thickness, z_tolerance, ecl_grid.getPinchMaxEmptyGap(),
poreVolume, ecl_grid.getMinpvVector(), actnumData, false,
zcornData.data(), nogap, pinchOptionALL,
permZ, multZ, tolerance_unique_points);
if (!minpv_result.nnc.empty()) {
this->zcorn = zcornData;
}
}catch(const std::runtime_error& e){
int success = 0;
// comminicate failure to others.
ccobj_.broadcast(&success, 1, 0);
throw; // rethrow
}
int success = 1;
// communicate success to others
ccobj_.broadcast(&success, 1, 0);
// Add PINCH NNCs.
std::vector<Opm::NNCdata> pinchedNNCs;
for (const auto& [cell1, cell2] : minpv_result.nnc) {
nnc_cells[PinchNNC].insert({cell1, cell2});
if (pinchOptionALL) {
auto topIJK = ecl_grid.getIJK(cell1);
auto bottomIJK = ecl_grid.getIJK(cell2);
std::vector<double> trans_between(bottomIJK[2]-topIJK[2]);
std::vector<std::size_t> cells_between;
cells_between.reserve(trans_between.size());
// first we need to calculate transmissibilities from permeability and geometry
auto trans = trans_between.begin();
auto bottom_cell_info = ecl_grid.getCellAndBottomCenterNormal(cell1);
// We calculate the transmissibilty tran for each intersection between the
// two active cells. For each intersection we need geometry information
// (distance from cell center to face center, face area and normal) of the
// the top (cell_top) and the bottom cell (cell_bottom).
// we start at the top (top cell is active) and iterate until the bottom
// (bottom cell is active).
for (std::size_t cell_top = cell1, cell_bottom = cell_top
+ ecl_grid.getNX() * ecl_grid.getNY();
cell_top < static_cast<std::size_t>(cell2);
cell_top = cell_bottom, cell_bottom = cell_top
+ ecl_grid.getNX() * ecl_grid.getNY(), ++trans) {
const auto top_cell_info = bottom_cell_info;
bottom_cell_info = ecl_grid.getCellAndBottomCenterNormal(cell_bottom);
const auto& cell_center_bottom = std::get<0>(bottom_cell_info);
cells_between.push_back(cell_top);
auto compute_half_trans =
[](const auto& cell_center,
const auto& face_center,
const auto& area_normal,
double perm)
{
auto half_trans = perm;
std::array<double, 3> distance;
std::ranges::transform(cell_center, face_center,
distance.begin(), std::minus<double>());
half_trans *= std::abs(std::inner_product(area_normal.begin(),
area_normal.end(),
distance.begin(), 0.));
half_trans /= std::inner_product(distance.begin(),
distance.end(),
distance.begin(), 0.);
return half_trans;
};
auto half_trans_top = compute_half_trans(std::get<0>(top_cell_info),
std::get<1>(top_cell_info),
std::get<2>(top_cell_info),
permZ[cell_top]);
auto half_trans_bottom = compute_half_trans(cell_center_bottom,
std::get<1>(top_cell_info),
std::get<2>(top_cell_info),
permZ[cell_bottom]);
if (std::abs(half_trans_top) < 1e-30 || std::abs(half_trans_bottom) < 1e-30)
*trans = 0.0;
else
*trans = 1.0 / (1.0/half_trans_top + 1.0/half_trans_bottom);
}
// Possibly overwrite with specified TRANZ values.
if (fp.tran_active("TRANZ"))
{
fp.apply_tranz_global(cells_between, trans_between);
}
// Apply Multipliers
// \todo FIXME We assume here that MULTZ does not change in the SCHEDULE or such changes have
// no effect here. This might be wrong and need fixing. Which basically means we need to store
// all the intermediate transmissibilities for the harmonic average and later apply additional
// multipliers
const auto& transMult = ecl_state->getTransMult();
trans = trans_between.begin();
for (std::size_t cell_top = cell1, cell_bottom = cell_top + ecl_grid.getNX() * ecl_grid.getNY();
cell_top < static_cast<std::size_t>(cell2);
cell_top = cell_bottom, cell_bottom += ecl_grid.getNX() * ecl_grid.getNY(), ++trans) {
*trans *= transMult.getMultiplier(cell_top, ::Opm::FaceDir::ZPlus) *
transMult.getMultiplier(cell_bottom, ::Opm::FaceDir::ZMinus);
}
//Compute harmonic average over pinched out cells.
double average{};
bool isZero = false;
for(const auto& trans1: trans_between)
if (std::abs(trans1) >= 1e-30)
average += 1.0 / trans1;
else
isZero = true;
if (isZero)
average = 0;
else
average = 1.0 / average;
// Set nnc and transmissibility, last param indicates that this from pinch
// It is needed to overwrite transmissibilities instead of adding to existing ones.
pinchedNNCs.emplace_back(cell1, cell2, average);
}
}
if (!nnc_cells[PinchNNC].empty()) {
auto suffix = std::string{(nnc_cells[PinchNNC].size() != 1)? "s" : ""};
Opm::OpmLog::info(std::to_string(nnc_cells[PinchNNC].size()) + " pinch-out connection" + suffix + " generated");
}
// Add explicit NNCs.
const auto& nncs = ecl_state->getInputNNC();
for (const auto& single_nnc : nncs.input()) {
// Repeated NNCs will only exist in the map once (repeated
// insertions have no effect). The code that computes the
// transmissibilities is responsible for ensuring repeated NNC
// transmissibilities are added.
nnc_cells[ExplicitNNC].insert({single_nnc.cell1, single_nnc.cell2});
}
// Add the pinch NNCs with transmissibilties due to PINCH option 4 all
ecl_state->setPinchNNC(std::move(pinchedNNCs));
ecl_state->prune_global_for_schedule_run();
}
// this variable is only required because getCellZvals() needs
// a coord_t instead of a plain integer pointer...
coord_t logicalCartesianSize;
for (int axisIdx = 0; axisIdx < 3; ++axisIdx)
logicalCartesianSize[axisIdx] = g.dims[axisIdx];
// Handle zcorn clipping. The g variable points to the data in
// the clipped_zcorn variable, i.e. clipped_zcorn must remain
// in scope.
std::vector<double> clipped_zcorn;
if (clip_z) {
double minz_top = 1e100;
double maxz_bot = -1e100;
for (int i = 0; i < g.dims[0]; ++i) {
for (int j = 0; j < g.dims[1]; ++j) {
coord_t logicalCartesianCoord;
logicalCartesianCoord[0] = i;
logicalCartesianCoord[1] = j;
logicalCartesianCoord[2] = 0;
std::array<double, 8> cellz_bot = getCellZvals(logicalCartesianCoord, logicalCartesianSize, &zcornData[0]);
logicalCartesianCoord[2] = g.dims[2] - 1;
std::array<double, 8> cellz_top = getCellZvals(logicalCartesianCoord, logicalCartesianSize, &zcornData[0]);
for (int dd = 0; dd < 4; ++dd) {
minz_top = std::min(cellz_top[dd+4], minz_top);
maxz_bot = std::max(cellz_bot[dd], maxz_bot);
}
}
}
if (minz_top <= maxz_bot) {
OPM_THROW(std::runtime_error, "Grid cannot be clipped to a shoe-box (in z): Would be empty afterwards.");
}
int num_zcorn = zcornData.size();
clipped_zcorn.resize(num_zcorn);
for (int i = 0; i < num_zcorn; ++i) {
clipped_zcorn[i] = std::max(maxz_bot, std::min(minz_top, g.zcorn[i]));
}
g.zcorn = &clipped_zcorn[0];
this->zcorn = clipped_zcorn;
}
if (periodic_extension) {
// Extend grid periodically with one layer of cells in the (i, j) directions.
std::vector<double> new_coord{};
std::vector<double> new_zcorn{};
std::vector<int> new_actnum{};
grdecl new_g{};
addOuterCellLayer(g, new_coord, new_zcorn, new_actnum, new_g);
// Make the grid.
this->processEclipseFormat(new_g,
ecl_state,
nnc_cells,
true,
turn_normals,
pinchActive,
tolerance_unique_points,
/* edge_conformal = */ false);// maybe need at some point?
}
else {
// Make the grid.
this->processEclipseFormat(g,
ecl_state,
nnc_cells,
false,
turn_normals,
pinchActive,
tolerance_unique_points,
edge_conformal);
}
return minpv_result.removed_cells;
}
#endif // #if HAVE_OPM_COMMON
enum { NNCFace = -1 };
/// Read the Eclipse grid format ('.grdecl').
void CpGridData::processEclipseFormat(const grdecl& input_data,
#if HAVE_OPM_COMMON
Opm::EclipseState* ecl_state,
#endif
NNCMaps& nnc,
const bool remove_ij_boundary,
const bool turn_normals,
const bool pinchActive,
const double tolerance_unique_points,
const bool edge_conformal)
{
if (ccobj_.rank() != 0) {
OPM_THROW(std::logic_error, "Processing corner-point grid "
"description only supported on rank 0");
}
#ifdef VERBOSE
std::cout << "Processing corner-point grid description." << std::endl;
#endif
processed_grid output{};
int process_ok{};
#if HAVE_OPM_COMMON
// Whether the numerical aquifers of the deck are represented by taking over grid
// cells. When they are not, the grid must come out exactly as it would without
// the AQUNUM records: no cells kept alive for their sake, no cell volumes
// overridden, and above all no non-neighbour connections generated -- the
// simulator represents those aquifers itself. Not generating them is also what
// makes such a deck usable with edge-conformal processing, which cannot handle
// non-neighbour connections at all.
const bool numAquiferInGrid = (ecl_state != nullptr)
&& ecl_state->aquifer().hasNumericalAquifer()
&& (ecl_state->numericalAquiferMode() == Opm::NumericalAquiferMode::GridCells);
if (numAquiferInGrid) {
const std::size_t global_nc =
static_cast<std::size_t>(input_data.dims[0]) *
static_cast<std::size_t>(input_data.dims[1]) *
static_cast<std::size_t>(input_data.dims[2]);
std::vector<int> is_aquifer_cell(global_nc, 0);
const auto aquifer_cells = ecl_state->aquifer()
.numericalAquifers().allAquiferCellIds();
for (const auto& global_index : aquifer_cells) {
is_aquifer_cell[global_index] = 1;
}
process_ok = process_grdecl(static_cast<int>(pinchActive),
static_cast<int>(edge_conformal),
tolerance_unique_points,
&input_data,
is_aquifer_cell.data(),
&output);
}
else
#endif
{
process_ok = process_grdecl(static_cast<int>(pinchActive),
static_cast<int>(edge_conformal),
tolerance_unique_points,
&input_data,
/* is_aquifer_cell = */ nullptr,
&output);
}
if (process_ok == 0) {
OPM_THROW(std::runtime_error,
"Failed to build unstructured "
"grid from COORD/ZCORN");
}
if (remove_ij_boundary) {
removeOuterCellLayer(output);
// removeUnusedNodes(output);
}
#if HAVE_OPM_COMMON
if (numAquiferInGrid) {
const std::size_t global_nc =
static_cast<std::size_t>(input_data.dims[0]) *
static_cast<std::size_t>(input_data.dims[1]) *
static_cast<std::size_t>(input_data.dims[2]);
std::vector<int> new_actnum(global_nc, 0);
for (int i = 0; i < output.number_of_cells; ++i) {
new_actnum[output.local_cell_index[i]] = 1;
}
const auto& ecl_grid = ecl_state->getInputGrid();
ecl_state->aquifer().mutableNumericalAquifers()
.postProcessConnections(ecl_grid, new_actnum);
const auto& fp = ecl_state->fieldProps();
const auto& aquifer_nnc = ecl_state->aquifer().numericalAquifers()
.aquiferConnectionNNCs(ecl_grid, fp);
// We need to update the nnc in the ecl_state
ecl_state->appendInputNNC(aquifer_nnc);
for (const auto& single_nnc : aquifer_nnc) {
nnc[ExplicitNNC].insert({single_nnc.cell1, single_nnc.cell2});
}
}
#endif
// Move data into the grid's structures.
#ifdef VERBOSE
std::cout << "Building topology." << std::endl;
#endif
std::vector<int> face_to_output_face{};
buildTopo(output, nnc, global_cell_,
cell_to_face_, face_to_cell_,
face_to_point_, cell_to_point_,
face_to_output_face);
std::copy_n(output.dimensions, 3, logical_cartesian_size_.begin());
#ifdef VERBOSE
std::cout << "Building geometry." << std::endl;
#endif
// here we need the cell volumes based on the active index order
std::unordered_map<std::size_t, double> aquifer_cell_volumes_local{};
#if HAVE_OPM_COMMON
if (numAquiferInGrid) {
const auto& aquifer_cell_volumes = ecl_state->aquifer()
.numericalAquifers().aquiferCellVolumes();
aquifer_cells_.reserve(aquifer_cell_volumes.size());
for (auto nc = this->global_cell_.size(), i = 0 * nc; i < nc; ++i) {
auto aquCellPos = aquifer_cell_volumes.find(this->global_cell_[i]);
if (aquCellPos != aquifer_cell_volumes.end()) {
aquifer_cell_volumes_local.emplace(i, aquCellPos->second);
aquifer_cells_.push_back(i);
}
}
std::ranges::sort(aquifer_cells_);
}
#endif
buildGeom(output, cell_to_face_, cell_to_point_,
face_to_output_face,
aquifer_cell_volumes_local,
*geometry_.geomVector(std::integral_constant<int,0>()),
*geometry_.geomVector(std::integral_constant<int,1>()),
geometry_.geomVector(std::integral_constant<int,3>()),
face_normals_,
turn_normals);
#ifdef VERBOSE
std::cout << "Assigning face tags." << std::endl;
#endif
const int nf = face_to_output_face.size();
std::vector<enum face_tag> temp_tags(nf);
for (int i = 0; i < nf; ++i) {
const int output_face = face_to_output_face[i];
temp_tags[i] = (output_face == -1)
? NNC_FACE
: output.face_tag[output_face];
}
face_tag_.assign(temp_tags.begin(), temp_tags.end());
#ifdef VERBOSE
std::cout << "Cleaning up." << std::endl;
#endif
// Clean up the output struct.
free_processed_grid(&output);
computeUniqueBoundaryIds();
if (ccobj_.size() > 1) {
populateGlobalCellIndexSet();
}
index_set_ = std::make_unique<IndexSet>(cell_to_face_.size(), geomVector<3>().size());
#ifdef VERBOSE
std::cout << "Done with grid processing." << std::endl;
#endif
}
} // end namespace cpgrid
// ---- Implementation details below ----
namespace
{
#if HAVE_OPM_COMMON
std::vector<double>
getSanitizedZCORN(const ::Opm::EclipseGrid& ecl_grid,
const ::std::vector<int>& actnumData)
{
std::vector<double> zcornData = ecl_grid.getZCORN();
auto repair = ::Opm::UgGridHelpers::RepairZCORN {
std::move(zcornData), actnumData,
std::vector<std::size_t>{ ecl_grid.getNX() ,
ecl_grid.getNY() ,
ecl_grid.getNZ() }
};
zcornData = repair.destructivelyGrabSanitizedValues();
if (repair.switchedToDepth()) {
std::cout << "ZCORN Values Switched from Elevation to "
<< "Depth (Sign Reversal)\n";
}
{
const auto& statTBB = repair.statTopBelowBottom();
if (statTBB.cells > std::size_t{0}) {
std::cout << "ZCORN Changes From Top Not Below Bottom:\n"
<< " - Number of Cells Changed: "
<< statTBB.cells << '\n'
<< " - Number of Corners Changed: "
<< statTBB.corners << '\n';
}
}
{
const auto& statBBLT = repair.statBottomBelowLowerTop();
if (statBBLT.cells > std::size_t{0}) {
std::cout << "ZCORN Changes From Bottom Not Below Lower Top:\n"
<< " - Number of Cells Changed: "
<< statBBLT.cells << '\n'
<< " - Number of Corners Changed: "
<< statBBLT.corners << '\n';
}
}
return zcornData;
}
typedef std::array<int, 3> coord_t;
typedef std::array<double, 8> cellz_t;
cellz_t getCellZvals(const coord_t& c, const coord_t& n, const double* z)
{
// cout << c << endl;
const int delta[3] = {
1,
2*n[0],
4*n[0]*n[1]
};
int ix = 2*(c[0]*delta[0] + c[1]*delta[1] + c[2]*delta[2]);
// cout << ix << endl;
cellz_t cellz = {{ z[ix], z[ix + delta[0]],
z[ix + delta[1]], z[ix + delta[1] + delta[0]],
z[ix + delta[2]], z[ix + delta[2] + delta[0]],
z[ix + delta[2] + delta[1]], z[ix + delta[2] + delta[1] + delta[0]] }};
return cellz;
}
void setCellZvals(const coord_t& c, const coord_t& n, double* z, const cellz_t& cellvals)
{
const int delta[3] = {
1,
2*n[0],
4*n[0]*n[1]
};
int ix = 2*(c[0]*delta[0] + c[1]*delta[1] + c[2]*delta[2]);
z[ix] = cellvals[0];
z[ix + delta[0]] = cellvals[1];
z[ix + delta[1]] = cellvals[2];
z[ix + delta[1] + delta[0]] = cellvals[3];
z[ix + delta[2]] = cellvals[4];
z[ix + delta[2] + delta[0]] = cellvals[5];
z[ix + delta[2] + delta[1]] = cellvals[6];
z[ix + delta[2] + delta[1] + delta[0]] = cellvals[7];
}
coord_t indexToIjk(const coord_t& n, const int index)
{
coord_t c;
c[2] = index/(n[0]*n[1]);
c[1] = (index%(n[0]*n[1]))/n[0];
c[0] = index%n[0];
return c;
}
void findTopAndBottomZ(const coord_t& n, const std::vector<double>& z, double& zb, double& zt)
{
int numperlevel = 4*n[0]*n[1];
zb = *std::max_element(z.begin(), z.begin() + numperlevel);
zt = *std::min_element(z.end() - numperlevel, z.end());
}
/// Add an outer cell layer in the (i, j) directions,
/// repeating the cells on the other side (for periodic
/// boundary conditions).
void addOuterCellLayer(const grdecl& original,
std::vector<double>& new_coord,
std::vector<double>& new_zcorn,
std::vector<int>& new_actnum,
grdecl& output)
{
// Based on periodic_extension.cpp from the old C++ code,
// with a few changes:
// 1. We want actnum of the added cells to be true.
// 2. We do not treat other fields such as PORO, SATNUM etc.
// since the grid will be reduced back to its regular
// size before those fields are processed.
OPM_MESSAGE("WARNING: Assuming vertical pillars in a cartesian grid.");
// Build new-to-old cell index table.
// First expand in x.
coord_t n = {{ original.dims[0], original.dims[1], original.dims[2] }};
std::vector<int> x_new2old;
x_new2old.reserve((n[0]+2)*n[1]*n[2]);
for (int kz = 0; kz < n[2]; ++kz) {
for (int jy = 0; jy < n[1]; ++jy) {
int row_ix = kz*n[0]*n[1] + jy*n[0];
x_new2old.push_back(row_ix + n[0] - 1);
for (int ix = 1; ix < n[0] + 1; ++ix) {
x_new2old.push_back(row_ix + ix - 1);
}
x_new2old.push_back(row_ix);
}
}
// copy(x_new2old.begin(), x_new2old.end(), ostream_iterator<int>(cout, " "));
// cout << endl;
// Then expand in y.
const int num_new_cells = (n[0]+2)*(n[1]+2)*n[2];
std::vector<int> new2old;
new2old.reserve(num_new_cells);
for (int kz = 0; kz < n[2]; ++kz) {
for (int jy = 0; jy < n[1] + 2; ++jy) {
int offset = kz*(n[0] + 2)*n[1] + (jy - 1)*(n[0] + 2);
if (jy == 0) {
offset = kz*(n[0] + 2)*n[1] + (n[1] - 1)*(n[0] + 2);
} else if (jy == n[1] + 1) {
offset = kz*(n[0] + 2)*n[1];
}
for (int ix = 0; ix < n[0] + 2; ++ix) {
new2old.push_back(x_new2old[offset + ix]);
}
}
}
assert(int(new2old.size()) == num_new_cells);
// copy(new2old.begin(), new2old.end(), ostream_iterator<int>(cout, " "));
// cout << endl;
// On second thought, we should have used a multidimensional array or something...
// Build new COORD field.
std::vector<double> coord;
coord.reserve(6*(n[0] + 3)*(n[1] + 3));
const double* old_coord = original.coord;
double dx = old_coord[6] - old_coord[0];
double dy = old_coord[6*(n[0] + 1) + 1] - old_coord[1];
double ox = old_coord[0] - dx;
double oy = old_coord[1] - dy;
for (int jy = 0; jy < n[1] + 3; ++jy) {
double y = oy + jy*dy;
for (int ix = 0; ix < n[0] + 3; ++ix) {
double x = ox + ix*dx;
coord.push_back(x);
coord.push_back(y);
coord.push_back(0.0);
coord.push_back(x);
coord.push_back(y);
coord.push_back(1.0);
}
}
// Build new ZCORN field, PERMX, PORO, ACTNUM, SATNUM.
const double* old_zcorn = original.zcorn;
const int* old_actnum = original.actnum;
std::vector<double> zcorn(8*num_new_cells);
std::vector<int> actnum(num_new_cells);
coord_t new_n = {{ n[0] + 2, n[1] + 2, n[2] }};
for (int kz = 0; kz < new_n[2]; ++kz) {
for (int jy = 0; jy < new_n[1]; ++jy) {
for (int ix = 0; ix < new_n[0]; ++ix) {
int new_cell_index = ix + jy*(new_n[0]) + kz*(new_n[0])*(new_n[1]);
int old_cell_index = new2old[new_cell_index];
cellz_t cellvals = getCellZvals(indexToIjk(n, old_cell_index), n, old_zcorn);
// cout << new_cell_index << ' ' << old_cell_index << ' ' << cellvals << endl;
setCellZvals(indexToIjk(new_n, new_cell_index), new_n, &zcorn[0], cellvals);
actnum[new_cell_index] = old_actnum?old_actnum[old_cell_index]:1;
if (ix == 0 || ix == new_n[0] - 1
|| jy == 0 || jy == new_n[1] - 1) {
actnum[new_cell_index] = 1; // This line is changed from the original.
}
}
}
}
// Clamp z-coord to make shoe box shape
constexpr bool clamp_z = true;
if constexpr (clamp_z) {
double zb;
double zt;
findTopAndBottomZ(new_n, zcorn, zb, zt);
for (int i = 0; i < int(zcorn.size()); ++i) {
zcorn[i] = std::min(zt, std::max(zb, zcorn[i]));
}
}
// Build output.
new_coord.swap(coord);
new_zcorn.swap(zcorn);
new_actnum.swap(actnum);
output.dims[0] = new_n[0];
output.dims[1] = new_n[1];
output.dims[2] = new_n[2];
output.coord = &new_coord[0];
output.zcorn = &new_zcorn[0];
output.actnum = &new_actnum[0];
}
#endif
/// Helper function used by removeOuterCellLayer().
int newLogCartFromOld(const int idx, const int dim[3])
{
// Compute old (i, j, k).
const int Nx = dim[0];
const int Ny = dim[1];
const int NxNy = Nx*Ny;
int k = idx/NxNy;
// if (k <= 0 || k >= dim[2] - 1) return -1;
int j = (idx - NxNy*k)/Nx;
if (j <= 0 || j >= Ny - 1) return -1;
int i = idx - Nx*j - Nx*Ny*k;
if (i <= 0 || i >= Nx - 1) return -1;
// return (Nx - 2)*(Ny - 2)*(k - 1) + (Nx - 2)*(j - 1) + (i - 1);
return (Nx - 2)*(Ny - 2)*k + (Nx - 2)*(j - 1) + (i - 1);
}
/// Removes all (i, j) boundary cells from a grid.
void removeOuterCellLayer(processed_grid& grid)
{
// Remove outer cells as follows:
// 1. Build a new local_cell_index (in a new variable), compute new number_of_cells.
// 2. Build the inverse lookup: From old logical cartesian to new cell indices.
// 3. Modify face_neighbours by replacing each entry by its new cell index (or -1).
// 4. Modify dimensions[], number_of_cells and replace local_cell_index.
// After this, we still have the same number of faces, it's just that some of them may
// have only (-1, -1) as neighbours.
// Part 1 and 2 in one pass.
std::vector<int> new_index_to_new_lcart;
new_index_to_new_lcart.reserve(grid.number_of_cells); // A little too large, but no problem.
int num_old_lcart = grid.dimensions[0]*grid.dimensions[1]*grid.dimensions[2];
std::vector<int> old_lcart_to_new_index(num_old_lcart, -1);
for (int i = 0; i < grid.number_of_cells; ++i) {
int old_lcart = grid.local_cell_index[i];
int new_lcart = newLogCartFromOld(old_lcart, grid.dimensions);
if (new_lcart != -1) {
old_lcart_to_new_index[old_lcart] = new_index_to_new_lcart.size();
new_index_to_new_lcart.push_back(new_lcart);
} else {
old_lcart_to_new_index[old_lcart] = -1;
}
}
// Part 3, modfying the face->cell connections.
for (unsigned i = 0; i < 2*grid.number_of_faces; ++i) {
int old_index = grid.face_neighbors[i];
if (old_index != -1) {
int old_lcart = grid.local_cell_index[old_index];
int new_index = old_lcart_to_new_index[old_lcart];
grid.face_neighbors[i] = new_index; // May be -1, if cell is to be removed.
}
}
// Part 4, modifying the other output data.
grid.dimensions[0] = grid.dimensions[0] - 2;
grid.dimensions[1] = grid.dimensions[1] - 2;
grid.dimensions[2] = grid.dimensions[2] - 2;
grid.number_of_cells = new_index_to_new_lcart.size();
std::ranges::copy(new_index_to_new_lcart, grid.local_cell_index);
}
/*
// NOTE: This function has been commented out as it is not in use, and therefore
// generates warnings. It has not been deleted, as it should eventually be
// used, what is missing is thorough testing of the method.
void removeUnusedNodes(processed_grid& grid)
{
// Nodes are considered unused if they are unreachable from a cell.
// The following data are modified by this function:
// grid.face_nodes
// grid.number_of_nodes
// grid.node_coordinates[]
// The following caveats apply:
// - grid.face_nodes will contain -1 where nodes have been removed
// (this will only happen for faces not neighbouring any cells)
// - grid.number_of_nodes_on_pillars is unchanged (and therefore wrong)
// Remove unused nodes in three steps:
//
// 1. Build the old_to_new node index array (-1 means removed).
//
// a) Initially, all are considered unused. We first signify usage
// by changing to a 0 the entries corresponding to reachable nodes.
std::vector<int> old_to_new(grid.number_of_nodes, -1);
for (int face = 0; face < grid.number_of_faces; ++face) {
if (grid.face_neighbors[2*face] != -1 || grid.face_neighbors[2*face + 1] != -1) {
// Face is reachable
for (int ii = grid.face_node_ptr[face]; ii < grid.face_node_ptr[face + 1]; ++ii) {
int node = grid.face_nodes[ii];
old_to_new[node] = 0;
}
}
}
// b) Set the new indices by simple array compression.
int nodecount = 0;
for (int node = 0; node < grid.number_of_nodes; ++node) {
if (old_to_new[node] != -1) {
assert(old_to_new[node] == 0);
old_to_new[node] = nodecount;
++nodecount;
}
}
// 2. Use old_to_new to transform grid.face_nodes and grid.node_coordinates[].
for (int fnode = 0; fnode < grid.face_node_ptr[grid.number_of_faces]; ++fnode) {
int old = grid.face_nodes[fnode];
grid.face_nodes[fnode] = old_to_new[old];
}
double* nc = grid.node_coordinates;
for (int node = 0; node < grid.number_of_nodes; ++node) {
int newidx = old_to_new[node];
if (newidx != -1) {
nc[3*newidx] = nc[3*node];
nc[3*newidx + 1] = nc[3*node + 1];
nc[3*newidx + 2] = nc[3*node + 2];
}
}
// 3. Set grid.number_of_nodes.
grid.number_of_nodes = nodecount;
}
*/