-
Notifications
You must be signed in to change notification settings - Fork 1
/
output.py
2391 lines (1904 loc) · 101 KB
/
output.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
'''Noddy output file analysis
Created on 24/03/2014
@author: Florian Wellmann, Sam Thiele
'''
import os
import numpy as np
from scipy.interpolate import interpn
import pynoddy
class NoddyOutput(object):
"""Class definition for Noddy output analysis"""
def __init__(self, output_name):
"""Noddy output analysis
**Arguments**:
- *output_name* = string : (base) name of Noddy output files
"""
self.basename = output_name
self.load_model_info()
self.load_geology()
def __add__(self, other):
"""Define addition as addition of grid block values
Note: Check first if model dimensions and settings are the same
"""
# check dimensions
self.compare_dimensions_to(other)
# 1. create copy
import copy
tmp_his = copy.deepcopy(self)
# 2. perform operation
tmp_his.block = self.block + other.block
return tmp_his
def __sub__(self, other):
"""Define subtraction as subtraction of grid block values
Note: Check first if model dimensions and settings are the same
"""
# check dimensions
self.compare_dimensions_to(other)
# 1. create copy
import copy
tmp_his = copy.deepcopy(self)
# 2. perform operation
tmp_his.block = self.block - other.block
return tmp_his
def __iadd__(self, x):
"""Augmented assignment addtition: add value to all grid blocks
**Arguments**:
- *x*: can be either a numerical value (int, float, ...) *or* another
NoddyOutput object! Note that, in both cases, the own block is updated
and no new object is created (compare to overwritten addition operator!)
Note: This method is changing the object *in place*!
"""
# if x is another pynoddy output object, then add values to own grid in place!
if isinstance(x, NoddyOutput):
self.block += x.block
else:
self.block += x
# update grid values
return self
def __isub__(self, x):
"""Augmented assignment addtition: add value(s) to all grid blocks
**Arguments**:
- *x*: can be either a numerical value (int, float, ...) *or* another
NoddyOutput object! Note that, in both cases, the own block is updated
and no new object is created (compare to overwritten addition operator!)
Note: This method is changing the object *in place*!
"""
# if x is another pynoddy output object, then add values to own grid in place!
if isinstance(x, NoddyOutput):
self.block -= x.block
else:
self.block -= x
# update grid values
return self
def set_basename(self, name):
"""Set model basename"""
self.basename = name
def compare_dimensions_to(self, other):
"""Compare model dimensions to another model"""
try:
assert((self.nx, self.ny, self.nz) == (other.nx, other.ny, other.nz))
except AssertionError:
raise AssertionError("Model dimensions do not seem to agree, please check!\n")
try:
assert((self.delx, self.dely, self.delz) == (other.delx, other.dely, other.delz))
except AssertionError:
raise AssertionError("Model dimensions do not seem to agree, please check!\n")
try:
assert((self.xmin, self.ymin, self.zmin) == (other.xmin, other.ymin, other.zmin))
except AssertionError:
raise AssertionError("Model dimensions do not seem to agree, please check!\n")
def load_model_info(self):
"""Load information about model discretisation from .g00 file"""
filelines = open(self.basename + ".g00").readlines()
for line in filelines:
if 'NUMBER OF LAYERS' in line:
self.nz = int(line.split("=")[1])
elif 'LAYER 1 DIMENSIONS' in line:
(self.nx, self.ny) = [int(l) for l in line.split("=")[1].split(" ")[1:]]
elif 'UPPER SW CORNER' in line:
l = [float(l) for l in line.split("=")[1].split(" ")[1:]]
(self.xmin, self.ymin, self.zmax) = l
elif 'LOWER NE CORNER' in line:
l = [float(l) for l in line.split("=")[1].split(" ")[1:]]
(self.xmax, self.ymax, self.zmin) = l
elif 'NUM ROCK' in line:
self.n_rocktypes = int(line.split('=')[1])
self.n_total = self.nx * self.ny * self.nz
(self.extent_x, self.extent_y, self.extent_z) = (self.xmax - self.xmin, self.ymax - self.ymin,
self.zmax - self.zmin)
(self.delx, self.dely, self.delz) = (self.extent_x / float(self.nx),
self.extent_y / float(self.ny),
self.extent_z / float(self.nz))
#load lithology colours & relative ages
if os.path.exists(self.basename + ".g20"):
filelines = open(self.basename + ".g20").readlines()
self.n_events = int(filelines[0].split(' ')[2]) #number of events
lithos = filelines[ 3 + self.n_events : len(filelines) - 1] #litho definitions
self.rock_ids = [] #list of litho ids. Will be a list from 1 to n
self.rock_names = [] #the (string) names of each rock type. Note that names including spaces will not be read properly.
self.rock_colors = [] #the colours of each rock type (in Noddy).
self.rock_events = [] #list of the events that created different lithologies
for l in lithos:
data = l.split(' ')
self.rock_ids.append(int(data[0]))
self.rock_events.append(int(data[1]))
self.rock_names.append(data[2])
self.rock_colors.append( (int(data[-3])/255., int(data[-2])/255., int(data[-1])/255.) )
#calculate stratigraphy
self.stratigraphy = [] #litho id's ordered by the age they were created in
for i in range(max(self.rock_events)+1): #loop through events
#create list of lithos created in this event
lithos = []
for n, e in enumerate(self.rock_events):
if e == i: #current event
lithos.append(self.rock_ids[n])
#reverse order... Noddy litho id's are ordered by event, but reverse ordered within depositional events (ie.
#lithologies created in younger events have larger ids, however the youngest unit created in a given event
#will have the smallest id...
for l in reversed(lithos):
self.stratigraphy.append(l)
def load_geology(self):
"""Load block geology ids from .g12 output file"""
f = open(self.basename + ".g12")
method = 'standard' # standard method to read file
# method = 'numpy' # using numpy should be faster - but it messes up the order... possible to fix?
if method == 'standard':
i = 0
j = 0
k = 0
self.block = np.ndarray((self.nx,self.ny,self.nz))
for line in f.readlines():
if line == '\n':
# next z-slice
k += 1
# reset x counter
i = 0
continue
l = [int(l1) for l1 in line.strip().split("\t")]
self.block[i,:,self.nz-k-1] = np.array(l)[::-1]
i += 1
elif method == 'standard_old':
j = 0
j_max = 0
k_max = 0
i_max = 0
self.block = np.ndarray((self.nz,self.ny,self.nx))
for k,line in enumerate(f.readlines()):
if line == '\n':
# next y-slice
j += 1
if j > j_max : j_max = j
continue
for i,l1 in enumerate(line.strip().split("\t")):
if i > i_max: i_max = i
if k/self.nz > k_max : k_max = k/self.nz
self.block[j,i,k/self.nz-1] = int(l1)
print((i_max, j_max, k_max))
elif method == 'numpy':
# old implementation - didn't work, but why?
self.block = np.loadtxt(f, dtype="int")
# reshape to proper 3-D shape
self.block = self.block.reshape((self.nz,self.ny,self.nx))
self.block = np.swapaxes(self.block, 0, 2)
# self.block = np.swapaxes(self.block, 0, 1)
# print np.shape(self.block)
def determine_unit_volumes(self):
"""Determine volumes of geological units in the discretized block model
"""
#
# Note: for the time being, the following implementation is extremely simple
# and could be optimised, for example to test specifically for units defined
# in stratigraphies, intrusions, etc.!
#
self.block_volume = self.delx * self.dely * self.delz
self.unit_ids = np.unique(self.block)
self.unit_volumes = np.empty(np.shape(self.unit_ids))
for i,unit_id in enumerate(self.unit_ids):
self.unit_volumes[i] = np.sum(self.block == unit_id) * self.block_volume
def get_surface_grid(self, lithoID, **kwds ):
'''
Returns a grid of lines that define a grid on the specified surface. Note that this cannot
handle layers that are repeated in the z direction...
**Arguments**:
- *lithoID* - the top surface of this lithology will be calculated. If a list is passed,
the top surface of each lithology in the list is calculated.
**Keywords**:
- *res* - the resolution to sample at. Default is 2 (ie. every second voxel is sampled).
**Returns**:
a tuple containing lists of tuples of x, y and z coordinate dictionaries and colour dictionaries,
one containing the east-west lines and one the north-south lines: ((x,y,z,c),(x,y,z,c)). THe dictionary
keys are the lithoID's passed in the lithoID parameter.
'''
import numpy.ma as ma
cube_size = self.xmax / self.nx
res = kwds.get('res',2)
if not type(lithoID) is list:
lithoID = [lithoID]
sx = {}
sy = {}
sz = {}
sc = {}
#get surface locations in x direction
for x in range(0,self.nx,res):
#start new line
for i in lithoID:
if i not in sx: #create list
sx[i] = []
sy[i] = []
sz[i] = []
if (hasattr(self,'rock_colors')):
sc[i] = self.rock_colors[i]
else:
sc[i] = i
sx[i].append([])
sy[i].append([])
sz[i].append([])
#fill in line
for y in range(0,self.ny,res):
#drill down filling surface info
found = []
for z in range(0,self.nz-1):
if (geo.block[x][y][z] != self.block[x][y][z+1]) and self.block[x][y][z] in lithoID:
key = self.block[x][y][z]
#add point
sx[key][-1].append(x * cube_size)
sy[key][-1].append(y * cube_size)
sz[key][-1].append(z * cube_size)
#remember that we've found this
found.append(key)
#check to see if anything has been missed(and hence we should start a new line segment)
for i in lithoID:
if not i in found:
sx[i].append([]) #new list
sy[i].append([])
sz[i].append([])
#apply mask
#for d in [sx,sy,sz]:
# for k in d.keys():
# d[key] = ma.masked_where(np.array(d[key]) == -1,d[key])
xlines = (sx,sy,sz,sc)
sx = {}
sy = {}
sz = {}
sc = {}
#get surface locations in y direction
for y in range(0,self.ny,res):
#start new line
for i in lithoID:
if i not in sx: #create list
sx[i] = []
sy[i] = []
sz[i] = []
if (hasattr(self,'rock_colors')):
sc[i] = self.rock_colors[i]
else:
sc[i] = i
sx[i].append([])
sy[i].append([])
sz[i].append([])
#fill in line
for x in range(0,self.nx,res):
#drill down filling surface info
found = []
for z in range(0,self.nz-1):
if (geo.block[x][y][z] != self.block[x][y][z+1]) and self.block[x][y][z] in lithoID:
key = self.block[x][y][z]
#add point
sx[key][-1].append(x * cube_size)
sy[key][-1].append(y * cube_size)
sz[key][-1].append(z * cube_size)
found.append(key)
for i in lithoID:
if not i in found: #line should end
sx[i].append([]) #add line end
sy[i].append([])
sz[i].append([])
ylines = (sx,sy,sz,sc)
return (xlines,ylines)
def get_section_lines(self, direction='y',position='center', **kwds):
"""Create and returns a list of lines representing a section block through the model
**Arguments**:
- *direction* = 'x', 'y', 'z' : coordinate direction of section plot (default: 'y')
- *position* = int or 'center' : cell position of section as integer value
or identifier (default: 'center')
**Returns**:
A tuple of lists of dictionaries.... ie:
( [ dictionary of x coordinates, with lithology pairs as keys, separated by an underscore],
[ dictionary of y coordinates, with lithology pairs as keys, separated by an underscore],
[ dictionary of z coordinates, with lithology pairs as keys, separated by an underscore],
[ dictionary of colours, with lithologies as keys])
For example: get_section_lines()[0]["1_2"] returns a list of all the x coordinates from the
contact between lithology 1 and lithology 2. Note that the smaller lithology index always
comes first in the code.
"""
#calc cube size
cube_size = self.delx
x = {}
y = {}
z = {}
c = {}
if 'z' in direction:
for i in range(0,self.nx):
for j in range(0,self.ny-1):
if self.block[i][j][0] != self.block[i][j+1][0]: #this is a contact
code = "%d_%d" % (min(self.block[i][j][0],self.block[i][j+1][0]),max(self.block[i][j][0],self.block[i][j+1][0]))
if code not in x:
x[code] = []
y[code] = []
z[code] = []
x[code].append(self.xmin +i * cube_size)
y[code].append(self.ymin +j * cube_size)
z[code].append(-1000)
if (hasattr(self,'rock_colors')):
c[code] = self.rock_colors[ int(self.block[i][j][0]) - 1]
else:
c[code] = int(self.block[i][j][0])
##xz
if 'y' in direction:
for i in range(0,self.nx):
for j in range(0,self.nz-1):
if self.block[i][0][j] != self.block[i][0][j+1]: #this is a contact
code = "%d_%d" % (min(self.block[i][0][j],self.block[i][0][j+1]),max(self.block[i][0][j],self.block[i][0][j+1]))
if code not in x:
x[code] = []
y[code] = []
z[code] = []
x[code].append(self.xmin + i * cube_size)
y[code].append(-1000)
z[code].append(self.zmin +j * cube_size)
if (hasattr(self,'rock_colors')):
c[code] = self.rock_colors[ int(self.block[i][0][j]) - 1]
else:
c[code] = int(self.block[i][j][0])
#yz
if 'x' in direction:
for i in range(0,self.ny):
for j in range(0,self.nz-1):
if self.block[0][i][j] != self.block[0][i][j+1]: #this is a contact
code = "%d_%d" % (min(self.block[0][i][j],self.block[0][i][j+1]),max(self.block[0][i][j],self.block[0][i][j+1]))
if code not in x:
x[code] = []
y[code] = []
z[code] = []
x[code].append(-1000)
y[code].append(self.ymin + i * cube_size)
z[code].append(self.zmin + j * cube_size)
if (hasattr(self,'rock_colors')):
c[code] = self.rock_colors[ int(self.block[0][i][j]) - 1]
else:
c[code] = int(self.block[i][j][0])
return (x,y,z,c)
def get_section_voxels(self, direction='y',position='center', **kwds):
"""Create and returns section block through the model
**Arguments**:
- *direction* = 'x', 'y', 'z' : coordinate direction of section plot (default: 'y')
- *position* = int or 'center' : cell position of section as integer value
or identifier (default: 'center')
**Optional Keywords**:
- *data* = np.array : data to plot, if different to block data itself
- *litho_filter* = a list of lithologies to draw. All others will be ignored.
"""
data = kwds.get('data',self.block)
if direction == 'x':
if position == 'center':
cell_pos = self.nx / 2
else:
cell_pos = position
section_slice = data[int(cell_pos),:,:].transpose()
#xlabel = "y"
#ylabel = "z"
elif direction == 'y':
if position == 'center':
cell_pos = self.ny / 2
else:
cell_pos = position
section_slice = data[:,int(cell_pos),:].transpose()
#xlabel = "x"
#ylabel = "z"
elif direction == 'z':
if position == 'center':
cell_pos = self.nz / 2
else:
cell_pos = position
section_slice = self.block[:,:,int(cell_pos)].transpose()
else:
print(("Error: %s is not a valid direction. Please specify either ('x','y' or 'z')." % direction))
#filter by lithology if a filter is set
if 'litho_filter' in kwds:
litho_filter = kwds['litho_filter']
if not litho_filter is None:
mask = []
for x in range(len(section_slice)):
mask.append([])
for y in range(len(section_slice[x])):
if not int(section_slice[x][y]) in litho_filter:
#section_slice[x][y] = -1 #null values
mask[x].append(True)
else:
mask[x].append(False)
#apply mask
section_slice = np.ma.masked_array(section_slice, mask=mask)
#section_slice = np.ma.masked_where(mask, section_slice)
return section_slice, cell_pos
def get_wellbore_voxels(self, **kwds):
"""Create and returns section block through the model
**Arguments**:
- *direction* = 'x', 'y', 'z' : coordinate direction of section plot (default: 'y')
- *position* = int or 'center' : cell position of section as integer value
or identifier (default: 'center')
**Optional Keywords**:
- *data* = np.array : data to plot, if different to block data itself
- *litho_filter* = a list of lithologies to draw. All others will be ignored.
"""
data = kwds.get('data',self.block)
section_slice = data[int(self.nx / 2),int(self.ny / 2),:].transpose()
return section_slice
def get_wellbore_voxels_from_paths(self, xi,yi,zi, **kwds):
x = np.arange(self.xmin, self.xmax, self.delx)
y = np.arange(self.ymin, self.ymax, self.dely)
z = np.arange(self.zmin, self.zmax, self.delz)
V = self.block
Vi = interpn((x,y,z), V, np.array([xi,yi,zi]).T)
return Vi
def plot_section(self, direction='y', position='center', **kwds):
"""Create a section block through the model
**Arguments**:
- *direction* = 'x', 'y', 'z' : coordinate direction of section plot (default: 'y')
- *position* = int or 'center' : cell position of section as integer value
or identifier (default: 'center')
**Optional Keywords**:
- *ax* = matplotlib.axis : append plot to axis (default: create new plot)
- *figsize* = (x,y) : matplotlib figsize
- *colorbar* = bool : plot colorbar (default: True)
- *colorbar_orientation* = 'horizontal' or 'vertical' : orientation of colorbar
(default: 'vertical')
- *title* = string : plot title
- *savefig* = bool : save figure to file (default: show directly on screen)
- *cmap* = matplotlib.cmap : colormap (default: YlOrRd)
- *fig_filename* = string : figure filename
- *ve* = float : vertical exaggeration
- *layer_labels* = list of strings: labels for each unit in plot
- *layers_from* = noddy history file : get labels automatically from history file
- *data* = np.array : data to plot, if different to block data itself
- *litho_filter* = a list of lithologies to draw. All others will be ignored.
"""
#try importing matplotlib
try:
import matplotlib.pyplot as plt
except ImportError:
print ("Could not draw image as matplotlib is not installed. Please install matplotlib")
cbar_orientation = kwds.get("colorbar_orientation", 'vertical')
litho_filter = kwds.get("litho_filter",None)
# determine if data are passed - if not, then recompute model
#data = kwds.get('data',self.block)
ve = kwds.get("ve", 1.)
cmap_type = kwds.get('cmap', 'YlOrRd')
if 'ax' in kwds:
# append plot to existing axis
ax = kwds['ax']
return_axis = True
else:
return_axis = False
figsize = kwds.get("figsize", (10,6))
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
savefig = kwds.get("savefig", False)
colorbar = kwds.get("colorbar", True)
# extract slice
#if kwds.has_key('data'):
section_slice, cell_pos = self.get_section_voxels(direction,position,**kwds)
#else:
# section_slice, cell_pos = self.get_section_voxels(direction,position,litho_filter=litho_filter)
#calculate axis labels
if 'x' in direction:
xlabel="y"
ylabel="z"
extent = [self.ymin-self.delx, self.ymax+self.dely, self.zmin-self.delz, self.zmax+self.delz]
elif 'y' in direction:
xlabel = "x"
ylabel = "z"
extent = [self.xmin-self.delx, self.xmax+self.delx, self.zmin-self.delz, self.zmax+self.delz]
elif 'z' in direction:
xlabel = "x"
ylabel = "y"
extent = [self.xmin-self.delx, self.xmax+self.delx, self.ymin-self.dely, self.ymax+self.dely]
#plot section
title = kwds.get("title", "Section in %s-direction, pos=%d" % (direction, cell_pos))
im = ax.imshow(section_slice, interpolation='nearest', aspect=ve, cmap=cmap_type, origin = 'lower left', extent=extent)
if colorbar and 'ax' not in kwds and False: #disable - color bar is broken
# cbar = plt.colorbar(im)
# _ = cbar
#
import matplotlib as mpl
bounds = np.arange(np.min(section_slice),np.max(section_slice)+1)
cmap = plt.cm.jet
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
if cbar_orientation == 'horizontal':
ax2 = fig.add_axes([0.125, 0.18, 0.775, 0.04])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_type, norm=norm, spacing='proportional',
ticks=bounds, boundaries=bounds-0.5, label='Lithology',
orientation = 'horizontal') # , format='%s')
else: # default is vertical
# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.165, 0.03, 0.69])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_type, norm=norm, spacing='proportional',
ticks=bounds, boundaries=bounds-0.5, label = 'Lithology',
orientation = 'vertical') # , format='%s')
# define the bins and normalize
if "layer_labels" in kwds:
cb.set_ticklabels(kwds["layer_labels"])
# invert axis to have "correct" stratigraphic order
cb.ax.invert_yaxis()
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if return_axis:
return ax
elif savefig:
fig_filename = kwds.get("fig_filename", "%s_section_%s_pos_%d" % (self.basename, direction, cell_pos))
plt.savefig(fig_filename, bbox_inches="tight")
else:
plt.show()
def plot_section_faults(self, direction='y', position='center', xy_origin=[0,0, 0], **kwds):
"""Create a section block through the model
**Arguments**:
- *direction* = 'x', 'y', 'z' : coordinate direction of section plot (default: 'y')
- *position* = int or 'center' : cell position of section as integer value
or identifier (default: 'center')
**Optional Keywords**:
- *ax* = matplotlib.axis : append plot to axis (default: create new plot)
- *figsize* = (x,y) : matplotlib figsize
- *colorbar* = bool : plot colorbar (default: True)
- *colorbar_orientation* = 'horizontal' or 'vertical' : orientation of colorbar
(default: 'vertical')
- *title* = string : plot title
- *savefig* = bool : save figure to file (default: show directly on screen)
- *cmap* = matplotlib.cmap : colormap (default: YlOrRd)
- *fig_filename* = string : figure filename
- *ve* = float : vertical exaggeration
- *layer_labels* = list of strings: labels for each unit in plot
- *layers_from* = noddy history file : get labels automatically from history file
- *data* = np.array : data to plot, if different to block data itself
- *litho_filter* = a list of lithologies to draw. All others will be ignored.
"""
#try importing matplotlib
try:
import matplotlib.pyplot as plt
except ImportError:
print ("Could not draw image as matplotlib is not installed. Please install matplotlib")
cbar_orientation = kwds.get("colorbar_orientation", 'vertical')
litho_filter = kwds.get("litho_filter",None)
# determine if data are passed - if not, then recompute model
#data = kwds.get('data',self.block)
ve = kwds.get("ve", 1.)
cmap_type = kwds.get('cmap', 'YlOrRd')
if 'ax' in kwds:
# append plot to existing axis
ax = kwds['ax']
return_axis = True
else:
return_axis = False
figsize = kwds.get("figsize", (10,6))
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
savefig = kwds.get("savefig", False)
colorbar = kwds.get("colorbar", True)
# extract slice
#if kwds.has_key('data'):
section_slice, cell_pos = self.get_section_voxels(direction,position,**kwds)
#else:
# section_slice, cell_pos = self.get_section_voxels(direction,position,litho_filter=litho_filter)
#calculate axis labels
if 'x' in direction:
xlabel="y"
ylabel="z"
extent = [self.ymin-0.5*self.dely +xy_origin[1], self.ymax+0.5*self.dely +xy_origin[1], self.zmin-0.5*self.delz+xy_origin[2], self.zmax+0.5*self.delz+xy_origin[2]]
elif 'y' in direction:
xlabel = "x"
ylabel = "z"
extent = [self.xmin-0.5*self.delx + xy_origin[0], self.xmax+0.5*self.delx+xy_origin[0], self.zmin-0.5*self.delz+xy_origin[2], self.zmax+0.5*self.delz+xy_origin[2]]
elif 'z' in direction:
xlabel = "x"
ylabel = "y"
extent = [self.xmin-0.5*self.delx+xy_origin[0], self.xmax+0.5*self.delx+xy_origin[0], self.ymin-0.5*self.dely+xy_origin[1], self.ymax+0.5*self.dely+xy_origin[1]]
#plot section
title = kwds.get("title", "Section in %s-direction, pos=%d" % (direction, cell_pos))
im = ax.imshow(section_slice, interpolation='nearest', aspect=ve, cmap=cmap_type, origin = 'lower left', extent=extent)
if colorbar and 'ax' not in kwds and False: #disable - color bar is broken
# cbar = plt.colorbar(im)
# _ = cbar
#
import matplotlib as mpl
bounds = np.arange(np.min(section_slice),np.max(section_slice)+1)
cmap = plt.cm.jet
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
if cbar_orientation == 'horizontal':
ax2 = fig.add_axes([0.125, 0.18, 0.775, 0.04])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_type, norm=norm, spacing='proportional',
ticks=bounds, boundaries=bounds-0.5, label='Lithology',
orientation = 'horizontal') # , format='%s')
else: # default is vertical
# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.165, 0.03, 0.69])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_type, norm=norm, spacing='proportional',
ticks=bounds, boundaries=bounds-0.5, label = 'Lithology',
orientation = 'vertical') # , format='%s')
# define the bins and normalize
if "layer_labels" in kwds:
cb.set_ticklabels(kwds["layer_labels"])
# invert axis to have "correct" stratigraphic order
cb.ax.invert_yaxis()
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if return_axis:
return ax
elif savefig:
fig_filename = kwds.get("fig_filename", "%s_section_%s_pos_%d" % (self.basename, direction, cell_pos))
plt.savefig(fig_filename, bbox_inches="tight")
else:
plt.show()
def export_to_vtk(self, **kwds):
"""Export model to VTK
Export the geology blocks to VTK for visualisation of the entire 3-D model in an
external VTK viewer, e.g. Paraview.
..Note:: Requires pyevtk, available for free on: https://github.com/firedrakeproject/firedrake/tree/master/python/evtk
**Optional keywords**:
- *vtk_filename* = string : filename of VTK file (default: output_name)
- *data* = np.array : data array to export to VKT (default: entire block model)
"""
vtk_filename = kwds.get("vtk_filename", self.basename)
try:
from evtk.hl import gridToVTK
except:
from pyevtk.hl import gridToVTK
# Coordinates
x = np.arange(0, self.extent_x + 0.1*self.delx, self.delx, dtype='float64')
y = np.arange(0, self.extent_y + 0.1*self.dely, self.dely, dtype='float64')
z = np.arange(0, self.extent_z + 0.1*self.delz, self.delz, dtype='float64')
# self.block = np.swapaxes(self.block, 0, 2)
if "data" in kwds:
gridToVTK(vtk_filename, x, y, z, cellData = {"data" : kwds['data']})
else:
gridToVTK(vtk_filename, x, y, z, cellData = {"geology" : self.block})
class NoddyGeophysics(object):
"""Definition to read, analyse, and visualise calculated geophysical responses"""
def __init__(self, output_name):
"""Methods to read, analyse, and visualise calculated geophysical responses
.. note:: The geophysical responses have can be computed with a keyword in the
function `compute_model`, e.g.:
``pynoddy.compute_model(history_name, output, type = 'GEOPHYSICS')``
"""
self.basename = output_name
self.read_gravity()
self.read_magnetics()
def read_gravity(self):
"""Read calculated gravity response"""
grv_lines = open(self.basename + ".grv", 'r').readlines()
self.grv_header = grv_lines[:8]
# read in data
# print len(grv_lines) - 8
dx = len(grv_lines) - 8
dy = len(grv_lines[8].rstrip().split("\t"))
self.grv_data = np.ndarray((dx, dy))
for i,line in enumerate(grv_lines[8:]):
self.grv_data[i,:] = np.array([float(x) for x in line.rstrip().split("\t")])
def read_magnetics(self):
"""Read caluclated magnetic field response"""
mag_lines = open(self.basename + ".mag", 'r').readlines()
self.mag_header = mag_lines[:8]
# read in data
# print len(mag_lines) - 8
dx = len(mag_lines) - 8
dy = len(mag_lines[8].rstrip().split("\t"))
self.mag_data = np.ndarray((dx, dy))
for i,line in enumerate(mag_lines[8:]):
self.mag_data[i,:] = np.array([float(x) for x in line.rstrip().split("\t")])
class NoddyTopology(object):
"""Definition to read, analyse, and visualise calculated voxel topology"""
def __init__(self, noddy_model, **kwds):
"""Methods to read, analyse, and visualise calculated voxel topology
.. note:: The voxel topology have can be computed with a keyword in the
function `compute_model`, e.g.: ``pynoddy.compute_model(history_name, output, type = 'TOPOLOGY')``
**Arguments**
- *noddy_model* = the name of the .his file or noddy output to run topology on.
**Optional Keywords**
- *load_attributes* = True if nodes and edges in the topology network should be attributed with properties such as volume
and surface area and lithology colour. Default is True.
"""
#if a .his file is passed strip extension
if "." in noddy_model:
output_name = noddy_model.split['.'][0] #remove file extension
else:
output_name = noddy_model
#load model
self.basename = output_name
self.load_attributes = kwds.get("load_attributes",True)
#load network
self.loadNetwork()
self.type = "overall"
def loadNetwork(self):
'''
Loads the topology network into a NetworkX datastructure
'''
#import networkx
try:
import networkx as nx
except ImportError:
print("Warning: NetworkX module could not be loaded. Please install NetworkX from https://networkx.github.io/ to perform topological analyses in PyNoddy")
#initialise new networkX graph
self.graph = nx.Graph()
self.graph.name = self.basename
#check files exist:
if not os.path.exists(self.basename+".g23"): #ensure topology code has been run
pynoddy.compute_topology(self.basename)
#load lithology properties
self.read_properties()
#load graph
f = open(self.basename + ".g23",'r')
lines = f.readlines() #read lines
for l in lines: #load edges
if '_' in l: #this line contains topology stuff (aka ignore empty lines)
l=l.rstrip()
data=l.split('\t')
#calculate edge colors
topoCode1 = data[0].split('_')[1]
topoCode2 = data[1].split('_')[1]
lithoCode1 = data[0].split('_')[0]
lithoCode2 = data[1].split('_')[0]
count = int(data[-1]) #number of voxels with this neighbour relationship (proxy of surface area)
#calculate edge type (dyke, fault etc)
eCode=0
eAge = self.lithology_properties[int(lithoCode1)]['age'] #for original stratigraphy. Default is the age of the first node
eType = 'stratigraphic' #default is stratigraphy
eColour='grey' #black
#calculate new topology codes
name = self.event_names[0] #default name is first name in sequence
for i in range(0,len(topoCode1) - 1): #-1 removes the trailing character
if (topoCode1[i] != topoCode2[i]): #find the difference
#this is the 'age' of this edge, as the lithologies formed during
#different events
eAge = i
#calculate what the difference means (ie. edge type)
if int(topoCode2[i]) > int(topoCode1[i]):
eCode=topoCode2[i]
else:
eCode=topoCode1[i]
name = self.event_names[i] #calculate event name
if int(eCode) == 0: #stratigraphic contact
eColour = 'grey'
eType = 'stratigraphic'
elif int(eCode) == 2 or int(eCode) == 7 or int(eCode) == 8: #various types of faults
eColour = 'r' #red
eType = 'fault'
elif int(eCode) == 3: #unconformity
eColour = 'g' #green
eType = 'unconformity'
elif int(eCode) == 5: #plug/dyke
eColour = 'orange' #orange
eType = 'intrusive'
else:
eColour = 'y' #yellow
eType = 'unknown'
#create nodes & associated properties
self.graph.add_node(data[0], lithology=lithoCode1, name=self.lithology_properties[int(lithoCode1)]['name'], age = self.lithology_properties[int(lithoCode1)]['age'])
self.graph.add_node(data[1], lithology=lithoCode2, name=self.lithology_properties[int(lithoCode2)]['name'], age = self.lithology_properties[int(lithoCode2)]['age'])
if (self.load_attributes):
self.graph.node[data[0]]['colour']=self.lithology_properties[int(lithoCode1)]['colour']
self.graph.node[data[0]]['centroid']=self.node_properties["%d_%s" % (int(lithoCode1),topoCode1) ]['centroid']
self.graph.node[data[0]]['volume'] = self.node_properties["%d_%s" % (int(lithoCode1),topoCode1) ]['volume']
self.graph.node[data[1]]['colour']=self.lithology_properties[int(lithoCode2)]['colour']
self.graph.node[data[1]]['centroid']=self.node_properties[ "%d_%s" % (int(lithoCode2),topoCode2) ]['centroid']
self.graph.node[data[1]]['volume'] = self.node_properties[ "%d_%s" % (int(lithoCode2),topoCode2) ]['volume']
#add edge
self.graph.add_edge(data[0],data[1],name=name,edgeCode=eCode,edgeType=eType, colour=eColour, area=count, weight=1, age=eAge)
def read_properties( self ):
#load lithology colours & relative ages. There is some duplication here
#of the NoddyOutput (sloppy, I know...) - ideally I should implement a base class
#that does this stuff and NoddyOutput and NoddyTopology both inherit from....
if os.path.exists(self.basename + ".g20"):
filelines = open(self.basename + ".g20").readlines()
self.n_events = int(filelines[0].split(' ')[2]) #number of events
lithos = filelines[ 3 + self.n_events : len(filelines) - 1] #litho definitions
self.rock_ids = [] #list of litho ids. Will be a list from 1 to n
self.rock_names = [] #the (string) names of each rock type. Note that names including spaces will not be read properly.
self.rock_colors = [] #the colours of each rock type (in Noddy).
self.rock_events = [] #list of the events that created different lithologies
for l in lithos:
data = l.split(' ')
self.rock_ids.append(int(data[0]))
self.rock_events.append(int(data[1]))
self.rock_names.append(data[2])
self.rock_colors.append( (int(data[-3])/255., int(data[-2])/255., int(data[-1])/255.) )
#load last line (list of names)
self.event_names = (filelines[-1].strip()).split('\t')
#calculate stratigraphy
self.stratigraphy = [] #litho id's ordered by the age they were created in
for i in range(max(self.rock_events)+1): #loop through events
#create list of lithos created in this event
lithos = []
for n, e in enumerate(self.rock_events):
if e == i: #current event
lithos.append(self.rock_ids[n])
#reverse order... Noddy litho id's are ordered by event, but reverse ordered within depositional events (ie.
#lithologies created in younger events have larger ids, however the youngest unit created in a given event
#will have the smallest id...
for l in reversed(lithos):
self.stratigraphy.append(l)