-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistory.py
More file actions
2489 lines (2260 loc) · 84.5 KB
/
history.py
File metadata and controls
2489 lines (2260 loc) · 84.5 KB
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 history file wrapper
Created on 24/03/2014
@author: Florian Wellmann
'''
import time # for header in model generation
import numpy as np
# import numpy as np
# import matplotlib.pyplot as plt
from . import events
class NoddyHistory(object):
"""Class container for Noddy history files"""
def __init__(self, history=None, **kwds):
"""Methods to analyse and change Noddy history files
**Arguments**:
- *history* = string : Name of Noddy history file
**Optional Keywords**:
- *url* = url : link to history file on web (e.g. to download
and open directly from Atlas of Structural Geophysics,
http://virtualexplorer.com.au/special/noddyatlas/index.html
- *verbose* = True if this function should print output to the printstream. Default is False.
Note: if both a (local) history is given and a URL, the local
file is opened!
"""
vb = kwds.get('verbose', False)
if history is None:
if "url" in kwds:
self.load_history_from_url(kwds['url'])
self.determine_events(verbose=vb)
else:
# generate a new history
self.create_new_history()
else:
# load existing history
self.load_history(history)
self.determine_events(verbose=vb)
def __repr__(self):
"""Print out model information"""
return self.get_info_string()
def info(self, **kwds):
"""Print out model information
**Optional keywords**:
- *events_only* = bool : only information on events
"""
print((self.get_info_string(**kwds)))
def get_info_string(self, **kwds):
"""Get model information as string
**Optional keywords**:
- *events_only* = bool : only information on events
"""
events_only = kwds.get("events_only", False)
local_os = ""
if not events_only:
# First: check if all information available
if not hasattr(self, 'extent_x'): self.get_extent()
if not hasattr(self, 'origin_x'): self.get_origin()
if not hasattr(self, 'cube_size'): self.get_cube_size()
if not hasattr(self, 'filename'): self.get_filename()
if not hasattr(self, 'date_saved'): self.get_date_saved()
local_os += (60 * "*" + "\n\t\t\tModel Information\n" + 60 * "*")
local_os += ("\n\n")
if self.n_events == 0:
local_os += ("The model does not yet contain any events\n")
else:
local_os += ("This model consists of %d events:\n" % self.n_events)
for k, ev in list(self.events.items()):
local_os += ("\t(%d) - %s\n" % (k, ev.event_type))
if not events_only:
local_os += ("The model extent is:\n")
local_os += ("\tx - %.1f m\n" % self.extent_x)
local_os += ("\ty - %.1f m\n" % self.extent_y)
local_os += ("\tz - %.1f m\n" % self.extent_z)
local_os += ("Number of cells in each direction:\n")
local_os += ("\tnx = %d\n" % (self.extent_x / self.cube_size))
local_os += ("\tny = %d\n" % (self.extent_y / self.cube_size))
local_os += ("\tnz = %d\n" % (self.extent_z / self.cube_size))
local_os += ("The model origin is located at: \n\t(%.1f, %.1f, %.1f)\n" % (self.origin_x,
self.origin_y,
self.origin_z))
local_os += ("The cubesize for model export is: \n\t%d m\n" % self.cube_size)
# and now some metadata
local_os += ("\n\n")
local_os += (60 * "*" + "\n\t\t\tMeta Data\n" + 60 * "*")
local_os += ("\n\n")
local_os += ("The filename of the model is:\n\t%s\n" % self.filename)
local_os += ("It was last saved (if origin was a history file!) at:\n\t%s\n" % self.date_saved)
return local_os
def get_origin(self):
"""Get coordinates of model origin and return and store in local variables
**Returns**: (origin_x, origin_y, origin_z)
"""
# check if footer_lines exist (e.g. read in from file)
# if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
for i, line in enumerate(self.footer_lines):
if "Origin X" in line:
self.origin_x = float(self.footer_lines[i].split("=")[1])
self.origin_y = float(self.footer_lines[i + 1].split("=")[1])
self.origin_z = float(self.footer_lines[i + 2].split("=")[1])
break
return (self.origin_x, self.origin_y, self.origin_z)
def set_origin(self, origin_x, origin_y, origin_z):
"""Set coordinates of model origin and update local variables
**Arguments**:
- *origin_x* = float : x-location of model origin
- *origin_y* = float : y-location of model origin
- *origin_z* = float : z-location of model origin
"""
# check if footer_lines exist (e.g. read in from file)
# if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
self.origin_x = origin_x
self.origin_y = origin_y
self.origin_z = origin_z
origin_x_line = " Origin X = %.2f\n" % origin_x
origin_y_line = " Origin Y = %.2f\n" % origin_y
origin_z_line = " Origin Z = %.2f\n" % origin_z
for i, line in enumerate(self.footer_lines):
if "Origin X" in line:
self.footer_lines[i] = origin_x_line
self.footer_lines[i + 1] = origin_y_line
self.footer_lines[i + 2] = origin_z_line
break
def get_extent(self):
"""Get model extent and return and store in local variables
**Returns**: (extent_x, extent_y, extent_z)
"""
# check if footer_lines exist (e.g. read in from file)
# if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
for i, line in enumerate(self.footer_lines):
if "Length X" in line:
self.extent_x = float(self.footer_lines[i].split("=")[1])
self.extent_y = float(self.footer_lines[i + 1].split("=")[1])
self.extent_z = float(self.footer_lines[i + 2].split("=")[1])
break
return (self.extent_x, self.extent_y, self.extent_z)
def set_extent(self, extent_x, extent_y, extent_z):
"""Set model extent and update local variables
**Arguments**:
- *extent_x* = float : extent in x-direction
- *extent_y* = float : extent in y-direction
- *extent_z* = float : extent in z-direction
"""
# check if footer_lines exist (e.g. read in from file)
# if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
self.extent_x = extent_x
self.extent_y = extent_y
self.extent_z = extent_z
extent_x_line = " Length X = %.2f\n" % extent_x
extent_y_line = " Length Y = %.2f\n" % extent_y
extent_z_line = " Length Z = %.2f\n" % extent_z
for i, line in enumerate(self.footer_lines):
if "Length X" in line:
self.footer_lines[i] = extent_x_line
self.footer_lines[i + 1] = extent_y_line
self.footer_lines[i + 2] = extent_z_line
break
def get_drillhole_data(self, x, y, **kwds):
"""Get geology values along 1-D profile at position x,y with a 1 m resolution
The following steps are performed:
1. creates a copy of the entire object,
2. sets values of origin, extent and geology cube size,
3. saves model to a temporary file,
4. runs Noddy on that file
5. opens and analyses output
6. deletes temporary files
Note: this method only works if write access to current directory
is enabled and noddy can be executed!
**Arguments**:
- *x* = float: x-position of drillhole
- *y* = float: y-position of drillhole
**Optional Arguments**:
- *z_min* = float : minimum depth of drillhole (default: model range)
- *z_max* = float : maximum depth of drillhole (default: model range)
- *resolution* = float : resolution along profile (default: 1 m)
"""
# resolve keywords
resolution = kwds.get("resolution", 1)
self.get_extent()
self.get_origin()
z_min = kwds.get("z_min", self.origin_z)
z_max = kwds.get("z_max", self.extent_z)
# 1. create copy
import copy
tmp_his = copy.deepcopy(self)
tmp_his.write_history("test.his")
# 2. set values
tmp_his.set_origin(x, y, z_min)
tmp_his.set_extent(resolution, resolution, z_max)
tmp_his.change_cube_size(resolution)
# 3. save temporary file
tmp_his_file = "tmp_1D_drillhole.his"
tmp_his.write_history(tmp_his_file)
tmp_out_file = "tmp_1d_out"
# 4. run noddy
import pynoddy
import pynoddy.output
pynoddy.compute_model(tmp_his_file, tmp_out_file)
# 5. open output
tmp_out = pynoddy.output.NoddyOutput(tmp_out_file)
# 6.
return tmp_out.block[0, 0, :]
def load_history(self, history):
"""Load Noddy history
**Arguments**:
- *history* = string : Name of Noddy history file
"""
self.history_lines = open(history, 'r').readlines()
# set flag for model loaded from file
self._from_file = True
# get footer lines
self.get_footer_lines()
def load_history_from_url(self, url):
"""Directly load a Noddy history from a URL
This method is useful to load a model from the Structural Geophysics
Atlas on the pages of the Virtual Explorer.
See: http://tectonique.net/asg
**Arguments**:
- *url* : url of history file
"""
# test if python 2 or 3 are running for appropriate urllib functionality
import sys
if sys.version_info[0] < 3:
import urllib2
response = urllib2.urlopen(url)
tmp_lines = response.read().split("\n")
else:
# from urllib import urlopen # , urllib.error, urllib.parse
import urllib
with urllib.urlrequest.urlopen(url) as f:
output = f.read().decode('utf-8')
# response = urllib.request.urlopen(url)
tmp_lines = output.split("\n")
# tmp_lines = response.read().decode("utf-8").split("\n")
self.history_lines = []
for line in tmp_lines:
# append EOL again for consistency
self.history_lines.append(line + "\n")
# set flag for model loaded from URL
self._from_url = True
# get footer lines
self.get_footer_lines()
def determine_model_stratigraphy(self):
"""Determine stratigraphy of entire model from all events"""
self.model_stratigraphy = []
for e in np.sort(list(self.events.keys())):
if self.events[e].event_type == 'STRATIGRAPHY':
self.model_stratigraphy += self.events[e].layer_names
if self.events[e].event_type == 'UNCONFORMITY':
self.model_stratigraphy += self.events[e].layer_names
if self.events[e].event_type == 'DYKE':
self.model_stratigraphy += self.events[e].name
if self.events[e].event_type == 'PLUG':
self.model_stratigraphy += self.events[e].name
def determine_events(self, **kwds):
"""Determine events and save line numbers
.. note:: Parsing of the history file is based on a fixed Noddy output order.
If this is, for some reason (e.g. in a changed version of Noddy) not the case, then
this parsing might fail!
**Optional Keywords**:
- verbose = True if this function is should write to the print bufffer, otherwise False. Default is False.
"""
vb = kwds.get('verbose', False)
self._raw_events = []
for i, line in enumerate(self.history_lines):
if "No of Events" in line:
self.n_events = int(line.split("=")[1])
elif "Event #" in line:
event = {'type': line.split('=')[1].rstrip(), 'num': int(line[7:9]), 'line_start': i}
self._raw_events.append(event)
# finally: if the definition for BlockOptions starts, the event definition is over
elif "BlockOptions" in line:
last_event_stop = i - 2
# now: find the line ends for the single event blocks
for i, event in enumerate(self._raw_events[1:]):
self._raw_events[i]['line_end'] = event['line_start'] - 1
# now adjust for last event
self._raw_events[-1]['line_end'] = last_event_stop
self.events = {} # idea: create events as dictionary so that it is easier
# to swap order later!
# now create proper event objects for these events
if vb:
print("Loaded model with the following events:")
for e in self._raw_events:
event_lines = self.history_lines[e['line_start']:e['line_end']+1]
if vb:
print((e['type']))
if 'FAULT' in e['type']:
ev = events.Fault(lines=event_lines)
elif 'SHEAR_ZONE' in e['type']:
ev = events.Shear(lines=event_lines)
elif 'FOLD' in e['type']:
ev = events.Fold(lines=event_lines)
elif 'UNCONFORMITY' in e['type']:
ev = events.Unconformity(lines=event_lines)
elif 'STRATIGRAPHY' in e['type']:
# event_lines = event_lines[:-1]
ev = events.Stratigraphy(lines=event_lines)
elif 'TILT' in e['type']: # AK
ev = events.Tilt(lines=event_lines)
elif 'DYKE' in e['type']:
ev = events.Dyke(lines=event_lines)
elif 'PLUG' in e['type']:
ev = events.Plug(lines=event_lines)
elif 'STRAIN' in e['type']:
ev = events.Strain(lines=event_lines)
else:
print(("Warning: event of type %s has not been implemented in PyNoddy yet" % e['type']))
continue
# now set shared attributes (those defined in superclass Event)
order = e['num'] # retrieve event number
self.events[order] = ev # store events sequentially
# determine overall begin and end of the history events
self.all_events_begin = self._raw_events[0]['line_start']
self.all_events_end = self._raw_events[-1]['line_end']
def copy_events(self):
"""Create a copy of the current event state"""
import copy
return copy.deepcopy(self.events)
def get_cube_size(self, **kwds):
"""Determine cube size for model export
**Optional Args**
-type: choose geology or geophysics cube size to return. Should be either 'Geology' (default) or 'Geophysics'
"""
# get args
sim_type = kwds.get("type", 'Geophysics') # everything seems to use this
cube_string = 'Geophysics Cube Size' # get geology cube size by default
if ('Geology' in sim_type):
cube_string = 'Geology Cube Size' # instead get geology cube size
print("Warning: pynoddy uses the geophysics cube size for all calculations... changing the geology cube size will have no effect internally.")
# check if footer exists, if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
for line in self.footer_lines:
if cube_string in line:
self.cube_size = float(line.split('=')[1].rstrip())
return self.cube_size
def get_filename(self):
"""Determine model filename from history file/ header"""
self.filename = self.history_lines[0].split('=')[1].rstrip()
def get_date_saved(self):
"""Determine the last savepoint of the file"""
self.date_saved = self.history_lines[1].split('=')[1].rstrip()
def change_cube_size(self, cube_size, **kwds):
"""Change the model cube size (isotropic)
**Arguments**:
- *cube_size* = float : new model cube size
"""
# check if footer_lines exist (e.g. read in from file)
# if not: create from template
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
# lines_new = self.history_lines[:]
for i, line in enumerate(self.footer_lines):
if "Geophysics Cube Size" in line: # correct line, make change
l = line.split('=')
l_new = '%7.2f\r\n' % cube_size
line_new = l[0] + "=" + l_new
self.footer_lines[i] = line_new
if "Geology Cube Size" in line: # change geology cube size also
l = line.split('=')
l_new = '%7.2f\r\n' % cube_size
line_new = l[0] + "=" + l_new
self.footer_lines[i] = line_new
# assign changed lines back to object
# self.history_lines = lines_new[:]
def get_footer_lines(self):
"""Get the footer lines from self.history_lines
The footer contains everything below events (all settings, etc.)"""
# get id of footer from history lines
for i, line in enumerate(self.history_lines):
if "#BlockOptions" in line:
break
self.footer_lines = self.history_lines[i:]
def create_footer_from_template(self):
"""Create model footer (with all settings) from template"""
self.footer_lines = []
for line in _Templates().footer.split("\n"):
line = line.replace(" ", "\t")
self.footer_lines.append(line + "\n")
def swap_events(self, event_num_1, event_num_2):
"""Swap two geological events in the timeline
**Arguments**:
- *event_num_1/2* = int : number of events to be swapped ("order")
"""
# events have to be copied, otherwise only a reference is passed!
event_tmp = self.events[event_num_1]
self.events[event_num_1] = self.events[event_num_2]
self.events[event_num_2] = event_tmp
self.update_event_numbers()
def reorder_events(self, reorder_dict):
"""Reorder events accoring to assignment in reorder_dict
**Arguments**:
- *reorder_dict* = dict : for example {1 : 2, 2 : 3, 3 : 1}
"""
tmp_events = self.events.copy()
for key, value in list(reorder_dict.items()):
try:
tmp_events[value] = self.events[key]
except KeyError:
print(("Event with id %d is not defined, please check!" % value))
self.events = tmp_events.copy()
self.update_event_numbers()
def update_event_numbers(self):
"""Update event numbers in 'Event #' line in noddy history file"""
for key, event in list(self.events.items()):
event.set_event_number(key)
def update_all_event_properties(self):
"""Update properties of all events - in case changes were made"""
for event in list(self.events.values()):
event.update_properties()
#
# class NewHistory():
# """Methods to create a Noddy model"""
#
def create_new_history(self):
"""Methods to create a Noddy model
"""
# set event counter
self.event_counter = 0
self.all_events_begin = 7 # default after header
self.all_events_end = 7
# initialise history lines
self.history_lines = []
self.events = {}
def get_ev_counter(self):
"""Event counter for implicit and continuous definition of events"""
self.event_counter += 1
return self.event_counter
def add_event(self, event_type, event_options, **kwds):
"""Add an event type to history
**Arguments**:
- *event_type* = string : type of event, legal options to date are:
'stratigraphy', 'fault', 'fold', 'unconformity'
- *event_options* = list : required options to create event (event dependent)
**Optional keywords**:
- *event_num* = int : event number (default: implicitly defined with increasing counter)
"""
event_num = kwds.get("event_num", self.get_ev_counter())
if event_type == 'stratigraphy':
ev = self._create_stratigraphy(event_options)
ev.event_type = 'STRATIGRAPHY'
elif event_type == 'fault':
ev = self._create_fault(event_options)
ev.event_type = 'FAULT'
elif event_type == 'tilt': # AK
ev = self._create_tilt(event_options)
ev.event_type = 'TILT'
elif event_type == 'unconformity': # AK
ev = self._create_unconformity(event_options)
ev.event_type = 'UNCONFORMITY'
elif event_type == 'fold':
ev = self._create_fold(event_options)
ev.event_type = 'FOLD'
else:
raise NameError('Event type %s not (yet) implemented' % event_type)
ev.set_event_number(event_num)
self.events[event_num] = ev
# update beginning and ending of events in history
self.all_events_end = self.all_events_end + len(ev.event_lines)
# add event to history lines, as well (for consistency with other methods)
self.history_lines[:self.all_events_begin] + \
ev.event_lines + \
self.history_lines[self.all_events_end:]
def _create_header(self):
"""Create model header, include actual date"""
t = time.localtime() # get current time
time_string = "%d/%d/%d %d:%d:%d" % (t.tm_mday,
t.tm_mon,
t.tm_year,
t.tm_hour,
t.tm_min,
t.tm_sec)
self.header_lines = """#Filename = """ + self.filename + """
#Date Saved = """ + time_string + """
FileType = 111
Version = 7.11
"""
@staticmethod
def _create_stratigraphy(event_options):
"""Create a stratigraphy event
**Arguments**:
- *event_options* = list : list of required and optional settings for event
Options are:
'num_layers' = int : number of layers (required)
'layer_names' = list of strings : names for layers (default names otherwise)
'layer_thickness' = list of floats : thicknesses for all layers
"""
ev = events.Stratigraphy()
tmp_lines = [""]
tmp_lines.append("\tNum Layers\t= %d" % event_options['num_layers'])
for i in range(event_options['num_layers']):
"""Add stratigraphy layers"""
layer_name = event_options['layer_names'][i]
try:
density = event_options['density'][i]
except KeyError:
density = 4.0
cum_thickness = np.cumsum(event_options['layer_thickness'])
layer_lines = _Templates().strati_layer
# now replace required variables
layer_lines = layer_lines.replace("$NAME$", layer_name)
layer_lines = layer_lines.replace("$HEIGHT$", "%.1f" % cum_thickness[i])
layer_lines = layer_lines.replace(" ", "\t")
layer_lines = layer_lines.replace("$DENSITY$", "%e" % density)
# split lines and add to event lines list:
for layer_line in layer_lines.split("\n"):
tmp_lines.append(layer_line)
# append event name
tmp_lines.append("""\tName\t= Strat""")
# event lines are defined in list:
tmp_lines_list = []
for line in tmp_lines:
tmp_lines_list.append(line + "\n")
ev.set_event_lines(tmp_lines_list)
ev.num_layers = event_options['num_layers']
return ev
def _create_fault(self, event_options):
"""Create a fault event
**Arguments**:
- *event_options* = list : list of required and optional settings for event;
Options are:
'name' = string : name of fault event
'pos' = (x,y,z) : position of reference point (floats)
.. note:: for convenience, it is possible to assign 'top' to z
for position at "surface"
'dip_dir' = [0,360] : dip direction of fault
'dip' = [0,90] : dip angle of fault
'slip' = float : slip along fault
'geometry' = 'Translation', 'Curved' : geometry of fault plane (default: 'Translation')
'movement' = 'Hanging Wall', 'Foot Wall' : relative block movement (default: 'Hanging Wall')
'rotation' = float: fault rotation (default: 30.0)
'amplitude' = float: (default: 2000.0)
'radius' = float: (default: 1000.0)
'xaxis' = float: (default: 2000.0)
'yaxis' = float: (default: 2000.0)
'zaxis' = float: (default: 2000.0)
"""
ev = events.Fault()
tmp_lines = [""]
fault_lines = _Templates.fault
# substitute text with according values
fault_lines = fault_lines.replace("$NAME$", event_options['name'])
fault_lines = fault_lines.replace("$POS_X$", "%.1f" % event_options['pos'][0])
fault_lines = fault_lines.replace("$POS_Y$", "%.1f" % event_options['pos'][1])
if event_options['pos'] == 'top':
# recalculate z-value to be at top of model
z = self.zmax
fault_lines = fault_lines.replace("$POS_Z$", "%.1f" % z)
else:
fault_lines = fault_lines.replace("$POS_Z$", "%.1f" % event_options['pos'][2])
fault_lines = fault_lines.replace("$DIP_DIR$", "%.1f" % event_options['dip_dir'])
fault_lines = fault_lines.replace("$DIP$", "%.1f" % event_options['dip'])
fault_lines = fault_lines.replace("$SLIP$", "%.1f" % event_options['slip'])
fault_lines = fault_lines.replace("$MOVEMENT$", "%s" % event_options.get('movement', 'Hanging Wall'))
fault_lines = fault_lines.replace("$GEOMETRY$", "%s" % event_options.get('geometry', 'Translation'))
fault_lines = fault_lines.replace("$ROTATION$", "%.1f" % event_options.get('rotation', 30.0))
fault_lines = fault_lines.replace("$AMPLITUDE$", "%.1f" % event_options.get('amplitude', 2000.0))
fault_lines = fault_lines.replace("$RADIUS$", "%.1f" % event_options.get('radius', 1000.0))
fault_lines = fault_lines.replace("$XAXIS$", "%.1f" % event_options.get('xaxis', 2000.0))
fault_lines = fault_lines.replace("$YAXIS$", "%.1f" % event_options.get('yaxis', 2000.0))
fault_lines = fault_lines.replace("$ZAXIS$", "%.1f" % event_options.get('zaxis', 2000.0))
# $GEOMETRY$ Translation
# now split lines and add as list entries to event lines
# event lines are defined in list:
# split lines and add to event lines list:
for layer_line in fault_lines.split("\n"):
tmp_lines.append(layer_line)
tmp_lines_list = []
for line in tmp_lines:
tmp_lines_list.append(line + "\n")
ev.set_event_lines(tmp_lines_list)
return ev
def _create_fold(self, event_options):
"""Create a fold event
**Arguments**:
- *event_options* = list : list of required and optional settings for event;
Options are:
'name' = string : name of fault event
'pos' = (x,y,z) : position of reference point (floats)
.. note:: for convenience, it is possible to assign 'top' to z
for position at "surface"
'amplitude' = float : amplitude of fold
'wavelength' = float : wavelength of fold
'dip_dir' = float : dip (plane) direction (default: 90)
'dip' = float : fault (plane) dip (default: 90)
"""
ev = events.Fault()
tmp_lines = [""]
fault_lines = _Templates.fold
# substitute text with according values
fault_lines = fault_lines.replace("$NAME$", event_options['name'])
fault_lines = fault_lines.replace("$POS_X$", "%.1f" % event_options['pos'][0])
fault_lines = fault_lines.replace("$POS_Y$", "%.1f" % event_options['pos'][1])
if event_options['pos'] == 'top':
# recalculate z-value to be at top of model
z = self.zmax
fault_lines = fault_lines.replace("$POS_Z$", "%.1f" % z)
else:
fault_lines = fault_lines.replace("$POS_Z$", "%.1f" % event_options['pos'][2])
fault_lines = fault_lines.replace("$WAVELENGTH$", "%.1f" % event_options['wavelength'])
fault_lines = fault_lines.replace("$AMPLITUDE$", "%.1f" % event_options['amplitude'])
# fault_lines = fault_lines.replace("$SLIP$", "%.1f" % event_options['slip'])
fault_lines = fault_lines.replace("$DIP_DIR$", "%.1f" % event_options.get('dip_dir', 90.0))
fault_lines = fault_lines.replace("$DIP$", "%.1f" % event_options.get('dip', 90.0))
# now split lines and add as list entries to event lines
# event lines are defined in list:
# split lines and add to event lines list:
for layer_line in fault_lines.split("\n"):
tmp_lines.append(layer_line)
tmp_lines_list = []
for line in tmp_lines:
tmp_lines_list.append(line + "\n")
ev.set_event_lines(tmp_lines_list)
return ev
# AK 2014-10
def _create_tilt(self, event_options):
"""Create a tilt event
**Arguments**:
- *event_options* = list : list of required and optional settings for event;
Options are:
'name' = string : name of tilt event
'pos' = (x,y,z) : position of reference point (floats)
.. note:: for convenience, it is possible to assign 'top' to z
for position at "surface"
'rotation' = [0,360] : dip?
'plunge_direction' = [0,360] : strike of plunge, measured from x axis
'plunge' = float : ?
"""
ev = events.Tilt()
tmp_lines = [""]
tilt_lines = _Templates.tilt
# substitute text with according values
tilt_lines = tilt_lines.replace("$NAME$", event_options['name'])
tilt_lines = tilt_lines.replace("$POS_X$", "%.1f" % event_options['pos'][0])
tilt_lines = tilt_lines.replace("$POS_Y$", "%.1f" % event_options['pos'][1])
if event_options['pos'] == 'top':
# recalculate z-value to be at top of model
z = self.zmax
tilt_lines = tilt_lines.replace("$POS_Z$", "%.1f" % z)
else:
tilt_lines = tilt_lines.replace("$POS_Z$", "%.1f" % event_options['pos'][2])
tilt_lines = tilt_lines.replace("$ROTATION$", "%.1f" % event_options['rotation'])
tilt_lines = tilt_lines.replace("$PLUNGE_DIRECTION$", "%.1f" % event_options['plunge_direction'])
tilt_lines = tilt_lines.replace("$PLUNGE$", "%.1f" % event_options['plunge'])
# now split lines and add as list entries to event lines
# event lines are defined in list:
# split lines and add to event lines list:
for tilt_line in tilt_lines.split("\n"):
tmp_lines.append(tilt_line)
tmp_lines_list = []
for line in tmp_lines:
tmp_lines_list.append(line + "\n")
ev.set_event_lines(tmp_lines_list)
return ev
# AK 2014-10
def _create_unconformity(self, event_options):
"""Create a unconformity event
**Arguments**:
- *event_options* = list : list of required and optional settings for event;
Options are:
'name' = string : name of unconformity event
'pos' = (x,y,z) : position of reference point (floats)
.. note:: for convenience, it is possible to assign 'top' to z
for position at "surface"
'rotation' = [0,360] : dip?
'plunge_direction' = [0,360] : strike of plunge, measured from x axis
'plunge' = float : ?
"""
ev = events.Unconformity()
tmp_lines = [""]
unconformity_lines = _Templates.unconformity
# substitute text with according values
unconformity_lines = unconformity_lines.replace("$NAME$", event_options['name'])
unconformity_lines = unconformity_lines.replace("$POS_X$", "%.1f" % event_options['pos'][0])
unconformity_lines = unconformity_lines.replace("$POS_Y$", "%.1f" % event_options['pos'][1])
if event_options['pos'] == 'top':
# recalculate z-value to be at top of model
z = self.zmax
unconformity_lines = unconformity_lines.replace("$POS_Z$", "%.1f" % z)
else:
unconformity_lines = unconformity_lines.replace("$POS_Z$", "%.1f" % event_options['pos'][2])
unconformity_lines = unconformity_lines.replace("$DIP_DIRECTION$", "%.1f" % event_options['dip_direction'])
unconformity_lines = unconformity_lines.replace("$DIP$", "%.1f" % event_options['dip'])
# split lines and add to event lines list:
for unconformity_line in unconformity_lines.split("\n"):
tmp_lines.append(unconformity_line)
# unconformity has a stratigraphy block
tmp_lines.append("\tNum Layers\t= %d" % event_options['num_layers'])
for i in range(event_options['num_layers']):
"""Add stratigraphy layers"""
layer_name = event_options['layer_names'][i]
cum_thickness = np.cumsum(event_options['layer_thickness'])
layer_lines = _Templates().strati_layer
# now replace required variables
layer_lines = layer_lines.replace("$NAME$", layer_name)
layer_lines = layer_lines.replace("$HEIGHT$", "%.1f" % cum_thickness[i])
layer_lines = layer_lines.replace(" ", "\t")
# split lines and add to event lines list:
for layer_line in layer_lines.split("\n"):
tmp_lines.append(layer_line)
# append event name
tmp_lines.append("""\tName\t= %s""" % event_options.get('name', 'Unconf'))
tmp_lines_list = []
for line in tmp_lines:
tmp_lines_list.append(line + "\n")
ev.set_event_lines(tmp_lines_list)
return ev
def set_event_params(self, params_dict):
"""set multiple event parameters according to settings in params_dict
**Arguments**:
- *params_dict* = dictionary : entries to set (multiple) parameters
"""
for key, sub_dict in list(params_dict.items()):
for sub_key, val in list(sub_dict.items()):
self.events[key].properties[sub_key] = val
def change_event_params(self, changes_dict):
"""Change multiple event parameters according to settings in changes_dict
**Arguments**:
- *changes_dict* = dictionary : entries define relative changes for (multiple) parameters
Per default, the values in the dictionary are added to the event parameters.
"""
# print changes_dict
for key, sub_dict in list(changes_dict.items()): # loop through events (key)
for sub_key, val in list(sub_dict.items()): # loop through parameters being changed (sub_key)
if isinstance(sub_key, int): # in this case, it is the layer id of a stratigraphic layer!
self.events[key].layers[sub_key].properties[val['property']] += val['val']
else:
self.events[key].properties[sub_key] += val
def get_event_params(self, event_number):
'''
Returns the parameter dictionary for a given event.
**Arguments**:
- *event_number* = the event to get a parameter for (integer)
**Returns**
- Returns the parameter dictionary for the requested event
'''
return self.events[event_number].properties
def get_event_param(self, event_number, name):
'''
Returns the value of a given parameter for a given event.
**Arguments**:
- *event_number* = the event to get a parameter for (integer)
- *name* = the name of the parameter to retreive (string)
**Returns**
- Returns the value of the request parameter, or None if it does not
exists.
'''
try:
ev = self.events[event_number].properties
return ev[name]
except KeyError:
return None # property does not exist
def write_history(self, filename):
"""Write history to new file
**Arguments**:
- *filename* = string : filename of new history file
.. hint:: Just love it how easy it is to 'write history' with Noddy ;-)
"""
# before saving: update all event properties (in case changes were made)
self.update_all_event_properties()
# first: create header
if not hasattr(self, "filename"):
self.filename = filename
self._create_header()
# initialise history lines
history_lines = []
# add header
for line in self.header_lines.split("\n"):
history_lines.append(line + "\n")
# add number of events
history_lines.append("No of Events\t= %d\n" % len(self.events))
# add events
for event_id in sorted(self.events.keys()):
for line in self.events[event_id].event_lines:
history_lines.append(line)
# add footer: from original footer or from template (if new file):
if not hasattr(self, "footer_lines"):
self.create_footer_from_template()
# add footer
for line in self.footer_lines:
history_lines.append(line)
f = open(filename, 'w')
for i, line in enumerate(history_lines):
# add empty line before "BlockOptions", if not there:
if ('BlockOptions' in line) and (history_lines[i - 1] != "\n"):
f.write("\n")
# write line
f.write(line)
f.close()
# ===============================================================================
# End of NoddyHistory
# ===============================================================================
# ===============================================================================
# Two extra PyNoddy functions for creating history files based on fault traces
# ===============================================================================
def setUpFaultRepresentation(Data, SlipParam=0.04, xy_origin=[0,0,0],
RefineFault=True, RefineDistance=350,
interpType = 'linear'):
'''
This is a function that takes a csv files with fault vertices and manipulates
the information so it can be easily input into PyNoddy
Parameters
----------
Data : A pandas table with the vertices of the faults.
Needs to contain four columns: id,DipDirecti,X,Y.
id: an identifier for each fault (to which fault does the vertex belong)
DipDirecti: dip direction: East, West, SS (strike slip)
X,Y: the x and y of the fault vertices
SlipParam : How much does the fault slip for the fault length, optional
The default is 0.04.
RefineFault: Should you refine the number of points with which the fault is modeled
RefineDistance: Every how many units should you create another fault vertex
interpType: The type of interpolation used when refining the fault trace.
choose from ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘previous’, ‘next’
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
Returns
-------
parametersForGeneratingFaults: a dictionary with lists of Noddy-ready fault parameters.
'''
import pandas as pd
from sklearn.decomposition import PCA
from scipy import interpolate
#################################
## 1. initialize parameters
#################################
#the x, y, z centers of the fault
XList, YList, ZList = [], [], []
#the x, y, trace points of the fault, and the number of points per fault trace
PtXList,PtYList = [],[]
nFaultPointsList = []