-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.py
2502 lines (2000 loc) · 106 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
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.xmax / self.nx
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(i * cube_size)
y[code].append(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(i * cube_size)
y[code].append(-1000)
z[code].append(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(i * cube_size)
z[code].append(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 = int(self.nx / 2)
else:
cell_pos = int(position)
section_slice = data[cell_pos,:,:].transpose()
#xlabel = "y"
#ylabel = "z"
elif direction == 'y':
if position == 'center':
cell_pos = int(self.ny / 2)
else:
cell_pos = int(position)
section_slice = data[:,int(cell_pos),:].transpose()
#xlabel = "x"
#ylabel = "z"
elif direction == 'z':
if position == 'center':
cell_pos = int(self.nz / 2)
else:
cell_pos = int(position)
section_slice = self.block[:,:,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 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"
elif 'y' in direction:
xlabel = "x"
ylabel = "z"
elif 'z' in direction:
xlabel = "x"
ylabel = "y"
#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')
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})
def CalculatePlotStructure(modelfile, plot, noddy_path, includeGravityCalc=0,
xy_origin=[0,0, 0], outputOption = 1,
outputfolder = '', LithologyOpacity=0.2):
'''
Function to take an input history file, calculate it, convert it to dxf,
and then plot it in vtkplotter
Variables:
modelfile: the history file (e.q. Model.his)
plot: a reference to the vtkPlotter plot
noddy_path: where is your noddy executable file located? (e.q. 'C:/Users/ahino/Documents/GitHub/pynoddy/noddyapp/noddy_win64.exe')
includeGravityCalc: [0,1] - would you like to just plot the surface (0) or also calculate the gravity (1)
xy_origin: This shifts the model by this amount. Note that PyNoddy lithology models expand during the calculation phase
outputOption: would you like a single vtk file with all the faults (0)? or a vtk file for each surface (1)?
outputfolder: where would you like to dump all those generated vtk files
LithologyOpacity: 0: you can't see the lithology, 1: you can see only the lithology
'''
## Some extra imports just for this function
import vtkplotter as vtkP
import time
import matplotlib.pylab as pl
###################################
### Calculate the PyNoddy model
###################################
# Assign the output name for the calculation
output_name = outputfolder+'vtkscratch'
## You can choose whether to calculate the gravity data as well as the surfaces
if(includeGravityCalc==0):
outputoption = 'BLOCK_SURFACES'
else:
outputoption = 'ALL'
#Calculate the model
start = time.time()
pynoddy.compute_model(modelfile, output_name, sim_type=outputoption, noddy_path=noddy_path)
end = time.time()
print('Calculation time took '+str(end - start) + ' seconds')
###################################
### Convert the dxf surfaces to vtk
###################################
## Now need to change the DXF file (mesh format) to VTK.
## This is slow unfortunately and I'm sure can be optimized
start = time.time()
points, cell_data, faceCounter = getDXF_parsed_structure(output_name)
end = time.time()
print('Parsing time took '+str(end - start) + ' seconds')
###################################
### Convert parsed structure to vtk
###################################
## Make a vtk file for each surface (option 1)
# or make a single vtk file for all surfaces (option 2)
fileprefix = outputfolder+'Surface'
start = time.time()
nSurfaces, points, CatCodes = convertSurfaces2VTK(points, cell_data, faceCounter, outputOption, fileprefix, xy_origin=xy_origin)
end = time.time()
print('Convert 2 VTK time took '+str(end - start) + ' seconds')
###################################
### Add the lithology block to the plot
###################################
## Now get the lithology data
N1 = NoddyOutput(output_name)
vol = vtkP.Volume(N1.block, c='jet', spacing=[N1.delx, N1.dely,N1.delz], origin =[xy_origin[0]+N1.xmin, xy_origin[1]+N1.ymin, xy_origin[2]+N1.zmin])
lego = vol.legosurface(-1, np.max(N1.block)*2).opacity(LithologyOpacity).c('jet')
plot += lego
###################################
### Add the calculated surfaces to the plot
###################################
#make sure each surface gets its own color
colors = pl.cm.jet(np.linspace(0,1,nSurfaces))
if(outputOption==1):
for i in range(nSurfaces):
filename = fileprefix+str(i)+'.vtk'
e=vtkP.load(filename).c(colors[i, 0:3])
plot += e
else:
filename = 'Model.vtk'
e=vtkP.load(filename)
plot += e
return points
def getDXF_parsed_structure(output_name):
'''
Take a dxf file and convert it to a point set
This needs some optimization work which could probably save 90% of the time
(maybe by completly loading and then doing some matrix parse operations,
or by using a converter inside np.loadtxt)
'''
filename = output_name + '.dxf'
cell_data = []
xpoint = []
ypoint = []
zpoint = []
with open(filename) as f:
cntr=0
faceCounter=0
for line in f:
if(cntr==(7+faceCounter*28)):
cell_data.append(line)
faceCounter=faceCounter+1
elif(cntr==(9+(faceCounter-1)*28)):
xpoint.append(float(line))
elif(cntr==(11+(faceCounter-1)*28)):
ypoint.append(float(line))
elif(cntr==(13+(faceCounter-1)*28)):
zpoint.append(float(line))
elif(cntr==(15+(faceCounter-1)*28)):
xpoint.append(float(line))
elif(cntr==(17+(faceCounter-1)*28)):
ypoint.append(float(line))
elif(cntr==(19+(faceCounter-1)*28)):
zpoint.append(float(line))
elif(cntr==(21+(faceCounter-1)*28)):
xpoint.append(float(line))
elif(cntr==(23+(faceCounter-1)*28)):
ypoint.append(float(line))
elif(cntr==(25+(faceCounter-1)*28)):
zpoint.append(float(line))
cntr=cntr+1
points = np.column_stack((np.asarray(xpoint, dtype=float),
np.asarray(ypoint, dtype=float),
np.asarray(zpoint, dtype=float)))
cell_data.pop()
cell_data = np.asarray(cell_data, dtype=object)
return points, cell_data, faceCounter
def convertSurfaces2VTK(points, cell_data, faceCounter, outputOption = 1,
fileprefix='Surface', xy_origin=[0,0,0]):
'''
Takes a pointset and then turns it into a vtk
Variables:
points, cell_data, faceCounter: outputs from getDXF_parsed_structure
outputOption: [0,1] 0: create a single vtk file with all the geologic events
1: multiple vtk files, one for each event
fileprefix: the file prefix for each vtk file
xy_origin: an offset to apply to the objects
'''
import meshio
import pandas as pd
num3Dfaces=faceCounter
print('The number of triangle elements (cells/faces) is: ' + str(num3Dfaces))
#apply origin transformation
points[:, 0] = points[:, 0]+xy_origin[0]
points[:, 1] = points[:, 1]+xy_origin[1]
points[:, 2] = points[:, 2]+xy_origin[2]
cell_data = pd.Series(cell_data.reshape((-1, )))
#In the output of the SURFACES command in pynoody, each surface is assigned a code
#The code indicates to which event each surface belongs
#I haven't completely understood how this code works.
#So this parsing of events can be improved.
#This is from the Noddy Manual:
# The naming convention for stratigraphic layer names is as follows:
# S02040005
# Where:
# • The initial S indicates that this is a stratigraphic surface.
# • The next two characters (02 in this example) refer to the stratigraphy
# number, showing that this is the second stratigraphy defined in the
# deformation history.
# • The next two characters (04) refer to the surface number within this
# stratigraphy.
# • The last four characters (0005) are an internally generated code which
# uniquely identify which contiguous volume this layer sits in the model.
# Faults, unconformities, plugs and dykes all cut a geological model into
# discontinuous volumes, and each distinct volume, across which other surfaces
# are discontinuous, are labelled internally by the software.
# The naming convention for discontinuity layer names is as follows:
# B003006009
# Where:
# • The initial B indicates that this is a discontinuity surface (Fault,
# unconformity, plug or dyke).
# • The next three characters (003 in this example) indicate event numbers of
# the discontinuity causing deformation event.
# • The next three characters (036) indicate the internally generated contiguous
# volume code of the volume on one side of the discontinuity.
# • The final three characters (009) indicate the internally generated contiguous
# volume code of the other side of the discontinuity.
# The reason for adopting such a complex scheme is that it allows related surfaces
# to be grouped in one of two ways:
# 1. Stratigraphic or discontinuity surfaces can all be selected by their age
# 2. Individual contiguous volumes may be selected by their volume code, so
# that all the surfaces surrounding a particular contiguous volume may be
# identified easily. This approach allows simple triangulated 3D volumes to
# be created.
CatCodes = np.zeros((len(cell_data),))
filterB = (cell_data.str.contains('B'))
filterS = (cell_data.str.contains('S'))
CatCodes[filterB]= cell_data.loc[filterB].str[:-20].astype('category').cat.codes
CatCodes[filterS]= -1*(cell_data.loc[filterS].str[:-12].astype('category').cat.codes+1)
for i in range(1, len(CatCodes)):
if(CatCodes[i]==0):
CatCodes[i]=CatCodes[i-1]
if(CatCodes[i-1]==0):
CatCodes[i]=CatCodes[np.nonzero(CatCodes)[0][0]]
UniqueCodes = np.unique(CatCodes)
nSurfaces = len(UniqueCodes)
## if you would like a single vtk file
if (outputOption==0):
cells = np.zeros((num3Dfaces, 3),dtype ='int')
i=0
for f in range(num3Dfaces):
cells[f,:]= [i, i+1, i+2]
i=i+3
meshio.write_points_cells(
"Model.vtk",
points,
cells={'triangle':cells},
cell_data= {'triangle': CatCodes}
)
## option 1: make a separate file for each surface
else:
for i in range(nSurfaces):
filterPoints = CatCodes==UniqueCodes[i]
nCells = np.sum(filterPoints)
Cells_i = np.zeros((nCells, 3),dtype ='int')
cntr = 0
for j in range(nCells):
Cells_i[j]=[cntr, cntr+1, cntr+2]
cntr=cntr+3
meshio.write_points_cells(
fileprefix+str(i)+".vtk",
points[np.repeat(filterPoints,3), :],
cells={'triangle':Cells_i}
)
return nSurfaces, points, CatCodes
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()