-
Notifications
You must be signed in to change notification settings - Fork 0
/
flowgrid.py
2809 lines (2565 loc) · 115 KB
/
flowgrid.py
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
import os, io
import numpy as np
from datetime import *
import getpass
import string
import copy
import math
import codecs, json
from mpl_toolkits.mplot3d import axes3d
from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt
import vtk
from vtk.util.numpy_support import vtk_to_numpy
# import pkg_resources # part of setuptools
# version = pkg_resources.require("ReGrid")[0].version
f2m = 0.3048 # ft to m
class FlowGrid(object):
def __init__(self):
self.skip = 0
self.Prop = {}
self.out_dir = 'output'
def __getitem__(self, key):
return getattr(self, key)
def set_out_dir(self, dir):
self.out_dir = dir
def _check_out(self, subDir):
if not os.path.exists(os.path.join(self.out_dir, subDir)):
os.makedirs(os.path.join(self.out_dir, subDir))
def cell_verts(self, idx):
"""
Get xyz coordinates for each vertex of a cell
Grid geometry must be constructed first
Parameters
----------
idx : array_like of int
(Size 3) ijk indices of a cell, starting at 1
Returns
-------
coords : array_like of array_like of float
Sub-arrays contain xyz coordinates of cell vertices
"""
coords = []
xyz = [0, 0, 0]
cell = self.grid.GetCell(idx[0] - 1, idx[1] - 1, idx[2] - 1)
p_ids = cell.GetPointIds()
n_ids = pointIds.GetNumberOfIds()
for n in range(n_ids):
p = p_ids.GetId(n)
self.grid.GetPoint(p, xyz)
coords.append(copy.deepcopy(xyz))
return coords
def centroid(self, coords):
"""
Compute center coordinates of cell
Parameters
----------
coords : array_like of array_like of float
(Size 6) Vertex coordinates of cell
Returns
-------
center : array_like of float
xyz coordinates of center of cell
"""
return np.mean(coords, axis=0)
def exportVTK(self, fname):
""" Saves the SUTRA grid as a VTK file, either a VTKStructuredGrid (.vts)
or a VTKUnstructuredGrid (.vtu) depending on mesh type.
fname = the filename it will be saved at, if no extension is given,
.vts is appended
"""
filename, ext = os.path.splitext(fname)
if self.GridType == "vtkStructuredGrid":
sWrite = vtk.vtkXMLStructuredGridWriter()
sWrite.SetInputData(self.Grid)
sWrite.SetFileName(filename + ".vts")
sWrite.Write()
elif self.GridType == "vtkUnstructuredGrid":
sWrite = vtk.vtkXMLUnstructuredGridWriter()
sWrite.SetInputData(self.Grid)
sWrite.SetFileName(filename + ".vtu")
sWrite.Write()
else:
print("Grid type is not recognized")
def printCOORDS(self, f, p, fstr):
MAXL = 132
# if self.skip:
# self.skip -= 1
# return fstr
for point in p:
up = " %2.2f" % (point)
if len(fstr) + len(up) > MAXL:
f.write(fstr + "\n")
fstr = " "
fstr += up
return fstr
def printAC(self, f, p, N, fstr):
MAXL = 132
if N == 1:
up = " %i" % (p)
else:
up = " %i*%i" % (N, p)
if len(fstr) + len(up) > MAXL:
f.write(fstr + "\n")
fstr = " "
fstr += up
return fstr
def printPROP(self, f, p, N, fstr):
MAXL = 132
if N == 1:
# up = " %1.4e" %(p) # standard notation
up = " %1.4e" % (p) # scientific notation
else:
up = " %i*%1.4e" % (N, p)
# up = " %i*%1.4e" %(N,p) # scientific notation
if len(fstr) + len(up) > MAXL:
f.write(fstr + "\n")
fstr = " "
fstr += up
return fstr
def exportTOUGH2(self, fname):
"""Saves the grid as a fixed format TOUGH(2) grid.
"""
STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
self.ne, self.nn, self.nz = np.array(self.Grid.GetDimensions()) # - 1 #
filename, ext = os.path.splitext(fname)
if self.GridType == "vtkStructuredGrid":
with io.open(filename, 'w', newline='\r\n') as f:
f.write("ELEME")
# debug
f.write(
"""
1 10 20 30 40 50 60 70 80
|--------|---------|---------|---------|---------|---------|---------|---------|
12345678901234567890123456789012345678901234567890123456789012345678901234567890
""")
ii = 0
for iy in range(self.nn):
for ix in range(self.ne):
# f.write(str(iy)+str(ix)+"\n")
# first base
b2 = ii // (len(STR) * len(STR))
b1 = (ii - len(STR) * b2) // len(STR)
b0 = ii % len(STR)
f.write(STR[b2] + STR[b1] + STR[b0] + "\t" + str(ii) + "\n")
ii += 1
def exportECL(self, fname):
""" Saves the grid as an ECLIPSE grid. For the purposes of ECLIPSE
"""
# TODO add consistency of dimensions across the inputs
self.ne, self.nn, self.nz = np.array(self.Grid.GetDimensions()) - 1 # ECLIPSE
filename, ext = os.path.splitext(fname)
if self.GridType == "vtkStructuredGrid":
with io.open(filename + ".GRDECL", 'w', newline='\r\n') as f:
f.write('-- Generated [\n')
f.write('-- Format : ECLIPSE keywords (grid geometry and properties) (ASCII)\n')
# f.write('-- Exported by : Petrel 2013.7 (64-bit) Schlumberger\n'
f.write('-- Exported by : ReGrid v.' + version + "\n")
f.write('-- User name : ' + getpass.getuser() + "\n")
f.write('-- Date : ' + datetime.now().strftime("%A, %B %d %Y %H:%M:%S") + "\n")
f.write('-- Project : ' + "ReGrid project\n")
f.write('-- Grid : ' + "Description\n")
f.write('-- Generated ]\n\n')
f.write('SPECGRID -- Generated : ReGrid\n')
f.write(' %i %i %i 1 F /\n\n' % (self.ne, self.nn, self.nz))
f.write('COORDSYS -- Generated : ReGrid\n')
f.write(' 1 4 /\n\n') # what is this line?
f.write('COORD -- Generated : ReGrid\n')
nz = self.nz
fstr = str(" ")
for iy in range(self.nn):
for ix in range(self.ne):
p0 = self.Grid.GetCell(ix, iy, 0).GetPoints().GetPoint(0)
fstr = self.printCOORDS(f, p0, fstr)
p1 = self.Grid.GetCell(ix, iy, nz - 1).GetPoints().GetPoint(4)
fstr = self.printCOORDS(f, p1, fstr)
# outside edge on far x
p2 = self.Grid.GetCell(ix, iy, 0).GetPoints().GetPoint(1)
fstr = self.printCOORDS(f, p2, fstr)
p3 = self.Grid.GetCell(ix, iy, nz - 1).GetPoints().GetPoint(5)
fstr = self.printCOORDS(f, p3, fstr)
# outside edge on far y
for ix in range(self.ne):
p8 = self.Grid.GetCell(ix, iy, 0).GetPoints().GetPoint(3)
fstr = self.printCOORDS(f, p8, fstr)
p9 = self.Grid.GetCell(ix, iy, nz - 1).GetPoints().GetPoint(7)
fstr = self.printCOORDS(f, p9, fstr)
# outside edge on far northeast
p14 = self.Grid.GetCell(ix, iy, 0).GetPoints().GetPoint(2)
fstr = self.printCOORDS(f, p14, fstr)
p15 = self.Grid.GetCell(ix, iy, nz - 1).GetPoints().GetPoint(6)
fstr = self.printCOORDS(f, p15, fstr)
f.write(fstr)
fstr = " "
f.write(" /")
f.write("\n")
f.write("\n")
f.write('ZCORN -- Generated : ReGrid\n')
for iz in range(self.nz):
for iy in range(self.nn):
# front face
for ix in range(self.ne):
p0 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(0)
p1 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(1)
fstr = self.printCOORDS(f, [p0[2]], fstr)
fstr = self.printCOORDS(f, [p1[2]], fstr)
# back face
for ix in range(self.ne):
p0 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(3)
p1 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(2)
fstr = self.printCOORDS(f, [p0[2]], fstr)
fstr = self.printCOORDS(f, [p1[2]], fstr)
# bottom layer
for iy in range(self.nn):
# front face
for ix in range(self.ne):
p0 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(4)
p1 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(5)
fstr = self.printCOORDS(f, [p0[2]], fstr)
fstr = self.printCOORDS(f, [p1[2]], fstr)
# back face
for ix in range(self.ne):
p0 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(7)
p1 = self.Grid.GetCell(ix, iy, iz).GetPoints().GetPoint(6)
fstr = self.printCOORDS(f, [p0[2]], fstr)
fstr = self.printCOORDS(f, [p1[2]], fstr)
f.write(fstr)
fstr = " "
f.write(" /")
f.write("\n")
f.write("\n")
f.write('ACTNUM -- Generated : ReGrid\n')
c = -999
N = 0
for iac in self.ActiveCells.flatten(order='F'):
if iac == c:
N += 1
else:
if c != -999:
fstr = self.printAC(f, c, N, fstr)
c = iac
N = 1
fstr = self.printAC(f, c, N, fstr)
f.write(fstr)
f.write(" /")
f.write("\n")
f.write("\n")
else:
print("Only structured grids can be converted to ECLIPSE files")
def exportECLPropertyFiles(self, fname):
""" Convert any point data to cell data
"""
# Convert point data to cell data for output
# verifying if this is necessary or if ECLIPSE can use point attributes
pointConvert = True
if pointConvert:
p2c = vtk.vtkPointDataToCellData()
p2c.SetInputDataObject(self.Grid)
p2c.PassPointDataOn()
p2c.Update()
self.Grid = p2c.GetOutput()
filename, ext = os.path.splitext(fname)
for ia in range(self.Grid.GetCellData().GetNumberOfArrays()):
prop = self.Grid.GetCellData().GetArray(ia).GetName()
print("exporting prop", prop)
if self.GridType == "vtkStructuredGrid":
with io.open(filename + "prop-" + prop.lower() + ".GRDECL", 'w', newline='\r\n') as f:
f.write('-- Generated [\n')
f.write('-- Format : ECLIPSE keywords (grid properties) (ASCII)\n')
f.write('-- Exported by : ReGrid v.' + version + "\n")
f.write('-- User name : ' + getpass.getuser() + "\n")
f.write('-- Date : ' + datetime.now().strftime("%A, %B %d %Y %H:%M:%S") + "\n")
f.write('-- Project : ' + "ReGrid project\n")
f.write('-- Grid : ' + "Description\n")
f.write('-- Unit system : ' + "ECLIPSE-Field\n")
f.write('-- Generated ]\n\n')
f.write(prop.upper() + ' -- Generated : ReGrid\n')
f.write('-- Property name in Petrel : ' + prop + '\n')
c = -999.9999
N = 0
ii = 0
fstr = " "
for iz in range(self.nz):
for iy in range(self.nn):
for ix in range(self.ne):
# iac = round(self.Grid.GetCellData().GetArray(ia).GetTuple1(ii), 4)
iac = '{:0.4e}'.format(self.Grid.GetCellData().GetArray(ia).GetTuple1(ii))
print(iac)
ii += 1
if iac == c:
N += 1
else:
if c != -999.9999:
fstr = self.printPROP(f, c, N, fstr)
c = eval(iac)
N = 1
fstr = self.printPROP(f, c, N, fstr)
f.write(fstr)
f.write(" /")
f.write("\n")
class GRDECL(FlowGrid):
"""
GRDECL processes Schlumberger ECLIPSE files
"""
def __init__(self):
super(GRDECL, self).__init__()
def loadNodes(self, fname):
"""
Reads I, J(max), K
iterates through I, then decriments J, increments K
I = easting
J = northing
K = depth or elevation?
"""
with open(fname, "r") as fp:
# Read in the header
for line in fp:
item = line.split()
if len(item) > 0:
if item[0] == "SPECGRID":
self.SPECGRID = np.array(fp.readline().split()[0:3], dtype=int)
if item[0] == "COORDSYS":
self.COORDSYS = fp.readline().split()
if item[0] == "COORD":
break
# Read in the coordinates
self.coords = []
for line in fp:
if line.split()[-1] != "/":
item = line.split()
for c in item:
if '*' in c:
cc = c.split('*')
for i in range(int(cc[0])):
self.coords.append(cc[-1])
else:
self.coords.append(c)
else:
if len(line.split()) > 1:
item = line.split()
for i in range(len(item) - 1):
cc = item[i]
if '*' in cc:
ccc = cc.split('*')
for j in range(int(ccc[0])):
self.coords.append(ccc[-1])
else:
self.coords.append(c)
break
else:
break
# Read in ZCORN
self.zcorn = []
i = 0
for line in fp:
item = line.split()
if len(item) > 0:
if item[0] == "ZCORN":
for line in fp:
if line.split():
if line.split()[-1] != "/":
self.zcorn += line.split()
else:
self.zcorn += line.split()[0:-1]
break
if len(self.zcorn) > 0:
break
# Read in (in)active cells
self.active = []
for line in fp:
item = line.split()
if len(item) > 0:
if item[0] == "ACTNUM":
for line in fp:
if line.split():
if line.split()[-1] != "/":
c = line.split()
if '*' in c:
cc = c.split('*')
for i in range(float(cc[0])):
self.active += cc[-1]
else:
self.active += c
else:
self.active += line.split()[0:-1]
break
self.coords = np.array(self.coords, dtype=float)
print(self.coords)
# In Petrel...
self.ne = self.SPECGRID[0] # x i
self.nn = self.SPECGRID[1] # y j
self.nz = self.SPECGRID[2] # z k
# build grid
self.buildGrid(plot=False)
self.buildActiveCells(plot=False)
self.buildZGrid(plot=False)
# self.calculateVolumes(plot=False)
#
# Convert to VTK
self.GridType = "vtkStructuredGrid"
self.Grid = vtk.vtkStructuredGrid()
self.Grid.SetDimensions(self.ne+1, self.nn+1, self.nz+1)
vtk_points = vtk.vtkPoints()
ve = 1.
for iz in range(self.nz):
if iz == 0:
for iy in range(self.nn+1):
for ix in range(self.ne+1):
vtk_points.InsertNextPoint( self.X0[ix,iy], \
self.Y0[ix,iy], \
ve * self.ZZT[iz][ix,iy] )
for iy in range(self.nn+1):
for ix in range(self.ne+1):
vtk_points.InsertNextPoint( self.X0[ix,iy], \
self.Y0[ix,iy], \
ve * self.ZZB[iz][ix,iy] )
self.Grid.SetPoints(vtk_points)
# Add in active cells
ac = vtk.vtkIntArray()
ac.SetName( "ActiveCells" )
for iac in self.ActiveCells.flatten( order='F' ):
ac.InsertNextTuple1( iac )
self.Grid.GetCellData().AddArray(ac)
def buildGrid(self, plot=False):
"""
Topology of COORD mesh, only describes first layer..
8--------10-------12-------14
/| /| /| /|
/ | / | / | / |
0--------2--------4--------6 |
| 9-----|--11----|--13----|--15
| / | / | / | /
|/ |/ |/ |/
1--------3--------5--------7 7 --> (2*(NE+1))
15 --> (2*(NE+1)*(NN+1))
"""
print("Constructing grid")
# print("Grid dims", self.ne, self.nn, self.nz)
# print("Num points", 2*(self.ne+1)*(self.nn+1)*3, len(self.coords))
# number of edges
self.ndx = self.ne + 1
self.ndy = self.nn + 1
self.ndz = self.nz + 1
# extract the triplets
self.points = {}
self.points["e"] = self.coords[0::3]
self.points["n"] = self.coords[1::3]
self.points["z"] = self.coords[2::3]
print('points e')
print(self.points["e"])
# Here are the coordinates
self.X0 = np.reshape(self.points["e"][0::2] , (self.ndx,self.ndy), order="F")
self.Y0 = np.reshape(self.points["n"][0::2] , (self.ndx,self.ndy), order="F")
self.Z0 = np.reshape(self.points["z"][0::2] , (self.ndx,self.ndy), order="F")
self.X1 = np.reshape(self.points["e"][1::2] , (self.ndx,self.ndy), order="F")
self.Y1 = np.reshape(self.points["n"][1::2] , (self.ndx,self.ndy), order="F")
self.Z1 = np.reshape(self.points["z"][1::2] , (self.ndx,self.ndy), order="F")
#
# # visualize
# if plot:
# print("plotting")
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.plot_wireframe(f2m*self.X0, f2m*self.Y0, f2m*self.Z0, rstride=1, cstride=1)
# ax.plot_wireframe(f2m*self.X1, f2m*self.Y1, f2m*self.Z1, rstride=1, cstride=1)
# plt.show()
def buildZGrid(self, plot=False):
"""
Petrel provides the ZCORN in a truly arcane ordering--it's awful--and really, the programmers
deserve a special place in hell for doing this. The ordering is as follows, for a given plane:
29 36 30 37 31 38 32 39 33 40 34 41 35 42
_______ _______ ______ _______ _______ _______ _______
/ / / / / / / / / / / / / /|
/ / / / / / / / / / / / / / |
00----01 02----03 04----05 06----07 08----09 10----11 12----13 /
| A | | B | | C | | D | | E | | F | | G |/
14----15 16----17 18----19 20----21 22----23 24----25 26----27
This pattern is then repeated for each depth layer, it isn't that clear, but my ASCII art skills
are already sufficiently challenged.
"""
print("Constructing Z corners")
# self.zcorn = np.array(self.zcorn, dtype=float)
# temp = np.zeros( ((self.ne+1)*(self.nn+1)*self.nz) )
temp = []
count = 0
for item in self.zcorn:
if "*" in item:
ct = (int)(item.split("*")[0])
vl = (float)(item.split("*")[1])
temp += np.tile(vl, ct).tolist()
count += ct
else:
temp += [(float)(item)]
count += 1
# layers = np.resize(temp, (8, self.ne*self.nn*self.nz ))
layers = np.resize(temp, (self.nz * 2, self.ne * self.nn * 4))
"""
plt.plot(newtemp[0,:]) # TOP 0 0
plt.plot(newtemp[1,:]) # SAME -- # BOTTOM 0 1
#plt.plot(newtemp[2,:]) # SAME -- # TOP 1 2
plt.plot(newtemp[3,:]) # SAME -- # BOTTOM 1 3
#plt.plot(newtemp[4,:]) # SAME -- # TOP 2 4
plt.plot(newtemp[5,:]) # SAME -- # BOTTOM 2 5
#plt.plot(newtemp[6,:]) # SAME -- # TOP 3 6
plt.plot(newtemp[7,:]) # BOTTOM 3 7
"""
self.ZZT = {} # zztop ha ha...two year's later this is still funny -TI
self.ZZB = {}
for ilay in range(self.nz):
self.ZZT[ilay] = np.zeros((self.ndx, self.ndy))
self.ZZB[ilay] = np.zeros((self.ndx, self.ndy))
iis = 0
# plt.plot(layers[ilay*2])
for iin in range(self.nn):
nears = {}
fars = {}
bnears = {}
bfars = {}
for iif in range(2):
# top
nears[iif] = layers[ilay * 2][iis:iis + 2 * self.ne][0::2].tolist()
fars[iif] = layers[ilay * 2][iis:iis + 2 * self.ne][1::2].tolist()
layers[ilay * 2][iis:iis + 2 * self.ne][0::2] *= 0. # check
layers[ilay * 2][iis:iis + 2 * self.ne][1::2] *= 0.
nears[iif].append(fars[iif][-1])
fars[iif] = [nears[iif][0]] + fars[iif]
# bottom
bnears[iif] = layers[ilay * 2 + 1][iis:iis + 2 * self.ne][0::2].tolist()
bfars[iif] = layers[ilay * 2 + 1][iis:iis + 2 * self.ne][1::2].tolist()
layers[ilay * 2 + 1][iis:iis + 2 * self.ne][0::2] *= 0.
layers[ilay * 2 + 1][iis:iis + 2 * self.ne][1::2] *= 0.
bnears[iif].append(bfars[iif][-1])
bfars[iif] = [bnears[iif][0]] + bfars[iif]
#
iis += 2 * self.ne
self.ZZT[ilay][:, iin] = nears[0]
self.ZZB[ilay][:, iin] = bnears[0]
# NaN mask for visualizing, but can be sort of a pain to deal with
# imask = np.nonzero( 1-self.ActiveCells[:,iin,ilay] )
# self.ZZT[ilay][:,iin][1::][imask] = np.nan
# self.ZZB[ilay][:,iin][1::][imask] = np.nan
# if self.ActiveCells[0,iin,ilay] == 0:
# self.ZZT[ilay][:,iin][0] = np.nan
# self.ZZB[ilay][:,iin][0] = np.nan
if iin == self.nn - 1:
self.ZZT[ilay][:, iin + 1] = fars[1]
self.ZZB[ilay][:, iin + 1] = bfars[1]
# NaN mask
# self.ZZT[ilay][:,iin+1][1::][imask] = np.nan
# self.ZZB[ilay][:,iin+1][1::][imask] = np.nan
# if self.ActiveCells[0,iin,ilay] == 0:
# self.ZZT[ilay][:,iin+1][0] = np.nan
# self.ZZB[ilay][:,iin+1][0] = np.nan
print("Layers ||", np.linalg.norm(layers), "||")
# exit()
# visualize
if plot:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.plot_wireframe( self.X0, self.Y0, self.Z0, rstride=1, cstride=1)
ax.plot_wireframe(self.X0, self.Y0, self.ZZT[0], rstride=1, cstride=1, color="blue")
# ax.plot_wireframe( self.X0, self.Y0, self.ZZT[1], rstride=1, cstride=1, color="blue")
# ax.plot_wireframe( self.X0, self.Y0, self.ZZT[2], rstride=1, cstride=1, color="blue")
# ax.plot_wireframe( self.X0, self.Y0, self.ZZT[3], rstride=1, cstride=1, color="blue")
# ax.plot_wireframe( self.X0, self.Y0, self.ZZB[3], rstride=1, cstride=1, color="green")
plt.gca().set_xlim(np.min(self.X0), np.max(self.X0))
plt.gca().set_ylim(np.max(self.Y0), np.min(self.Y0))
# plt.gca().set_zlim( np.max(self.ZZB[3]), np.min(self.ZZT[0]) )
plt.gca().set_zlim(5000, 4000)
plt.savefig("mesh.png")
plt.show()
def buildActiveCells(self, plot=False):
print("Constructing active cells")
self.ActiveCells = np.zeros((self.ne * self.nn * self.nz), dtype=int)
count = 0
for item in self.active:
if "*" in item:
ct = (int)(item.split("*")[0])
vl = (int)(item.split("*")[1])
self.ActiveCells[count:count + ct] = vl
count += ct
else:
self.ActiveCells[count] = (int)(item)
count += 1
self.ActiveCells = np.reshape(self.ActiveCells, (self.ne, self.nn, self.nz), order="F")
if plot:
plt.pcolor(self.X0.T, self.Y0.T, self.ActiveCells[:, :, 0].T, edgecolors='w', linewidths=.1)
plt.xlabel("easting")
plt.ylabel("northing")
plt.gca().set_xlim(np.min(self.X0), np.max(self.X0))
plt.gca().set_ylim(np.max(self.Y0), np.min(self.Y0))
plt.gca().xaxis.tick_top()
plt.gca().xaxis.set_label_position("top")
plt.show()
def calculateVolumes(self, plot=False):
# Iterate over cells, assert that we are dealing with parallelpiped, if so
# | u1 u2 u3 |
# A = det | v1 v2 v3 |
# | w1 w2 w3 |
# self.Volumes = 10000*np.random.normal(0,1, (self.ne, self.nn, self.nz) )
self.Volumes = np.zeros((self.ne, self.nn, self.nz))
for iiz in range(self.nz):
for iie in range(self.ne):
for iin in range(self.nn):
if self.ActiveCells[iie, iin, iiz]:
u = np.array((self.X0[iie, iin], self.Y0[iie, iin], self.ZZT[iiz][iie, iin])) - \
np.array((self.X0[iie + 1, iin], self.Y0[iie + 1, iin], self.ZZT[iiz][iie, iin]))
v = np.array((self.X0[iie, iin], self.Y0[iie, iin], self.ZZT[iiz][iie, iin])) - \
np.array((self.X0[iie, iin + 1], self.Y0[iie, iin + 1], self.ZZT[iiz][iie, iin]))
w = np.array((self.X0[iie, iin], self.Y0[iie, iin], self.ZZT[iiz][iie, iin])) - \
np.array((self.X0[iie, iin], self.Y0[iie, iin], self.ZZB[iiz][iie, iin]))
if np.any(u != u) or np.any(v != v) or np.any(w != w):
print("NAN!", iie, iin, iiz)
exit()
V = np.linalg.det(np.array((f2m * u, f2m * v, f2m * w)))
self.Volumes[iie, iin, iiz] = np.abs(V) # in m^3
vr = ((3. / (4. * np.pi)) * self.Volumes) ** (1. / 3.) # virtual radius, taking into account porosity
print("Total grid volume: " + str(np.sum(self.Volumes)) + " m^3")
def read_prop(self, fname, attr_name):
""" Reads a single property from a file
"""
print('Reading ' + attr_name + ' input')
temp = []
with open(fname, "r") as fp:
for line in fp:
item = line.split()
if len(item) > 0:
if item[0] != "--":
tag = item[0]
break
for line in fp:
attribute = line.split()
if attribute:
if attribute[0] != "--":
if attribute[-1] != "/":
for c in attribute:
if '*' in c:
cc = c.split('*')
for i in range(int(cc[0])):
temp.append(cc[-1])
else:
temp.append(c)
else:
attribute.pop()
for c in attribute:
if '*' in c:
cc = c.split('*')
for i in range(int(cc[0])):
temp.append(cc[-1])
else:
temp.append(c)
break
# #attribute = fp.readline().split()[-1]
# attribute = fp.readline().split()
# print(attribute)
# if attribute[0] != "--":
# self.Prop[tag] = attribute
# print("loading", attribute)
# for line in fp:
# if line.split():
# if line.split()[0] != "--":
# if line.split()[-1] != "/":
# temp += line.split()
# else:
# temp += line.split()[0:-1]
# break
print(temp)
data = np.zeros((self.ne * self.nn * self.nz), dtype=float)
count = 0
for item in temp:
if "*" in item:
ct = (int)(item.split("*")[0])
vl = (float)(item.split("*")[1])
data[count:count + ct] = vl
count += ct
else:
data[count] = (float)(item)
count += 1
data = np.reshape(data, (self.ne, self.nn, self.nz), order="F")
# Add to VTK grid
ac = vtk.vtkDoubleArray()
ac.SetName(attr_name)
for iac in data.flatten(order='F'):
ac.InsertNextTuple1(iac)
self.Grid.GetCellData().AddArray(ac)
return data
def read_outputs(self, fname, prop_strings, toVTK=True, toNumpy=True):
"""
Reads per-cell properties from .PRT file for all timesteps
Pack property keywords to read from .PRT into list of lists
This saves significant time for large grids as only one pass is required through .PRT file
Inner lists should contain keywords that enable line denoting property section to be uniquely identified
:param prop_strings: [[ECL prop keyword, subkey1, subkey2, ...], ...]
Order props as they appear in .PRT file
"""
print('Reading output properties\n')
prop = {}
prop_idx = 0
for p in prop_strings:
prop[p[0]] = {}
with open(fname, "r") as fp:
t = 0
II = []
build = False
data = np.zeros(self.ne * self.nn * self.nz)
for line in fp:
# Find prop keywords
if not build:
if all(e in line for e in prop_strings[prop_idx]):
data = np.zeros(self.ne * self.nn * self.nz)
# print('Reading output property: ' + prop_strings[prop_idx][0])
# print('t = ' + str(t))
build = True
# Read prop data
else:
item = line.split()
if len(item) > 0:
if 'I=' in line:
II = line.split('I=')[1].split()
II = list(map(int, II))
elif '(*,' in item[0]:
idxs = line.split('(')[1].split(')')[0].replace(',', ' ').split()
J = int(idxs[1])
K = int(idxs[2])
vals = line.split(')')[1].split()
for c,I in enumerate(II):
if '-' in vals[c]:
vals[c] = 0
idx = ((self.ne * self.nn) * (K - 1)) + (self.ne * (J - 1)) + (I - 1)
data[idx] = vals[c]
elif '--' in item[0]:
build = False
pname = prop_strings[prop_idx][0]
prop[pname] = copy.deepcopy(data)
if prop_idx < len(prop_strings) - 1:
prop_idx += 1
# All properties for current t have been read
else:
print('Exporting grid for t = ' + str(t))
ids = []
for pn in prop.keys():
data = prop[pn]
if toNumpy:
if t == 0:
self._check_out(pn)
grid_data = np.reshape(data, (self.ne, self.nn, self.nz), order="F")
np.savez_compressed(os.path.join(self.out_dir, pn, pn + '_' + str(t)), grid_data)
if toVTK:
if t == 0:
self._check_out('vtk')
ac = vtk.vtkDoubleArray()
ac.SetName(pn)
for iac in data:
ac.InsertNextTuple1(iac)
id = self.Grid.GetCellData().AddArray(ac)
ids.append(id)
if toVTK:
self.exportVTK(os.path.join(self.out_dir, 'vtk', os.path.basename(os.path.splitext(fname_out)[0], str(t))))
for id in ids:
self.Grid.GetCellData().RemoveArray(id)
prop_idx = 0
t += 1
def readWellOutput(self, fname, keys):
wellOutput = {}
keyOrder = {}
readNames = False
build = False
skip = 0
for key in keys:
wellOutput[key] = {}
with open(fname, "r") as fp:
for line in fp:
item = line.split()
if len(item) > 0:
# read time series values
if build:
# I don't know why '1' denotes timestep end in .RSM file
if item[0] == '1':
build = False
continue
t = item[0]
for idx in keyOrder.keys():
if t in wellOutput[keyOrder[idx][0]]:
wellOutput[keyOrder[idx][0]][t][keyOrder[idx][1]] = float(item[idx])
else:
if len(keyOrder[idx]) > 1:
wellOutput[keyOrder[idx][0]][t] = {}
wellOutput[keyOrder[idx][0]][t][keyOrder[idx][1]] = float(item[idx])
else:
wellOutput[keyOrder[idx][0]][t] = float(item[idx])
continue
# get names of wells
if readNames:
for idx in keyOrder.keys():
curr = keyOrder[idx]
if keyOrder[idx][0][0] == 'W':
keyOrder[idx].append(item[idx - skip])
next(fp)
next(fp)
readNames = False
build = True
skip = 0
continue
# find line that contains keys
if item[0] == 'TIME':
keyOrder = {}
# if time found, then keys might be on this same line
for j,key in enumerate(keys):
for i,var in enumerate(item):
if key == var:
if i in keyOrder:
keyOrder[i].append(key)
else:
keyOrder[i] = [key]
if j == 0 and var[0] != 'W':
# then it is time related or a field variable
skip += 1
if len(keyOrder.keys()) > 0:
next(fp)
readNames = True
return wellOutput
# Exports Numpy array of property (can be wells)
# TODO: inherit from FlowGrid
def export_prop(self, title, prop):
if not os.path.exists(self.out_dir):
os.mkdir(self.out_dir)
np.savez_compressed(os.path.join(self.out_dir, title), prop)
class SUTRA(FlowGrid):
""" SUTRA is a USGS flow modelling code.
"""
def __init__(self):
super(SUTRA, self).__init__()
nx, ny, nz = 0, 0, 0
def loadNodes(self, fname, nx, ny, nz, ve=-1):
""" Reads in the points of the grid, ususally in a file called nodewise
fname = nodes file
nx = number of cells in the easting(x) direction
ny = number of cells in the northing (y) direction
nz = number of cells in depth, positive up
ve = vertical exaggeration, default is 1 (none)
This method results in the generation of a VtkStructuredGrid
"""
self.nx = nx
self.ny = ny
self.nz = nz
self.ActiveCells = np.ones((self.nx * self.ny * self.nz), dtype=int)
X = np.loadtxt(fname, comments="#")
self.points = np.reshape(np.array((X[:, 2], X[:, 3], X[:, 4])).T, (nx, ny, nz, 3))
# work directly with VTK structures
self.GridType = "vtkStructuredGrid"
self.Grid = vtk.vtkStructuredGrid()
self.Grid.SetDimensions(nx, ny, nz)
vtk_points = vtk.vtkPoints()
for iz in range(nz):
for iy in range(ny):
for ix in range(nx):
vtk_points.InsertNextPoint(self.points[ix, iy, iz][0], \
self.points[ix, iy, iz][1], \
ve * self.points[ix, iy, iz][2])
self.Grid.SetPoints(vtk_points)
def loadNodesConnections(self, nodes, connections):
""" In contrast to the above method, the points and connections can be loaded instead.
For non-regular grids this is necessary. This method results in the generation
of a vtkUnstructuredGrid.
nodes = node file, often called nodewise
connections = element connections, often called incident
"""
X = np.loadtxt(nodes, comments="#")
# x y z
points = np.array((X[:, 2], X[:, 3], X[:, 4])).T
self.GridType = "vtkUnstructuredGrid"
self.Grid = vtk.vtkUnstructuredGrid()
vtk_points = vtk.vtkPoints()
for point in range(np.shape(points)[0]):
vtk_points.InsertNextPoint(points[point, 0], points[point, 1], points[point, 2])
self.Grid.SetPoints(vtk_points)
# Read in the connections, the format is as follows
# nodeid p0, p1, p2, p3, p4, p5, p6, p7, p8
C = np.loadtxt(connections, comments="#", skiprows=2, dtype=int)
for line in range(np.shape(C)[0]):
idList = vtk.vtkIdList()
for node in C[line, :][1:]:
idList.InsertNextId(node - 1)
self.Grid.InsertNextCell(vtk.VTK_HEXAHEDRON, idList)
def readPermeability(self, fname, label=("$\kappa_x$", "$\kappa_y$", "$\kappa_z$")):
""" Reads in SUTRA permeability data
"""
k = np.loadtxt(fname, comments="#")