/
occam2d.py
2381 lines (1824 loc) · 87 KB
/
occam2d.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
# -*- coding: utf-8 -*-
"""
Spin-off from 'occamtools'
(Created August 2011, re-written August 2013)
Tools for Occam2D
authors: JP/LK
Classes:
- Data
- Model
- Setup
- Run
- Plot
- Mask
Functions:
- getdatetime
- makestartfiles
- writemeshfile
- writemodelfile
- writestartupfile
- read_datafile
- get_model_setup
- blocks_elements_setup
"""
#==============================================================================
import numpy as np
import scipy as sp
from scipy.stats import mode
import sys
import os
import os.path as op
import subprocess
import shutil
import fnmatch
import datetime
from operator import itemgetter
import time
import matplotlib.colorbar as mcb
from matplotlib.colors import Normalize
from matplotlib.ticker import MultipleLocator
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import mtpy.core.edi as MTedi
import mtpy.modeling.winglinktools as MTwl
import mtpy.utils.conversions as MTcv
import mtpy.utils.filehandling as MTfh
import mtpy.utils.configfile as MTcf
import mtpy.analysis.geometry as MTgy
import mtpy.utils.exceptions as MTex
import scipy.interpolate as si
reload(MTcv)
reload(MTcf)
reload(MTedi)
reload(MTex)
#==============================================================================
occamdict = {'1':'resxy','2':'phasexy','3':'realtip','4':'imagtip','5':'resyx',
'6':'phaseyx'}
#------------------------------------------------------------------------------
class Setup():
"""
Dealing with the setup for an Occam2D run. Generate 'startup', 'inmodel',
'mesh' files. Calling Data() for generating a suitable input data file.
Setting up those files within one (pre-determined) folder, so Occam can be
run there straight away.
"""
def __init__(self, configfile = None, **input_parameters):
self.parameters_startup = {}
self.parameters_inmodel = {}
self.parameters_data = {}
self.parameters_mesh = {}
self.parameters_prejudice = {}
self.parameters_startup['description'] = 'generic MTpy setup'
self.parameters_startup['iter_format'] = 'OCCAM_ITER'
self.parameters_startup['datetime_string'] = datetime.datetime.now().strftime(
'%Y/%m/%d %H:%M:%S')
self.parameters_startup['no_iteration'] = 0
self.parameters_startup['roughness_start'] = 1.0E+07
self.parameters_startup['reached_misfit'] = 0
self.parameters_startup['roughness_type'] = 1
self.parameters_startup['debug_level'] = 1
self.parameters_startup['mu_start'] = 5.0
self.parameters_startup['max_no_iterations'] = 30
self.parameters_startup['target_rms'] = 1.5
self.parameters_startup['rms_start'] = 1000
self.parameters_startup['halfspace_resistivity'] = 100.
self.parameters_inmodel['no_sideblockelements'] = 5
self.parameters_inmodel['no_bottomlayerelements'] = 4
self.parameters_inmodel['firstlayer_thickness'] = 100
self.parameters_inmodel['no_mergedsideblockelements'] = 5
self.parameters_inmodel['sidepadding_increasefactor'] = 2.
#model depth is in km!
self.parameters_inmodel['model_depth'] = 100
self.parameters_inmodel['no_layers'] = 25
self.parameters_inmodel['max_blockwidth'] = 1000
self.parameters_inmodel['model_name'] = 'Modelfile generated with MTpy'
self.parameters_inmodel['block_merge_threshold'] = 0.75
# factor determining amount of increase with each bottom padding
self.parameters_inmodel['bottompadding_scalefactor'] = 1.
self.parameters_inmodel['roughness_exceptions'] = None
self.parameters_inmodel['build_roughness_exceptions'] = False
self.parameters_inmodel['interface_dir'] = None
self.parameters_inmodel['interface_filelist'] = None
self.parameters_inmodel['elevation_filename'] = None
self.parameters_data['strike'] = None
self.parameters_data['rho_errorfloor'] = 0.
self.parameters_data['phase_errorfloor'] = 0.
self.parameters_data['tipper_errorfloor'] = 0.
self.parameters_data['tipper_errorfloor_abs'] = 0.
self.parameters_data['azimuth'] = 0
self.parameters_data['mode'] = 'tetm'
self.parameters_data['edi_type'] = 'z'
self.parameters_data['min_frequency'] = None
self.parameters_data['max_frequency'] = None
self.parameters_data['max_no_frequencies'] = None
self.parameters_mesh['mesh_title'] = 'Mesh file generated with MTpy'
self.parameters_prejudice = {}
self.parameters_prejudice['constraints_type'] = 'interfaces'
self.parameters_prejudice['build_prejudice_file'] = False
self.parameters_prejudice['interfaces'] = [] # list of arrays containing 2 columns, distance x along profile and depth z of interface
self.parameters_prejudice['interface_resistivity_values'] = None
self.parameters_prejudice['interface_prejudice_weights'] = None#
self.parameters_prejudice['interface_filelist'] = None
self.parameters_prejudice['welldata'] = None
self.parameters_prejudice['prejudice_weight'] = 1.
self.mesh = None
self.meshlocations_x = None
self.meshlocations_z = None
self.meshblockwidths_x = None
self.meshblockthicknesses_z = None
self.profile_easts = None
self.profile_norths = None
self.modelblocklocations_x = None
self.modelblocklocations_z = None
self.inmodel = None
self.no_parameters = None
self.welldata = None
self.well_xy = None
self.edifiles = []
self.Data = None
self.Prejudice = None
self.datafile = 'occaminputdata.dat'
self.meshfile = 'mesh'
self.inmodelfile = 'inmodel'
self.startupfile = 'startup'
self.staticsfile = None
self.prejudicefile = None
self.edi_directory = None
#working directory
self.wd = '.'
update_dict = {}
if configfile is not None:
try:
configfile = op.join(os.curdir,configfile)
if not op.isfile(configfile):
raise
except:
raise MTex.MTpyError_inputarguments('Error - Configuration '\
'file {0} does not exist!'.format(configfile))
try:
update_dict = {}
raw_configfile_content = MTcf.read_configfile(configfile)
for k in raw_configfile_content.keys():
temp_dict = raw_configfile_content[k]
update_dict.update(temp_dict)
except:
raise MTex.MTpyError_inputarguments('Error - Configuration '\
'file {0} cannot be read!'.format(configfile))
#correcting dictionary for upper case keys
input_parameters_nocase = {}
for key in input_parameters.keys():
input_parameters_nocase[key.lower()] = input_parameters[key]
update_dict.update(input_parameters_nocase)
for dictionary in [self.parameters_startup, self.parameters_inmodel,
self.parameters_mesh, self.parameters_data,
self.parameters_prejudice]:
for key in dictionary.keys():
if key in update_dict:
#check if entry exists:
try:
value = float(update_dict[key])
dictionary[key] = value
except:
value = update_dict[key]
dictionary[key] = value
if type(value) in [str]:
if value.strip().lower()=='none':
dictionary[key] = None
for key in update_dict:
try:
value = getattr(self,key)
if len(update_dict[key]) > 0:
try:
value = float(update_dict[key])
setattr(self,key,value)
except:
value = update_dict[key]
setattr(self,key,value)
if type(value) in [str]:
if value.strip().lower()=='none':
setattr(self,key,None)
except:
continue
if self.parameters_prejudice['build_prejudice_file']:
self.prejudicefile = 'prejudice'
def read_configfile(self, configfile):
cf = op.abspath(configfile)
if not op.isfile(cf):
print 'Warning - config file not found {0}'.format(cf)
return
config_dictionary = MTcf.read_configfile(cf)
no_p = self.update_parameters(config_dictionary)
no_a = self.update_attributes(config_dictionary)
print '{0} parameters and attributes updated'.format(no_a + no_p)
def update_parameters(self, **parameters_dictionary):
input_parameters_nocase = {}
for key in parameters_dictionary.keys():
input_parameters_nocase[key.lower()] = parameters_dictionary[key]
if self.validate_parameters(input_parameters_nocase) is False:
print 'Error - parameters invalid \n'
return
counter = 0
for dictionary in [self.parameters_startup, self.parameters_inmodel,
self.parameters_mesh, self.parameters_data]:
for key in dictionary.keys():
if key in input_parameters_nocase:
dictionary[key] = input_parameters_nocase[key]
counter += 1
return counter
def validate_parameters(self, **parameters_dictionary):
valid = True
return valid
def update_attributes(self, **attributes_dictionary):
input_attributes_nocase = {}
for key in attributes_dictionary.keys():
input_attributes_nocase[key.lower()] = attributes_dictionary[key]
if self.validate_attributes(input_attributes_nocase) is False:
print 'Error - attributes invalid \n'
return
counter = 0
for attr in dir(self):
if attr in input_attributes_nocase:
self.setattr(attr,input_attributes_nocase[attr])
counter += 1
return counter
def validate_attributes(self, **attributes_dictionary):
valid = True
return valid
def add_edifiles_directory(self, directory = None):
if directory is None:
print 'Error - provide directory name'
return
if op.isdir(directory) is False:
print 'Warning - not a valid directory - cannot browse for EDI files: {0}'.format(directory)
return
edilist_raw = fnmatch.filter(os.listdir(directory),'*.[Ee][Dd][Ii]')
edilist_full = [op.abspath(op.join(edi_dir,i)) for i in edilist_raw]
counter = 0
for edi in edilist_full:
try:
if op.isfile(edi):
self.edifiles.append(edi)
counter += 1
except:
continue
print 'Added {0} Edi files'.format(counter)
def add_edifiles(self, edilist):
if not np.iterable(edilist):
print 'Error - provide valid file list'
return
counter = 0
for edi in edilist:
try:
fn = op.abspath(op.join(os.curdir,edi))
if op.isfile(fn):
self.edifiles.append(fn)
counter += 1
except:
continue
print 'Added {0} Edi files'.format(counter)
def remove_edifiles(self, edilist):
if not np.iterable(edilist):
print 'Error - provide valid file list'
return
counter = 0
for edi in edilist:
try:
fn = op.abspath(op.join(os.curdir,edi))
if fn in self.edifiles:
self.edifiles.remove(fn)
counter += 1
except:
continue
print 'Removed {0} Edi files'.format(counter)
def read_edifiles(self, edi_dir = None):
if self.edi_directory is None:
self.edi_directory = op.abspath(os.curdir)
if (edi_dir is not None):
edi_dir = op.abspath(op.join(os.curdir,edi_dir))
if (edi_dir):
self.edi_directory = edi_dir
else:
print 'Warning - given directory not found: {0} \n\t-'\
' using current directory instead:{1}'.format(edi_dir,os.curdir)
edilist_raw = fnmatch.filter(os.listdir(self.edi_directory),'*.[Ee][Dd][Ii]')
edilist_full = [op.abspath(op.join(self.edi_directory,i)) for i in edilist_raw]
edilist = []
for edi in edilist_full:
if op.isfile(edi):
edilist.append(edi)
else:
continue
self.edifiles = edilist
def write_datafile(self):
try:
data_object = Data(edilist = self.edifiles, wd = self.wd, **self.parameters_data)
except:
print 'cannot write data file'
raise
self.stationlocations = data_object.stationlocations
data_object.writefile(self.datafile)
#self.datafile = data_object.datafile
self.Data = data_object
def setup_mesh_and_model(self):
"""
Build the mesh and inmodel blocks from given data and parameters.
Attributes required:
- self.stationlocations
- self.parameters_inmodel
"""
#given as offset on the profile line
lo_sites = self.Data.stationlocations
n_sites = len(lo_sites)
#maximum width of MODEL block - implicitely defines finiteness of the mesh
maxblockwidth = float(self.parameters_inmodel['max_blockwidth'])
#define vertical setup
#old version:
#number of layers per depth meters decade
#layers_per_decade = float(self.parameters_inmodel['no_layersperdecade'])
#new:
model_depth_m = float(self.parameters_inmodel['model_depth'])*1000.
#depth of first layer
first_layer_thickness = float(self.parameters_inmodel['firstlayer_thickness'])
#so "layers_per_decade" layers between "first_layer_thickness" and 10* "first_layer_thickness"
#then the same number between 10* "first_layer_thickness" and 100* "first_layer_thickness"
#padding layer does NOT count in here
n_layers = int(float(self.parameters_inmodel['no_layers']))
#number of padding mesh layers at the bottom
n_bottompadding = int(float(self.parameters_inmodel['no_bottomlayerelements']))
bottompadding_scalefactor = self.parameters_inmodel['bottompadding_scalefactor']
#number of padding mesh columns to the sides
n_sidepadding = int(float(self.parameters_inmodel['no_sideblockelements']))
nmerge_sidepadding = int(float(self.parameters_inmodel['no_mergedsideblockelements']))
if (n_sidepadding-nmerge_sidepadding)%2 == 1:
nmerge_sidepadding += 1
sidepadding_increasefactor = float(self.parameters_inmodel['sidepadding_increasefactor'])
#1. check, if inter-station spacing is smaller than the allowed max block size
#if not, add dummy station locations
lo_allsites = []
lo_distances = []
lo_real_station_distances = []
no_dummys = 0
print '\nlength of station profile: {0:.1f} km '.format((lo_sites[-1]-lo_sites[0])/1000.)
print 'Azimuth of profile: {0:.1f} degrees'.format(self.Data.azimuth)
if self.Data.strike is not None:
print 'Assumed strike: {0:.1f} degrees'.format(self.Data.strike)
else:
print 'Strike orientation unknown'
for idx_site,location in enumerate(lo_sites):
lo_allsites.append(location)
if idx_site == len(lo_sites)-1:
break
distance = np.abs(lo_sites[idx_site+1] - location)
lo_real_station_distances.append(distance)
if distance >= maxblockwidth:
dummys = int(distance/maxblockwidth)
smallblockwidth = distance/float(dummys+1)
no_dummys += dummys
for d in range(dummys):
lo_allsites.append(location + (d+1)* smallblockwidth)
lo_distances.append(smallblockwidth)
else:
lo_distances.append(distance)
print '\nadded {0} dummy stations'.format(no_dummys)
totalstations = no_dummys+len(lo_sites)
totalmeshblocknumber = 2*n_sidepadding+4+2*(totalstations)
totalmodelblocknumber = 4+totalstations+(n_sidepadding - nmerge_sidepadding)/2
print '{0} stations in total => \n\t{1} meshblocks and {2} modelblocks expected in top layer'.format(
totalstations,totalmeshblocknumber, totalmodelblocknumber)
#2. determine padding column widths:
paddingwidth = 0.5 * np.max(lo_real_station_distances)
meshnodelocations = []
#add left half of block under first station
leftedge = lo_allsites[0] - lo_distances[0]/2.
meshnodelocations.insert(0,leftedge)
#add extra block column on the left of first station
#consists of two mesh cells
leftedge -= paddingwidth
meshnodelocations.insert(0,leftedge)
leftedge -= paddingwidth
meshnodelocations.insert(0,leftedge)
#3. split the inner station gaps into 2 mesh blocks each
print lo_allsites
for idx,station in enumerate(lo_allsites):
meshnodelocations.append(station)
if idx == len(lo_allsites)-1:
break
#include point in the middle between here and next station
meshnodelocations.append(station+(lo_allsites[idx+1]-station)/2.)
#add right half of block under last station
rightedge = lo_allsites[-1] + lo_distances[-1]/2.
meshnodelocations.append(rightedge)
#add extra block column on the right of last station
#consists of two mesh cells
rightedge += paddingwidth
meshnodelocations.append(rightedge)
rightedge += paddingwidth
meshnodelocations.append(rightedge)
#add 2 side padding blocks with expon. increasing width of N mesh cells
padding_absolute = 0
padding_nmerge = 0
for p in range(n_sidepadding):
current_padding = sidepadding_increasefactor**(p+1)*paddingwidth
if current_padding > 100000:
current_padding = 100000
padding_absolute+=current_padding
if p < nmerge_sidepadding:
padding_nmerge += current_padding
rightedge += current_padding
meshnodelocations.append(rightedge)
leftedge -= current_padding
meshnodelocations.insert(0,leftedge)
print '\nlength of model profile: {0:.1f} km (from {1:.1f} to {2:.1f})'.format(
(meshnodelocations[-1]-meshnodelocations[0])/1000.,
meshnodelocations[0]/1000., meshnodelocations[-1]/1000.)
if len(meshnodelocations) > 1000:
raise MTex.MTpyError_occam('Error - Occam cannot handle more than 1000'\
' lateral mesh blocks - increase size of "max_blockwidth" !')
#4.determine the overall width of mesh blocks
lo_meshblockwidths = []
for loc in range(len(meshnodelocations)-1):
lo_meshblockwidths.append( meshnodelocations[loc+1] - meshnodelocations[loc] )
#5. build top layer modelblocks by merging paddings and then 2 blocks each:
lo_columns_to_merge = []
lo_modelblockwidths = []
current_meshblock_index = 0
lo_columns_to_merge.append(nmerge_sidepadding)
lo_modelblockwidths.append(padding_nmerge)
current_meshblock_index += nmerge_sidepadding
# merge the extra padding cells that haven't been merged into a big block at the edge
for ii in range((n_sidepadding - nmerge_sidepadding)/2):
lo_columns_to_merge.append(2)
lo_modelblockwidths.append(lo_meshblockwidths[current_meshblock_index]
+ lo_meshblockwidths[current_meshblock_index+1] )
current_meshblock_index += 2
#merge the extra column at the left:
lo_columns_to_merge.append(2)
lo_modelblockwidths.append( lo_meshblockwidths[current_meshblock_index]
+ lo_meshblockwidths[current_meshblock_index+1] )
current_meshblock_index += 2
for idx,location in enumerate(lo_allsites):
#each site is on top of a block, consisting of 2 mesh cells each
lo_columns_to_merge.append(2)
lo_modelblockwidths.append(lo_meshblockwidths[current_meshblock_index]
+ lo_meshblockwidths[current_meshblock_index+1] )
current_meshblock_index += 2
#merge right extra column
lo_columns_to_merge.append(2)
lo_modelblockwidths.append( lo_meshblockwidths[current_meshblock_index]
+ lo_meshblockwidths[current_meshblock_index+1] )
current_meshblock_index += 2
# merge the extra padding cells that haven't been merged into a big block at the edge
for ii in range((n_sidepadding - nmerge_sidepadding)/2):
lo_columns_to_merge.append(2)
lo_modelblockwidths.append(lo_meshblockwidths[current_meshblock_index]
+ lo_meshblockwidths[current_meshblock_index+1] )
current_meshblock_index += 2
#merge the side padding columns on the right
lo_columns_to_merge.append(nmerge_sidepadding)
lo_modelblockwidths.append(np.sum(padding_absolute))
current_meshblock_index += nmerge_sidepadding
#6.right side of left most model block - effectively the edge of the padding
#given with resspect to location of the first station
#idx of station 1 is n_sidepadding + 2(extra column) + 1 (half the block under the station)
#binding_offset = meshnodelocations[n_sidepadding+3] - meshnodelocations[n_sidepadding]
binding_offset = meshnodelocations[nmerge_sidepadding]
#should be identical!
no_x_nodes = current_meshblock_index + 1
nodey = len(lo_meshblockwidths) + 1 #vertical nodes
ncol0 = len(lo_columns_to_merge) # number of blocks in the first layer
#------
#7. now turn to depths - set up the z axis for the mesh:
# the model layers increas in thickness with depth
# the increase is in decadic logarithm, starting with the given depth
# of the first layer
#part to be scaled logarithmically:
log_part_thickness = model_depth_m - (n_layers-1) * first_layer_thickness
depths = np.logspace(np.log10(first_layer_thickness),
np.log10(log_part_thickness),
n_layers) + np.arange(n_layers) * first_layer_thickness
#no_decades = int(n_layers/layers_per_decade)+1
#no_depthpoints_max = layers_per_decade * no_decades
#depthscale = 10**np.linspace(0,no_decades,no_depthpoints_max + 1)
#lo_model_depths = list((depthscale[:n_layers-1] * first_layer_thickness))
lo_model_depths = list(depths)
lo_mesh_depths = []
lo_rows_to_merge = []
#2 mesh-blocks for a model layer only in the topmost layer
for idx, depth in enumerate(lo_model_depths):
if idx == 0:
newdepth = depth/2.
#else:
# newdepth = depth - (depth - lo_model_depths[idx-1])/2.
lo_mesh_depths.append(newdepth)
lo_rows_to_merge.append(2)
lo_mesh_depths.append(depth)
continue
lo_mesh_depths.append(depth)
lo_rows_to_merge.append(1)
lo_mesh_thicknesses = []
for idx,depth in enumerate(lo_mesh_depths):
if idx == 0:
thickness = depth
else:
thickness = depth - lo_mesh_depths[idx-1]
lo_mesh_thicknesses.append(thickness)
max_thickness = np.max(lo_mesh_thicknesses)
maxdepth = lo_mesh_depths[-1]
for i in range(n_bottompadding):
lo_mesh_thicknesses.append(max_thickness)
lo_mesh_depths.append(maxdepth+max_thickness)
maxdepth += max_thickness
max_thickness *= bottompadding_scalefactor
lo_model_depths.append(lo_model_depths[-1]+n_bottompadding*max_thickness)
#just to be safe!
# self.parameters_inmodel['no_layers'] = len(lo_model_depths)
lo_model_thicknesses = []
for idx,depth in enumerate(lo_model_depths):
if idx == 0:
thickness = depth
else:
thickness = depth - lo_model_depths[idx-1]
lo_model_thicknesses.append(thickness)
lo_rows_to_merge.append(n_bottompadding)
no_z_nodes = len(lo_mesh_depths) +1
self.parameters_inmodel['bindingoffset'] = binding_offset
self.parameters_inmodel['max_number_columns'] = ncol0
self.parameters_inmodel['lo_merged_lines'] = lo_rows_to_merge
self.meshblockwidths_x = lo_meshblockwidths
self.meshblockthicknesses_z = lo_mesh_thicknesses
self.meshlocations_z = lo_mesh_depths
self.meshlocations_x = meshnodelocations
self.parameters_mesh['no_nodes_x'] = no_x_nodes
self.parameters_mesh['no_nodes_z'] = no_z_nodes
#mesh DONE
#-----------------------------------------------------
#defining the actual blocks:
trigger = self.parameters_inmodel['block_merge_threshold']
modelblockstrings = []
lo_column_numbers = []
num_params = 0
ncol = ncol0
#loop over all model layers
#lo_modelblockwidths include the generaic merging of side padding mesh cells
#as well as the merging of each 2 neighbouring cells
#
for layer_idx, thickness in enumerate(lo_model_thicknesses):
#start with second column, because side paddings are never merged
block_idx = 1
#sweep columns
while block_idx+1 < ncol-1 :
#if two neighbouring blocks are wider than the thickness of the
#layer (times a factor), nothing happens
if thickness < (trigger*(lo_modelblockwidths[block_idx]+
lo_modelblockwidths[block_idx+1])):
block_idx += 1
continue
#otherwise: avoid the vertical over-exaggeration by merging 2
#neighboring blocks:
else:
#concatenate/merge blocks
lo_modelblockwidths[block_idx] += lo_modelblockwidths[block_idx+1]
lo_columns_to_merge[block_idx] += lo_columns_to_merge[block_idx+1]
lo_modelblockwidths.pop(block_idx+1)
lo_columns_to_merge.pop(block_idx+1)
ncol -=1
lo_column_numbers.append(ncol)
tempstring = ""
for j in range(ncol):
tempstring += "%i "%(lo_columns_to_merge[j])
tempstring += "\n"
modelblockstrings.append(tempstring)
num_params += ncol
print 'depth of model (incl.padding): {0:.1f} km'.format(lo_model_depths[-1]/1000.)
print '\nnumber of mesh layers: {0} ({1} model layers + 1 split top layer'\
' + {2} bottom-padding)'.format(len(lo_mesh_thicknesses),
n_layers,n_bottompadding)
print 'number of model blocks: {0}\n'.format(num_params)
self.no_parameters = num_params
self.parameters_inmodel['lo_modelblockstrings'] = modelblockstrings
self.parameters_inmodel['lo_column_numbers'] = lo_column_numbers
self.parameters_inmodel['lo_merged_columns'] = lo_columns_to_merge
self.parameters_inmodel['lo_model_thicknesses'] = lo_model_thicknesses
def write_meshfile(self):
"""
Create the mesh file
Attributes required:
- self.meshlocations_x
- self.meshlocations_z
- self.meshnodes_x
- self.meshnodes_z
- self.meshfile
- self.wd
"""
mesh_positions_vert = self.meshlocations_z
mesh_positions_hor = self.meshlocations_x
mesh_widths = self.meshblockwidths_x
mesh_depths = self.meshblockthicknesses_z
n_nodes_x = self.parameters_mesh['no_nodes_x']
n_nodes_z = self.parameters_mesh['no_nodes_z']
mesh_outstring =''
temptext = '{0}\n'.format(self.parameters_mesh['mesh_title'])
mesh_outstring += temptext
temptext = "{0} {1} {2} {0} {0} {3}\n".format(0,n_nodes_x,n_nodes_z,2)
mesh_outstring += temptext
temptext = ""
counter = 0
for i in range(n_nodes_x-1):
temptext += "%.1f "%(mesh_widths[i])
counter +=1
if counter == 10:
temptext += '\n'
counter = 0
temptext +="\n"
mesh_outstring += temptext
temptext = ""
counter = 0
for i in range(n_nodes_z-1):
temptext += "%.1f "%(mesh_depths[i])
counter +=1
if counter == 10:
temptext += '\n'
counter = 0
temptext +="\n"
mesh_outstring += temptext
mesh_outstring +="%i\n"%(0)
#occam source code has hard coded limit for reading not more than 1000
#characters per line:
if n_nodes_x < 1000:
# -1 since the surface is counted as uppermost node
for j in range(4*(n_nodes_z-1)):
tempstring=''
tempstring += (n_nodes_x-1)*"?"
tempstring += '\n'
mesh_outstring += tempstring
else:
#hope that occam fortran code can handle line breaks:
#most likely not....!!!
for j in range(4*(n_nodes_z-1)):
tempstring=''
counter = 0
for k in range(n_nodes_x-1):
tempstring += "?"
counter += 1
if counter == 1000:
#tempstring += '\n'
counter = 0
if counter != 0 :
tempstring += '\n'
mesh_outstring += tempstring
self.mesh = mesh_outstring
fn = op.join(self.wd,self.meshfile)
F_mesh = open(fn,'w')
F_mesh.write(mesh_outstring)
F_mesh.close()
def write_inmodelfile(self):
"""
Generate inmodel file.
Require attributes:
- self.parameters_inmodel['lo_modelblockstrings']
- self.parameters_inmodel['lo_columnnumbers']
- self.parameters_inmodel['lo_merged_columns']
- self.parameters_inmodel['bindingoffset']
- self.no_layers
"""
modelblockstrings = self.parameters_inmodel['lo_modelblockstrings']
lo_merged_columns = self.parameters_inmodel['lo_merged_columns']
lo_merged_lines = self.parameters_inmodel['lo_merged_lines']
lo_column_numbers = self.parameters_inmodel['lo_column_numbers']
boffset = self.parameters_inmodel['bindingoffset']
n_layers = int(self.parameters_inmodel['no_layers'])
model_outstring =''
temptext = "Format: {0}\n".format("OCCAM2MTMOD_1.0")
model_outstring += temptext
temptext = "Model Name: {0}\n".format(self.parameters_inmodel['model_name'])
model_outstring += temptext
temptext = "Description: {0}\n".format("Random Text")
model_outstring += temptext
temptext = "Mesh File: {0}\n".format(self.meshfile)
model_outstring += temptext
temptext = "Mesh Type: {0}\n".format("PW2D")
model_outstring += temptext
if self.staticsfile is not None:
temptext = "Statics File: {0}\n".format(self.staticsfile)
else:
temptext = "Statics File: none\n"
model_outstring += temptext
if self.prejudicefile is not None:
temptext = "Prejudice File: {0}\n".format(self.prejudicefile)
else:
temptext = "Prejudice File: none\n"
model_outstring += temptext
temptext = "Binding Offset: {0:.1f}\n".format(boffset)
model_outstring += temptext
temptext = "Num Layers: {0}\n".format(n_layers + 1 )
model_outstring += temptext
for k in range(n_layers+1):
n_meshlayers = lo_merged_lines[k]
n_meshcolumns = lo_column_numbers[k]
temptext="{0} {1}\n".format(n_meshlayers, n_meshcolumns)
model_outstring += temptext
temptext = modelblockstrings[k]
model_outstring += temptext
#model_outstring += "\n"
if self.parameters_inmodel['build_roughness_exceptions']:
for interface in self.parameters_inmodel['interface_filelist']:
self.project_interface(interface)
if self.parameters_inmodel['elevation_filename'] is not None:
self.subtract_elevation(self.parameters_inmodel['elevation_filename'])
self.build_roughness_exceptions()
re = self.parameters_inmodel['roughness_exceptions']
temptext = "Number Exceptions:{0}\n".format(-len(re))
temptext += '\n'.join([' '.join([str(rr) for rr in r]+['0']) for r in re])
else:
temptext = "Number Exceptions:{0}\n".format(0)
model_outstring += temptext
self.inmodel = model_outstring
fn = op.join(self.wd,self.inmodelfile)
F_model = open(fn,'w')
F_model.write(model_outstring)
F_model.close()
def write_startupfile(self):
"""
Generate startup file
Require attributes:
-
"""
startup_outstring =''
temptext = "Format: {0}\n".format(self.parameters_startup['iter_format'])
startup_outstring += temptext
temptext = "Description: {0}\n".format(self.parameters_startup['description'])
startup_outstring += temptext
temptext = "Model File: {0}\n".format(self.inmodelfile)
startup_outstring += temptext
temptext = "Data File: {0}\n".format(self.datafile)
startup_outstring += temptext
temptext = "Date/Time: {0}\n".format(self.parameters_startup['datetime_string'])
startup_outstring += temptext
temptext = "Max Iter: {0}\n".format(int(float(self.parameters_startup['max_no_iterations'])))
startup_outstring += temptext
temptext = "Target Misfit: {0:.2f}\n".format(float(self.parameters_startup['target_rms']))
startup_outstring += temptext
temptext = "Roughness Type: {0}\n".format(int(self.parameters_startup['roughness_type']))
startup_outstring += temptext
temptext = "Debug Level: {0}\n".format(int(self.parameters_startup['debug_level']))
startup_outstring += temptext
temptext = "Iteration: {0}\n".format(int(self.parameters_startup['no_iteration']))
startup_outstring += temptext
temptext = "Lagrange Value: {0}\n".format(self.parameters_startup['mu_start'])
startup_outstring += temptext
temptext = "Roughness Value: {0}\n".format(self.parameters_startup['roughness_start'])