forked from yohanesnuwara/PyTOUGH
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulgrids.py
executable file
·4225 lines (3939 loc) · 196 KB
/
mulgrids.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
"""For reading, writing and manipulating MULgraph geometry grids.
Copyright 2011 University of Auckland.
This file is part of PyTOUGH.
PyTOUGH is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
PyTOUGH 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with PyTOUGH. If not, see <http://www.gnu.org/licenses/>."""
from __future__ import print_function
import sys
from string import ascii_lowercase, ascii_uppercase
from geometry import *
from fixed_format_file import *
def padstring(s, length = 80): return s.ljust(length)
def int_to_chars(i, st = '', chars = ascii_lowercase,
spaces = True, length = 0):
"""Converts a number into a string of characters, using the specified
characters. If spaces is False, no spaces are used in the name,
and it is padded out with the first character in chars to the
specified length."""
def pad_to_length(st):
return ''.join([chars[0] * (length - len(st)), st])
if i > 0:
n = len(chars)
char_index = i - 1 if spaces else i
st = int_to_chars(char_index // n,
''.join([chars[char_index % n], st]),
chars, spaces, length = 0)
return pad_to_length(st) if length and not spaces else st
def new_dict_key(d, istart = 0, justfn = str.rjust, length = 5,
chars = ascii_lowercase, spaces = True):
"""Returns an unused key for dictionary d, using the specified
characters, plus the corresponding next starting index."""
i = istart
used = True
while used:
i += 1
name = justfn(int_to_chars(i, chars = chars,
spaces = spaces,
length = length),
length)
used = name in d
return name, i
def uniqstring(s): return ''.join(sorted(set(s), key = s.index))
def fix_blockname(name):
"""Fixes blanks in 4th column of block names, caused by TOUGH2
treating names as (a3, i2)"""
if name[2].isdigit() and name[4].isdigit() and name[3] == ' ':
return '0'.join((name[0:3], name[4:5]))
else: return name
def unfix_blockname(name):
"""The inverse of fix_blockname()."""
return "%3s%2d" % (name[0:3], int(name[3:5]))
def fix_block_mapping(blockmap):
"""Fixes block names in specified block mapping."""
keys_to_fix = {}
for k, v in blockmap.items():
fixedk = fix_blockname(k)
if k != fixedk: keys_to_fix[k] = fixedk
blockmap[k] = fix_blockname(v)
for k,v in keys_to_fix.items():
item = blockmap[k]
del blockmap[k]
blockmap[v] = item
def valid_blockname(name):
"""Tests if a 5-character string is a valid blockname. Allows names
with the first three characters either letters, numbers, spaces or
punctuation, the fourth character a digit or a space and the last
character a digit.
"""
from string import ascii_letters, digits, punctuation
digit_space = digits + ' '
letter_digit_space_punct = ascii_letters + digit_space + punctuation
return all([s in letter_digit_space_punct for s in name[0:3]]) and \
(name[3] in digit_space) and (name[4] in digits)
class NamingConventionError(Exception):
"""Used to raise exceptions when grid naming convention is not
respected- e.g. when column or layer names are too long.
"""
pass
class quadtree(object):
"""Quadtree for spatial searching in 2D grids."""
def __init__(self, bounds, elements, parent = None):
self.parent = parent
self.bounds = bounds
self.elements = elements
self.child = []
if self.parent:
self.generation = self.parent.generation + 1
self.all_elements = self.parent.all_elements
else:
self.generation = 0
self.all_elements = set(elements)
if self.num_elements > 1:
rects = sub_rectangles(self.bounds)
rect_elements = [[], [], [], []]
for elt in self.elements:
for irect, rect in enumerate(rects):
if in_rectangle(elt.centre, rect):
rect_elements[irect].append(elt)
break
for rect, elts in zip(rects, rect_elements):
if len(elts) > 0: self.child.append(quadtree(rect, elts, self))
def __repr__(self): return self.bounds.__repr__()
def get_num_elements(self): return len(self.elements)
num_elements = property(get_num_elements)
def get_num_children(self): return len(self.child)
num_children = property(get_num_children)
def search_wave(self, pos):
from copy import copy
todo = copy(self.elements)
done = []
while len(todo) > 0:
elt = todo.pop(0)
if elt.contains_point(pos): return elt
done.append(elt)
for nbr in elt.neighbour & self.all_elements:
if rectangles_intersect(nbr.bounding_box, self.bounds) and \
not ((nbr in done) or (nbr in todo)):
todo.append(nbr)
return None
def search(self, pos):
leaf = self.leaf(pos)
if leaf: return leaf.search_wave(pos)
else: return None
def leaf(self, pos):
if in_rectangle(pos, self.bounds):
for child in self.child:
childleaf = child.leaf(pos)
if childleaf: return childleaf
return self
else: return None
def plot(self, plt = None):
if plt is None: import matplotlib.pyplot as plt
x = [self.bounds[0][0], self.bounds[1][0], self.bounds[1][0],
self.bounds[0][0], self.bounds[0][0]]
y = [self.bounds[0][1], self.bounds[0][1], self.bounds[1][1],
self.bounds[1][1], self.bounds[0][1]]
plt.plot(x, y, '.--')
for child in self.child: child.plot(plt)
mulgrid_format_specification = {
'header': [['type', '_convention', '_atmosphere_type',
'atmosphere_volume', 'atmosphere_connection',
'unit_type', 'gdcx', 'gdcy', 'cntype',
'permeability_angle', '_block_order_int'],
['5s', '1d', '1d',
'10.2e', '10.2e',
'5s', '10.2f', '10.2f', '1d', '10.2f', '2d']],
'node': [['name', 'x', 'y'], ['3s'] + ['10.2f'] * 2],
'column': [['name', 'centre_specified', 'num_nodes', 'xcentre', 'ycentre'],
['3s', '1d', '2d'] + ['10.2f'] * 2],
'column_node': [['name'], ['3s']],
'connection': [['name1', 'name2'], ['3s', '3s']],
'layer': [['name', 'bottom', 'centre'], ['3s'] + ['10.2f'] * 2],
'surface': [['name', 'elevation'], ['3s', '10.2f']],
'well': [['name', 'x', 'y', 'z'], ['5s'] + ['10.1f'] * 3]}
class node(object):
"""Grid node class"""
def __init__(self, name = ' ', pos = None):
if pos is None: pos = np.array([0.0, 0.0])
self.name = name
if isinstance(pos, (tuple, list)): pos = np.array(pos)
self.pos = pos
self.column = set([])
def __repr__(self): return self.name
class column(object):
"""Grid column class"""
def __init__(self, name = ' ', node = None, centre = None, surface = None):
if node is None: node = []
self.name = name
self.node = node
if centre is None:
self.centre_specified = 0
if self.num_nodes > 0: self.centre = self.centroid
else: self.centre = None
else:
self.centre_specified = 1
self.centre = centre
self.surface = surface
self.get_area()
if self.area < 0.: # check node numbering orientation
self.node.reverse()
self.area = -self.area
self.neighbour = set([])
self.connection = set([])
self.num_layers = 0
def get_num_nodes(self): return len(self.node)
num_nodes = property(get_num_nodes)
def get_num_neighbours(self): return len(self.neighbour)
num_neighbours = property(get_num_neighbours)
def get_surface(self): return self._surface
def set_surface(self, val):
self._surface = val
if val is None: self.default_surface = True
else: self.default_surface = False
surface = property(get_surface, set_surface)
def is_against(self, col):
"""Returns True if the column is against the specified other column-
that is, if it shares more than one node with it."""
return len(set(self.node).intersection(set(col.node))) > 1
def get_polygon(self):
"""Returns polygon formed by node positions."""
return [node.pos for node in self.node]
polygon = property(get_polygon)
def get_area(self):
"""Calculates column area"""
self.area = polygon_area(self.polygon)
def get_centroid(self):
"""Returns column centroid"""
return polygon_centroid(self.polygon)
centroid = property(get_centroid)
def get_bounding_box(self):
"""Returns (horizontal) bounding box of the column."""
return bounds_of_points([node.pos for node in self.node])
bounding_box = property(get_bounding_box)
def get_neighbourlist(self):
"""Returns a list of neighbouring columns corresponding to each column side (None if
the column side is on a boundary)."""
nbrlist = []
for i, nodei in enumerate(self.node):
i1 = (i + 1) % self.num_nodes
nodes = set([nodei, self.node[i1]])
con = [cn for cn in self.connection if set(cn.node) == nodes]
if con: col = [c for c in con[0].column if c != self][0]
else: col = None
nbrlist.append(col)
return nbrlist
neighbourlist = property(get_neighbourlist)
def near_point(self, pos):
"""Returns True if pos is within the bounding box of the column."""
return in_rectangle(pos, self.bounding_box)
def contains_point(self, pos):
"""Determines if specified point is inside the column."""
return in_polygon(pos, self.polygon)
def in_polygon(self, polygon):
"""Returns true if the centre of the column is inside the specified polygon."""
if len(polygon) == 2: return in_rectangle(self.centre, polygon) # for rectangles
else: return in_polygon(self.centre, polygon)
def get_exterior_angles(self):
"""Returns list of exterior angle for each node in the column."""
side = [self.node[i].pos - self.node[i - 1].pos for i in range(self.num_nodes)]
h = [vector_heading(s) for s in side]
angles = [np.pi - (h[(i + 1) % self.num_nodes] - h[i]) for i in range(self.num_nodes)]
angles = [a % (2 * np.pi) for a in angles]
return angles
exterior_angles = property(get_exterior_angles)
def get_interior_angles(self):
return [2. * np.pi - a for a in self.exterior_angles]
interior_angles = property(get_interior_angles)
def get_angle_ratio(self):
"""Returns the angle ratio for the column, defined as the ratio of the
largest interior angle to the smallest interior angle.
"""
angles = self.interior_angles
return max(angles) / min(angles)
angle_ratio = property(get_angle_ratio)
def get_side_lengths(self):
"Returns list of side lengths for the column"
return np.array([norm(self.node[(i + 1) % self.num_nodes].pos -
self.node[i].pos) for i in range(self.num_nodes)])
side_lengths = property(get_side_lengths)
def get_side_ratio(self):
"""Returns the side ratio for the column, defined as the ratio of the
largest side length to the smallest side length (a
generalisation of the aspect ratio for quadrilateral
columns).
"""
l = self.side_lengths
return np.max(l) / np.min(l)
side_ratio = property(get_side_ratio)
def bisection_sides(self, direction = None):
"""Returns indices of column sides which should be used to bisect the
column. If direction is specified as 'x' or 'y', the column
in bisected across the sides most closely aligned with that
direction; otherwise, bisection is done for triangles across
the two longest sides of the column, and for quadrilaterals
across the longest side and its opposite.
"""
if direction is None:
l = self.side_lengths
isort = np.argsort(l)
if self.num_nodes == 3: return (isort[-1], isort[-2])
elif self.num_nodes == 4:
imax = isort[-1]
iopp = (imax + 2) % self.num_nodes
return (imax, iopp)
else: return None
else:
n = np.array([[1., 0.], [0., 1.]][direction == 'y'])
d, iside = [], []
nn = self.num_nodes
if nn in [3, 4]:
for i in range(nn):
x1 = 0.5 * (self.node[i].pos + self.node[(i + 1) % nn].pos)
if self.num_nodes == 3: i2 = (i + 1) % nn
else: i2 = (i + 2) % nn
x2 = 0.5 * (self.node[i2].pos + self.node[(i2 + 1) % nn].pos)
d.append(abs(np.dot(x2 - x1, n)))
iside.append((i, i2))
imax = np.argsort(d)
return iside[imax[-1]]
else: return None
def basis(self, xi):
"""Returns bilinear 2D finite element basis functions for the column
at the specified local coordinate."""
if self.num_nodes == 3: return np.array([xi[0], xi[1], 1. - xi[0] - xi[1]])
elif self.num_nodes == 4: # over [-1, 1]
a0, a1, b0, b1 = 1. - xi[0], 1. + xi[0], 1. - xi[1], 1. + xi[1]
return 0.25 * np.array([a0 * b0, a1 * b0, a1 * b1, a0 * b1])
else: return None
def basis_derivatives(self, xi):
"""Returns bilinear 2D finite element basis function derivatives for
the column at the specified local coordinate."""
if self.num_nodes == 3: return np.array([[1., 0.], [0., 1.], [-1., -1.]])
elif self.num_nodes == 4:
a0, a1, b0, b1 = 1. - xi[0], 1. + xi[0], 1. - xi[1], 1. + xi[1]
return 0.25 * np.array([[-b0, -a0], [b0, -a1], [b1, a1], [-b1, a0]])
else: return None
def Jacobian(self, xi):
"""Returns bilinear 2D finite element Jacobian matrix for the column
at the specified local coordinate."""
dpsi = self.basis_derivatives(xi)
J = np.zeros((2, 2))
for i in range(2):
for j in range(2):
for k, nodek in enumerate(self.node): J[i, j] += dpsi[k, j] * nodek.pos[i]
return J
def global_pos(self, xi):
"""Returns global coordinates of the local point xi in the column."""
psi = self.basis(xi)
return sum([psi[i] * nodei.pos for i, nodei in enumerate(self.node)])
def local_inside(self, xi):
"""Returns true if a local point is inside the column."""
if self.num_nodes == 3: return all([x >= 0. for x in xi]) and (np.sum(xi) <= 1.)
elif self.num_nodes == 4: return all([abs(x) <= 1. for x in xi])
else: return None
def local_pos(self, x):
"""Finds local coordinates of global point x in the column."""
if self.num_nodes in [3, 4]:
tolerance, max_iterations = 1.e-8, 15
if self.num_nodes == 3: xi = np.array([1 / 3., 1 / 3.])
else: xi = np.zeros(2)
found = False
for n in range(max_iterations): # Newton iteration
dx = self.global_pos(xi) - x
if np.linalg.norm(dx) <= tolerance:
found = True
break
else:
J = self.Jacobian(xi)
try:
xi -= np.linalg.solve(J, dx)
except np.linalg.LinAlgError: break
if not found: return None
else:
if self.local_inside(xi): return xi
else: return None
else: return None
def index_plus(self, i, d):
"""Adds d to index i around column."""
return (i + d) % self.num_nodes
def index_minus(self, i, d):
"""Subtracts d from index i around column."""
result = i - d
if result < 0: result += self.num_nodes
return result
def index_dist(self, i1, i2):
"""Returns distance between two integer indices around the column."""
d = abs(i1 - i2)
if 2 * d > self.num_nodes: d = self.num_nodes - d
return d
def __repr__(self): return self.name
class connection(object):
"""Column connection class"""
def __init__(self, col = None, nod = None):
if col is None: col = [column(), column()]
if nod is None: nod = [node(), node()]
self.column = col
self.node = nod
def __repr__(self): return self.column[0].name + ':' + self.column[1].name
def get_angle_cosine(self):
"""Returns cosine of angle between the connection face and the line
joining the two columns in the connection. Ideally want this
to be zero, i.e. connecting line perpendicular to the face.
"""
n = self.node[1].pos - self.node[0].pos
n = n / norm(n)
dcol = self.column[1].centre - self.column[0].centre
d = dcol / norm(dcol)
return np.dot(n, d)
angle_cosine = property(get_angle_cosine)
class layer(object):
"""Grid layer class"""
def __init__(self, name = ' ', bottom = 0.0, centre = 0.0, top = 0.0):
self.name = name
self.bottom = bottom
self.centre = centre
self.top = top
def __repr__(self):
return self.name + '(' + str(self.bottom) + ':' + str(self.top) + ')'
def contains_elevation(self, z):
return self.bottom <= z <= self.top
def translate(self, shift):
"""Translates a layer up or down by specified distance"""
self.top += shift
self.bottom += shift
self.centre += shift
def get_thickness(self): return self.top - self.bottom
thickness = property(get_thickness)
class well(object):
"""Well class"""
def __init__(self, name = ' ', pos = None):
if pos is None: pos = []
self.name = name
for i, p in enumerate(pos):
if isinstance(p, (list, tuple)): pos[i] = np.array(p)
self.pos = pos
def __repr__(self): return self.name
def get_num_pos(self): return len(self.pos)
num_pos = property(get_num_pos)
def get_num_deviations(self): return self.num_pos - 1
num_deviations = property(get_num_deviations)
def get_deviated(self): return self.num_deviations > 1
deviated = property(get_deviated)
def get_head(self): return self.pos[0]
head = property(get_head)
def get_bottom(self): return self.pos[-1]
bottom = property(get_bottom)
def pos_coordinate(self, index):
"""Returns array of specified coordinate in pos array."""
return np.array([pos[index] for pos in self.pos])
def get_pos_depth(self):
"""Returns array of downhole depths corresponding to pos array."""
return np.cumsum([0.] + [np.linalg.norm(pos - self.pos[i]) for
i, pos in enumerate(self.pos[1:])])
pos_depth = property(get_pos_depth)
def elevation_depth(self, elevation):
"""Returns downhole depth corresponding to a given elevation (or None
if the specified elevation is outside the well).
"""
epos = self.pos_coordinate(2)
# NB: np.interp() needs abcissa to be increasing, so have to
# reverse the arrays here:
if epos[-1] <= elevation <= epos[0]:
return np.interp(elevation, epos[::-1], self.pos_depth[::-1])
else: return None
def depth_elevation(self, depth):
"""Returns elevation corresponding to a given downhole depth (or None if the specified
depth is outside the well)."""
dpos = self.pos_depth
if dpos[0] <= depth <= dpos[-1]:
return np.interp(depth, dpos, self.pos_coordinate(2))
else: return None
def elevation_pos(self, elevation, extend = False):
"""Returns 3D position in well, given an elevation. If extend is
True, return extrapolated positions for elevations below the
bottom of the well.
"""
poscoord = [self.pos_coordinate(i) for i in range(3)]
epos = poscoord[2]
if epos[-1] <= elevation <= epos[0]:
return np.array([np.interp(elevation, epos[::-1],
poscoord[i][::-1]) for i in range(3)])
elif elevation < epos[-1] and extend:
# extrapolate last deviation:
pbot = self.pos[-1]
if self.num_pos > 1: ptop = self.pos[-2]
else: ptop = np.array(list(pbot[0:2]) + [pbot[2] + 1.])
ebot, etop = pbot[2], ptop[2]
alpha = (elevation - ebot) / (etop - ebot)
return (1. - alpha) * pbot + alpha * ptop
else: return None
def depth_pos(self, depth):
"""Returns 3D position in well, given a depth."""
elevation = self.depth_elevation(depth)
if elevation: return self.elevation_pos(elevation)
else: return None
class mulgrid(object):
"""MULgraph grid class"""
def __init__(self, filename = '', type = 'GENER', convention = 0,
atmos_type = 0, atmos_volume = 1.e25,
atmos_connection = 1.e-6, unit_type = '', permeability_angle = 0.0,
read_function = default_read_function,
block_order = None):
self.filename = filename
self.type = type # geometry type- only GENER supported
self._convention = convention # naming convention:
# 0: 3-char column + 2-digit layer
# 1: 3-char layer + 2-digit column
# 2: 2-char layer + 3-digit column
self._atmosphere_type = atmos_type # atmosphere type:
# 0: single atmosphere block
# 1: one atmosphere block per column
# else: no atmosphere blocks
self.set_secondary_variables()
self.atmosphere_volume = atmos_volume
self.atmosphere_connection = atmos_connection
self.unit_type = unit_type
self.gdcx, self.gdcy = None, None
self.cntype = None # not supported
self.permeability_angle = permeability_angle
self._block_order = None
self._block_order_int = None
self.read_function = read_function
self.empty()
if self.filename: self.read(filename)
if block_order is not None: self.block_order = block_order.lower()
def set_secondary_variables(self):
"""Sets variables dependent on naming convention and atmosphere type"""
if self.atmosphere_type == 0:
self.atmosphere_column_name = ['ATM', ' 0', ' 0'][self.convention]
self.colname_length = [3, 2, 3][self.convention]
self.layername_length = [2, 3, 2][self.convention]
def get_convention(self):
"""Get naming convention"""
return self._convention
def set_convention(self, convention):
"""Set naming convention"""
self._convention = convention
self.set_secondary_variables()
self.setup_block_name_index()
self.setup_block_connection_name_index()
convention = property(get_convention, set_convention)
def get_atmosphere_type(self):
"""Get atmosphere type"""
return self._atmosphere_type
def set_atmosphere_type(self, atmos_type):
"""Set atmosphere type"""
self._atmosphere_type = atmos_type
self.set_secondary_variables()
self.setup_block_name_index()
self.setup_block_connection_name_index()
atmosphere_type = property(get_atmosphere_type, set_atmosphere_type)
def get_unit_type(self):
"""Get unit type"""
return self._unit_type
def set_unit_type(self, unit_type):
"""Set unit type"""
self._unit_type = unit_type
self.unit_scale = {'': 1.0, 'FEET ': 0.3048}[unit_type]
unit_type = property(get_unit_type, set_unit_type)
def set_block_order_int(self):
"""Sets block order integer flag, for input/output."""
block_order_ints = {'layer_column': 0, 'dmplex': 1}
if self.block_order in block_order_ints:
self._block_order_int = block_order_ints[self.block_order]
elif self.block_order is None:
self._block_order_int = None
else:
raise Exception('Unrecognised block ordering: %s' % self.block_order)
def get_block_order(self):
"""Get block ordering scheme"""
return self._block_order
def set_block_order(self, block_order):
"""Set block ordering scheme"""
self._block_order = block_order
self.set_block_order_int()
self.setup_block_name_index()
block_order = property(get_block_order, set_block_order)
def get_area(self):
"""Grid area- sum of column areas"""
return sum([col.area for col in self.columnlist])
area = property(get_area)
def get_centre(self):
"""Returns grid centre- approximated as area-weighted average of column centres"""
if self.num_columns > 0:
return sum([col.area * col.centre for col in self.columnlist]) / self.area
else: return None
centre = property(get_centre)
def get_num_blocks(self):
"""Returns number of blocks in the tough2 grid represented by the geometry."""
return len(self.block_name_list)
num_blocks = property(get_num_blocks)
def get_num_atmosphere_blocks(self):
"""Returns number of atmosphere blocks in the tough2 grid represented by the geometry."""
return [1, self.num_columns, 0][self.atmosphere_type]
num_atmosphere_blocks = property(get_num_atmosphere_blocks)
def get_num_underground_blocks(self):
"""Returns number of blocks under the ground surface
(i.e. non-atmosphere blocks) in the tough2 grid represented by
the geometry.
"""
return self.num_blocks - self.num_atmosphere_blocks
num_underground_blocks = property(get_num_underground_blocks)
def get_num_block_connections(self):
"""Returns number of connections between blocks in the TOUGH2 grid
represented by the geometry."""
return len(self.block_connection_name_list)
num_block_connections = property(get_num_block_connections)
def get_column_angle_ratio(self):
"""Returns an array of angle ratios for each column."""
return np.array([col.angle_ratio for col in self.columnlist])
column_angle_ratio = property(get_column_angle_ratio)
def get_column_side_ratio(self):
"""Returns an array of side ratios for each column."""
return np.array([col.side_ratio for col in self.columnlist])
column_side_ratio = property(get_column_side_ratio)
def get_connection_angle_cosine(self):
"""Returns an array of connection angle cosines, for each connection."""
return np.array([con.angle_cosine for con in self.connectionlist])
connection_angle_cosine = property(get_connection_angle_cosine)
def get_tilt_vector(self):
"""Returns a tilt vector, used to calculate gravity cosines of TOUGH2
grid connections when the GDCX or GDCY grid tilting options
are used.
"""
from math import sqrt
gdcx = 0. if self.gdcx is None else self.gdcx
gdcy = 0. if self.gdcy is None else self.gdcy
def cosfromsin(sinangle): return sqrt(1. - min(sinangle * sinangle, 1.))
sintheta = -gdcy
costheta = cosfromsin(sintheta)
try:
sinphi = gdcx / costheta
cosphi = cosfromsin(sinphi)
return np.array([costheta * sinphi, -sintheta, -costheta * cosphi])
except ZeroDivisionError: return np.array([0., -sintheta, 0.]) # theta = pi/2
tilt_vector = property(get_tilt_vector)
def empty(self):
"""Empties grid contents."""
self.nodelist = []
self.columnlist = []
self.layerlist = []
self.connectionlist = []
self.welllist = []
self.node = {}
self.column = {}
self.layer = {}
self.connection = {}
self.well = {}
self.block_name_list = []
self.block_name_index = {}
self.block_connection_name_list = []
self.block_connection_name_index = {}
def __repr__(self):
conventionstr = [
'3 characters for column, 2 digits for layer',
'3 characters for layer, 2 digits for column',
'2 characters for layer, 3 digits for column'][self.convention]
atmstr = [
'single atmosphere block',
'one atmosphere block over each column',
'no atmosphere blocks'][self.atmosphere_type]
return str(self.num_nodes) + ' nodes; ' + \
str(self.num_columns) + ' columns; ' + \
str(self.num_layers) + ' layers; ' + \
str(self.num_blocks) + ' blocks; ' + \
str(self.num_wells) + ' wells' + '\n' + \
'Naming convention: ' + str(self.convention) + \
' (' + conventionstr + ')\n' + \
'Atmosphere type : ' + str(self.atmosphere_type) + \
' (' + atmstr + ')'
def get_default_surface(self):
return all([col.default_surface for col in self.columnlist])
default_surface = property(get_default_surface)
def get_num_nodes(self):
return len(self.node)
num_nodes = property(get_num_nodes)
def get_num_columns(self):
return len(self.column)
num_columns = property(get_num_columns)
def get_num_layers(self):
return len(self.layer)
num_layers = property(get_num_layers)
def get_num_connections(self):
return len(self.connectionlist)
num_connections = property(get_num_connections)
def get_num_wells(self):
return len(self.well)
num_wells = property(get_num_wells)
def get_layer_index(self):
return dict([(lay.name, i) for i, lay in enumerate(self.layerlist)])
layer_index = property(get_layer_index)
def get_column_index(self):
return dict([(col.name, i) for i, col in enumerate(self.columnlist)])
column_index = property(get_column_index)
def connects(self, col1, col2):
"""Returns True if the geometry contains a connection connecting the
two specified columns."""
return any([(col1 in con.column) and (col2 in con.column) for
con in self.connectionlist])
def setup_block_name_index(self):
"""Sets up list and dictionary of block names and indices for the
tough2 grid represented by the geometry."""
self.block_name_list = []
if self.num_layers > 0:
if self.atmosphere_type == 0: # one atmosphere block
self.block_name_list.append(
self.block_name(self.layerlist[0].name, self.atmosphere_column_name))
elif self.atmosphere_type == 1: # one atmosphere block per column
for col in self.columnlist:
self.block_name_list.append(
self.block_name(self.layerlist[0].name, col.name))
if self.block_order is None or self.block_order == 'layer_column':
self.block_name_list += self.block_name_list_layer_column()
elif self.block_order == 'dmplex':
self.block_name_list += self.block_name_list_dmplex()
else:
raise Exception('Unrecognised mulgrid block order: %s' % self.block_order)
self.block_name_index = dict([(blk, i) for i, blk in enumerate(self.block_name_list)])
def block_name_list_layer_column(self):
"""Returns list of underground (i.e. non-atmosphere) block names,
sorted by layers and then columns."""
names = []
for lay in self.layerlist[1:]:
for col in [col for col in self.columnlist if col.surface > lay.bottom]:
blkname = self.block_name(lay.name, col.name)
names.append(blkname)
return names
def block_name_list_dmplex(self):
"""Returns list of underground (i.e. non-atmosphere) block names, in
PETSc DMPlex order. These are sorted first by cell type
(hexahedrons followed by wedges), then by layers and
columns. It may be used e.g. for exporting a model to
Waiwera."""
blocknames = {6: [], 8: []}
for lay in self.layerlist[1:]:
for col in [col for col in self.columnlist if col.surface > lay.bottom]:
blkname = self.block_name(lay.name, col.name)
num_block_nodes = 2 * col.num_nodes
try:
blocknames[num_block_nodes].append(blkname)
except KeyError:
raise Exception('Blocks with %d nodes not supported by DMPlex ordering' %
num_block_nodes)
return blocknames[8] + blocknames[6]
def setup_block_connection_name_index(self):
"""Sets up list and dictionary of connection names and indices for
blocks in the TOUGH2 grid represented by the geometry."""
self.block_connection_name_list = []
for ilay, lay in enumerate(self.layerlist[1:]):
layercols = [col for col in self.columnlist if col.surface > lay.bottom]
for col in layercols: # vertical connections
thisblkname = self.block_name(lay.name, col.name)
if (ilay == 0) or (col.surface <= lay.top): # connection to atmosphere
abovelayer = self.layerlist[0]
if self.atmosphere_type == 0:
aboveblkname = self.block_name_list[0]
elif self.atmosphere_type == 1:
aboveblkname = self.block_name(abovelayer.name, col.name)
else: continue
else:
abovelayer = self.layerlist[ilay]
aboveblkname = self.block_name(abovelayer.name, col.name)
self.block_connection_name_list.append((thisblkname, aboveblkname))
layercolset = set(layercols) # horizontal connections:
cons = [con for con in self.connectionlist if
set(con.column).issubset(layercolset)]
for con in cons:
conblocknames = tuple([self.block_name(lay.name, concol.name) for
concol in con.column])
self.block_connection_name_list.append(conblocknames)
self.block_connection_name_index = dict(
[(con, i) for i, con in enumerate(self.block_connection_name_list)])
def column_name(self, blockname):
"""Returns column name of block name."""
if self.convention == 0: return blockname[0: 3]
elif self.convention == 1: return blockname[3: 5]
elif self.convention == 2: return blockname[2: 5]
else: return None
def layer_name(self, blockname):
"""Returns layer name of block name."""
if self.convention == 0: return blockname[3: 5]
elif self.convention == 1: return blockname[0: 3]
elif self.convention == 2: return blockname[0: 2]
else: return None
def node_col_name_from_number(self, num, justfn = str.rjust,
chars = ascii_lowercase, spaces = True):
"""Returns node or column name from number."""
if self.convention == 0:
name = justfn(int_to_chars(num, chars = chars, spaces = spaces,
length = self.colname_length), self.colname_length)
else: name = str.rjust(str(num), self.colname_length)
return name
def column_name_from_number(self, num, justfn = str.rjust,
chars = ascii_lowercase, spaces = True):
"""Returns column name from column number."""
name = self.node_col_name_from_number(num, justfn, chars, spaces)
if len(name) > self.colname_length:
raise NamingConventionError(
"Column name is too long for the grid naming convention.")
return name
def node_name_from_number(self, num, justfn = str.rjust,
chars = ascii_lowercase, spaces = True):
"""Returns node name from node number."""
name = self.node_col_name_from_number(num, justfn, chars, spaces)
if len(name) > self.colname_length:
raise NamingConventionError(
"Node name is too long for the grid naming convention.")
return name
def layer_name_from_number(self, num, justfn = str.rjust, chars = ascii_lowercase,
spaces = True):
"""Returns layer name from layer number."""
if self.convention == 0:
name = justfn(str(num), self.layername_length)
else:
name = justfn(int_to_chars(num, chars = chars, spaces = spaces,
length = self.layername_length),
self.layername_length)
if len(name) > self.layername_length:
raise NamingConventionError(
"Layer name is too long for the grid naming convention.")
return name
def get_uppercase_names(self):
"""Returns True if character part of block names are uppercase."""
return all([(blkname[0:3] == blkname[0:3].upper()) for
blkname in self.block_name_list])
uppercase_names = property(get_uppercase_names)
def get_right_justified_names(self):
"""Returns True if character part of block names are right-justified."""
return all([(blkname[0:3] == blkname[0:3].rjust(3)) for
blkname in self.block_name_list])
right_justified_names = property(get_right_justified_names)
def new_node_name(self, istart = 0, justfn = str.rjust, chars = ascii_lowercase,
spaces = True):
name, i = new_dict_key(self.node, istart, justfn, self.colname_length,
chars, spaces)
if len(name) > self.colname_length:
raise NamingConventionError(
"Node name is too long for the grid naming convention.")
else: return name, i
def new_column_name(self, istart = 0, justfn = str.rjust,
chars = ascii_lowercase, spaces = True):
name, i = new_dict_key(self.column, istart, justfn, self.colname_length,
chars, spaces)
if len(name) > self.colname_length:
raise NamingConventionError(
"Column name is too long for the grid naming convention.")
else: return name, i
def column_bounds(self, columns):
"""Returns horizontal bounding box for a list of columns."""
nodes = self.nodes_in_columns(columns)
return bounds_of_points([node.pos for node in nodes])
def get_bounds(self):
"""Returns horizontal bounding box for grid."""
return bounds_of_points([node.pos for node in self.nodelist])
bounds = property(get_bounds)
def add_node(self, nod = None):
"""Adds node to the geometry. If a node with the specified name
already exists in the geometry, no new node is added."""
if nod is None: nod = node()
if nod.name not in self.node:
self.nodelist.append(nod)
self.node[nod.name] = self.nodelist[-1]
def delete_node(self, nodename):
"""Deletes node from the geometry."""
node = self.node[nodename]
del self.node[nodename]
self.nodelist.remove(node)
def add_column(self, col = None):
"""Adds column to the geometry. If a column with the specified
name already exists in the geometry, no new column is added."""
if col is None: col = column()
if col.name not in self.column:
self.columnlist.append(col)
self.column[col.name] = self.columnlist[-1]
for node in col.node: node.column.add(col)
def delete_column(self, colname):
"""Deletes a column from the geometry."""
col = self.column[colname]
cons = [con for con in self.connectionlist if col in con.column]
for con in cons:
self.delete_connection(tuple([c.name for c in con.column]))
for nbr in col.neighbour: nbr.neighbour.remove(col)
for node in col.node: node.column.remove(col)
del self.column[colname]
self.columnlist.remove(col)
def split_column(self, colname, nodename, chars = ascii_lowercase):
"""Splits the specified quadrilateral column into two triangles,
splitting at the specified node. Returns True if the
operation was successful.
"""
chars = uniqstring(chars)
justfn = [str.ljust, str.rjust][self.right_justified_names]