-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdippingfault.py
2742 lines (2262 loc) · 90.4 KB
/
dippingfault.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
'''
A class that deals with vertical faults.
Written by R. Jolivet, April 2013
'''
# Externals
import numpy as np
import pyproj as pp
import matplotlib.pyplot as plt
import scipy.interpolate as sciint
import copy
import sys
from .RectangularPatches import RectangularPatches
# Personals
major, minor, micro, release, serial = sys.version_info
if major==2:
import okada4py as ok
from .gps import gps as gpsclass
class dippingfault(RectangularPatches):
def __init__(self, name, utmzone=None, ellps='WGS84', verbose=True, lon0=None, lat0=None):
'''
Args:
* name : Name of the fault.
* utmzone : UTM zone (optional, default=None)
* ellps : ellipsoid (optional, default='WGS84')
'''
# Parent class init
super(planarfault,self).__init__(name,
utmzone=utmzone,
ellps=ellps,
lon0=lon0,
lat0=lat0,
verbose=verbose)
# All done
return
def duplicateFault(self):
'''
Returns a copy of the fault.
'''
return copy.deepcopy(self)
def initializeslip(self, n=None):
'''
Re-initializes the fault slip array.
Args:
* n : Number of slip values. If None, it'll take the number of patches.
'''
if n is None:
n = len(self.patch)
self.slip = np.array(())
# All done
return
def trace(self, Lon, Lat):
'''
Set the surface fault trace.
Args:
* Lon : Array/List containing the Lon points.
* Lat : Array/List containing the Lat points.
'''
# Set lon and lat
self.lon = np.array(Lon)
self.lat = np.array(Lat)
# utmize
self.trace2xy()
# All done
return
def addfaults(self, filename):
'''
Add some other faults to plot with the modeled one.
Args:
* filename : Name of the fault file (GMT lon lat format).
'''
# Allocate a list
self.addfaults = []
# Read the file
fin = open(filename, 'r')
A = fin.readline()
tmpflt=[]
while len(A.split()) > 0:
if A.split()[0]=='>':
if len(tmpflt) > 0:
self.addfaults.append(np.array(tmpflt))
tmpflt = []
else:
lon = float(A.split()[0])
lat = float(A.split()[1])
tmpflt.append([lon,lat])
A = fin.readline()
fin.close()
# Convert to utm
self.addfaultsxy = []
for fault in self.addfaults:
x,y = self.ll2xy(fault[:,0], fault[:,1])
self.addfaultsxy.append([x,y])
# All done
return
def setdepth(self, depth, top=0, num=5):
'''
Set the maximum depth of the fault patches.
Args:
* depth : Depth of the fault patches.
* num : Number of fault patches at depth.
'''
# Set depth
self.top = top
self.depth = depth
self.numz = num
# All done
return
def file2trace(self, filename):
'''
Reads the fault trace directly from a file.
Format is:
Lon Lat
Args:
* filename : Name of the fault file.
'''
# Open the file
fin = open(filename, 'r')
# Read the whole thing
A = fin.readlines()
# store these into Lon Lat
Lon = []
Lat = []
for i in range(len(A)):
Lon.append(float(A[i].split()[0]))
Lat.append(float(A[i].split()[1]))
# Create the trace
self.trace(Lon, Lat)
# All done
return
def utmzone(self, utmzone):
'''
Set the utm zone of the fault.
Args:
* utm : UTM zone of the fault.
'''
# Set utmzone
self.utmzone = utmzone
self.putm = pp.Proj(proj='utm', zone=self.utmzone, ellps='WGS84')
# All done
return
def trace2xy(self):
'''
Transpose the surface trace of the fault into the UTM reference.
'''
# do it
self.xf, self.yf = self.ll2xy(self.lon, self.lat)
# All done
return
def ll2xy(self, lon, lat):
'''
Do the lat lon 2 utm transform
'''
# Transpose
x, y = self.putm(lon, lat)
# Put it in Km
x = x/1000.
y = y/1000.
# All done
return x, y
def xy2ll(self, x, y):
'''
Do the utm to lat lon transform
'''
# Transpose and return
return self.putm(x*1000., y*1000., inverse=True)
def extrapolate(self, length_added=50, tol=2., fracstep=5., extrap='ud'):
'''
Extrapolates the surface trace. This is usefull when building deep patches for interseismic loading.
Args:
* length_added : Length to add when extrapolating.
* tol : Tolerance to find the good length.
* fracstep : control each jump size.
* extrap : if u in extrap -> extrapolates at the end
if d in extrap -> extrapolates at the beginning
default is 'ud'
'''
# print
print ("Extrapolating the fault for {} km".format(length_added))
# Check if the fault has been interpolated before
if self.xi is None:
print ("Run the discretize() routine first")
return
# Build the interpolation routine
import scipy.interpolate as scint
fi = scint.interp1d(self.xi, self.yi)
# Build the extrapolation routine
fx = self.extrap1d(fi)
# make lists
self.xi = self.xi.tolist()
self.yi = self.yi.tolist()
if 'd' in extrap:
# First guess for first point
xt = self.xi[0] - length_added/2.
yt = fx(xt)
d = np.sqrt( (xt-self.xi[0])**2 + (yt-self.yi[0])**2)
# Loop to find the best distance
while np.abs(d-length_added)>tol:
# move up or down
if (d-length_added)>0:
xt = xt + d/fracstep
else:
xt = xt - d/fracstep
# Get the corresponding yt
yt = fx(xt)
# New distance
d = np.sqrt( (xt-self.xi[0])**2 + (yt-self.yi[0])**2)
# prepend the thing
self.xi.reverse()
self.xi.append(xt)
self.xi.reverse()
self.yi.reverse()
self.yi.append(yt)
self.yi.reverse()
if 'u' in extrap:
# First guess for the last point
xt = self.xi[-1] + length_added/2.
yt = fx(xt)
d = np.sqrt( (xt-self.xi[-1])**2 + (yt-self.yi[-1])**2)
# Loop to find the best distance
while np.abs(d-length_added)>tol:
# move up or down
if (d-length_added)<0:
xt = xt + d/fracstep
else:
xt = xt - d/fracstep
# Get the corresponding yt
yt = fx(xt)
# New distance
d = np.sqrt( (xt-self.xi[-1])**2 + (yt-self.yi[-1])**2)
# Append the result
self.xi.append(xt)
self.yi.append(yt)
# Make them array again
self.xi = np.array(self.xi)
self.yi = np.array(self.yi)
# Build the corresponding lon lat arrays
self.loni, self.lati = self.xy2ll(self.xi, self.yi)
# All done
return
def extrap1d(self,interpolator):
'''
Linear extrapolation routine. Found on StackOverflow by sastanin.
'''
# import a bunch of stuff
from scipy import arange, array, exp
xs = interpolator.x
ys = interpolator.y
def pointwise(x):
if x < xs[0]:
return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
elif x > xs[-1]:
return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
else:
return interpolator(x)
def ufunclike(xs):
return pointwise(xs) #array(map(pointwise, array(xs)))
return ufunclike
def discretize(self, every=2, tol=0.5, fracstep=0.2):
'''
Refine the surface fault trace prior to divide it into patches.
Args:
* every : Spacing between each point.
* tol : Tolerance in the spacing.
'''
# print
print("Discretizing the fault {} every {} km".format(self.name, every))
# Check if the fault is in UTM coordinates
if self.xf is None:
self.trace2xy()
# Import the interpolation routines
import scipy.interpolate as scint
# Build the interpolation
od = np.argsort(self.xf)
self.inter = scint.interp1d(self.xf[od], self.yf[od], bounds_error=False)
# Initialize the list of equally spaced points
xi = [self.xf[od][0]] # Interpolated x fault
yi = [self.yf[od][0]] # Interpolated y fault
xlast = self.xf[od][-1] # Last point
ylast = self.yf[od][-1]
# First guess for the next point
xt = xi[-1] + every * fracstep
# Check if first guess is in the domain
if xt>xlast:
xt = xlast
# Get the corresponding yt
yt = self.inter(xt)
# While the last point is not the last wanted point
while (xi[-1] < xlast):
if (xt==xlast): # I am at the end
xi.append(xt)
yi.append(yt)
else: # I am not at the end
# I compute the distance between me and the last accepted point
d = np.sqrt( (xt-xi[-1])**2 + (yt-yi[-1])**2 )
# Check if I am in the tolerated range
if np.abs(d-every)<tol:
xi.append(xt)
yi.append(yt)
else:
# While I am to far away from my goal and I did not pass the last x
while ((np.abs(d-every)>tol) and (xt<xlast)):
# I add the distance*frac that I need to go
xt -= (d-every)*fracstep
if (xt>xlast): # If I passed the last point
xt = xlast
elif (xt<xi[-1]): # If I passed the previous point
xt = xi[-1] + every
# I compute the corresponding yt
yt = self.inter(xt)
# I compute the corresponding distance
d = np.sqrt( (xt-xi[-1])**2 + (yt-yi[-1])**2 )
# When I stepped out of that loop, append
xi.append(xt)
yi.append(yt)
# Next guess for the loop
xt = xi[-1] + every * fracstep
# Store the result in self
self.xi = np.array(xi)
self.yi = np.array(yi)
# Compute the lon/lat
self.loni, self.lati = self.putm(self.xi*1000., self.yi*1000., inverse=True)
# All done
return
def build_patches(self):
'''
Builds rectangular patches from the discretized fault.
A patch is a list of 4 corners.
'''
# If the maximum depth and the number of patches is not set
if self.depth is None:
print("Depth and number of patches are not set.")
print("Please use setdepth to define maximum depth and number of patches")
return
print ("Build patches for fault {} between depths: {}, {}".format(self.name, self.top, self.depth))
# Define the depth vector
z = np.linspace(self.top, self.depth, num=self.numz+1)
self.z_patches = z
# If the discretization is not done
if self.xi is None:
self.discretize()
# Define a patch list
self.patch = []
self.patchll = []
self.slip = []
# Iterate over the surface discretized fault points
for i in range(len(self.xi)-1):
# First corner
x1 = self.xi[i]
y1 = self.yi[i]
lon1 = self.loni[i]
lat1 = self.lati[i]
# Second corner
x2 = self.xi[i]
y2 = self.yi[i]
lon2 = self.loni[i]
lat2 = self.lati[i]
# Third corner
x3 = self.xi[i+1]
y3 = self.yi[i+1]
lon3 = self.loni[i+1]
lat3 = self.lati[i+1]
# Fourth corner
x4 = self.xi[i+1]
y4 = self.yi[i+1]
lon4 = self.loni[i+1]
lat4 = self.lati[i+1]
# iterate at depth
for j in range(len(z)-1):
p = np.zeros((4,3))
pll = np.zeros((4,3))
p[0,:] = [x1, y1, z[j]]
pll[0,:] = [lon1, lat1, z[j]]
p[1,:] = [x2, y2, z[j+1]]
pll[1,:] = [lon2, lat2, z[j+1]]
p[2,:] = [x3, y3, z[j+1]]
pll[2,:] = [lon3, lat3, z[j+1]]
p[3,:] = [x4, y4, z[j]]
pll[3,:] = [lon4, lat4, z[j]]
self.patch.append(p)
self.patchll.append(pll)
self.slip.append([0.0, 0.0, 0.0])
# Translate slip to np.array
self.slip = np.array(self.slip)
# All done
return
def importPatches(self, filename, origin=[45.0, 45.0]):
'''
Builds a patch geometry and the corresponding files from a relax co-seismic file type.
Args:
filename : Input from Relax (See Barbot and Cie on the CIG website).
origin : Origin of the reference frame used by relax. [lon, lat]
'''
# Create lists
self.patch = []
self.patchll = []
self.slip = []
# origin
x0, y0 = self.ll2xy(origin[0], origin[1])
# open/read/close the input file
fin = open(filename, 'r')
Text = fin.readlines()
fin.close()
# Depth array
D = []
# Loop over the patches
for text in Text:
# split
text = text.split()
# check if continue
if not text[0]=='#':
# Get values
slip = float(text[1])
xtl = float(text[2]) + x0
ytl = float(text[3]) + y0
depth = float(text[4])
length = float(text[5])
width = float(text[6])
strike = float(text[7])*np.pi/180.
rake = float(text[9])*np.pi/180.
D.append(depth)
# Build a patch with that
x1 = xtl
y1 = ytl
z1 = depth + width
x2 = xtl
y2 = ytl
z2 = depth
x3 = xtl + length*np.cos(strike)
y3 = ytl + length*np.sin(strike)
z3 = depth
x4 = xtl + length*np.cos(strike)
y4 = ytl + length*np.sin(strike)
z4 = depth + width
# Convert to lat lon
lon1, lat1 = self.xy2ll(x1, y1)
lon2, lat2 = self.xy2ll(x2, y2)
lon3, lat3 = self.xy2ll(x3, y3)
lon4, lat4 = self.xy2ll(x4, y4)
# Fill the patch
p = np.zeros((4, 3))
pll = np.zeros((4, 3))
p[0,:] = [x1, y1, z1]
p[1,:] = [x2, y2, z2]
p[2,:] = [x3, y3, z3]
p[3,:] = [x4, y4, z4]
pll[0,:] = [lon1, lat1, z1]
pll[1,:] = [lon2, lat2, z2]
pll[2,:] = [lon3, lat3, z3]
pll[3,:] = [lon4, lat4, z4]
self.patch.append(p)
self.patchll.append(pll)
# Slip
ss = slip*np.cos(rake)
ds = slip*np.sin(rake)
ts = 0.
self.slip.append([ss, ds, ts])
# Translate slip to np.array
self.slip = np.array(self.slip)
# Depth
D = np.unique(np.array(D))
self.z_patches = D
self.depth = D.max()
# Create a trace
dmin = D.min()
self.lon = []
self.lat = []
for p in self.patchll:
d = p[1][2]
if d==dmin:
self.lon.append(p[1][0])
self.lat.append(p[1][1])
self.lon = np.array(self.lon)
self.lat = np.array(self.lat)
# All done
return
def BuildPatchesVarResolution(self, depths, Depthpoints, Resolpoints, interpolation='linear', minpatchsize=0.1, extrap=None):
'''
Patchizes the fault with a variable patch size at depth.
The variable patch size is given by the respoints table.
Depthpoints = [depth1, depth2, depth3, ...., depthN]
Resolpoints = [Resol1, Resol2, Resol3, ...., ResolN]
The final resolution is interpolated given the 'interpolation' method.
Interpolation can be 'linear', 'cubic'.
'''
print('Build fault patches for fault {} between {} and {} km deep, with a variable resolution'.format(self.name, self.top, self.depth))
# Define the depth vector
z = np.array(depths)
self.z_patches = z
# Interpolate the resolution
fint = sciint.interp1d(Depthpoints, Resolpoints, kind=interpolation)
resol = fint(z)
# build lists for storing things
self.patch = []
self.patchll = []
self.slip = []
# iterate over the depths
for j in range(len(z)-1):
# discretize the fault at the desired resolution
print('Discretizing at depth {}'.format(z[j]))
self.discretize(every=np.floor(resol[j]), tol=resol[j]/20., fracstep=resol[j]/1000.)
if extrap is not None:
self.extrapolate(length_added=extrap[0], extrap=extrap[1])
# iterate over the discretized fault
for i in range(len(self.xi)-1):
# First corner
x1 = self.xi[i]
y1 = self.yi[i]
lon1 = self.loni[i]
lat1 = self.lati[i]
# Second corner
x2 = self.xi[i]
y2 = self.yi[i]
lon2 = self.loni[i]
lat2 = self.lati[i]
# Third corner
x3 = self.xi[i+1]
y3 = self.yi[i+1]
lon3 = self.loni[i+1]
lat3 = self.lati[i+1]
# Fourth corner
x4 = self.xi[i+1]
y4 = self.yi[i+1]
lon4 = self.loni[i+1]
lat4 = self.lati[i+1]
# build patches
p = np.zeros((4,3))
pll = np.zeros((4,3))
# fill them
p[0,:] = [x1, y1, z[j]]
pll[0,:] = [lon1, lat1, z[j]]
p[1,:] = [x2, y2, z[j+1]]
pll[1,:] = [lon2, lat2, z[j+1]]
p[2,:] = [x3, y3, z[j+1]]
pll[2,:] = [lon3, lat3, z[j+1]]
p[3,:] = [x4, y4, z[j]]
pll[3,:] = [lon4, lat4, z[j]]
psize = np.sqrt( (x3-x2)**2 + (y3-y2)**2 )
if psize>minpatchsize:
self.patch.append(p)
self.patchll.append(pll)
self.slip.append([0.0, 0.0, 0.0])
else: # Increase the size of the previous patch
self.patch[-1][2,:] = [x3, y3, z[j+1]]
self.patch[-1][3,:] = [x4, y4, z[j]]
self.patchll[-1][2,:] = [lon3, lat3, z[j+1]]
self.patchll[-1][3,:] = [lon4, lat4, z[j]]
# Translate slip into a np.array
self.slip = np.array(self.slip)
# all done
return
def rotationHoriz(self, center, angle):
'''
Rotates the geometry of the fault around center, of an angle.
Args:
* center : [lon,lat]
* angle : degrees
'''
# Translate the center to x, y
xc, yc = self.ll2xy(center[0], center[1])
ref = np.array([xc, yc])
# Create the rotation matrix
angle = angle*np.pi/180.
Rot = np.array( [ [np.cos(angle), -1.0*np.sin(angle)],
[np.sin(angle), np.cos(angle)] ] )
# Loop on the patches
for i in range(len(self.patch)):
# Get patch
p = self.patch[i]
pll = self.patchll[i]
for j in range(4):
x, y = np.dot( Rot, p[j][:-1] - ref )
p[j][0] = x + xc
p[j][1] = y + yc
lon, lat = self.xy2ll(p[j][0],p[j][1])
pll[j][0] = lon
pll[j][1] = lat
# All done
return
def translationHoriz(self, dx, dy):
'''
Translates the patches.
Args:
* dx : Translation along x (km)
* dy : Translation along y (km)
'''
# Loop on the patches
for i in range(len(self.patch)):
# Get patch
p = self.patch[i]
pll = self.patchll[i]
for j in range(4):
p[j][0] += dx
p[j][1] += dy
lon, lat = self.xy2ll(p[j][0],p[j][1])
pll[j][0] = lon
pll[j][1] = lat
# All done
return
def mergePatches(self, p1, p2):
'''
Merges 2 patches that have common corners.
Args:
* p1 : index of the patch #1.
* p2 : index of the patch #2.
'''
print('Merging patches {} and {} into patch {}'.format(p1,p2,p1))
# Get the patches
patch1 = self.patch[p1]
patch2 = self.patch[p2]
patch1ll = self.patchll[p1]
patch2ll = self.patchll[p2]
# Create the newpatches
newpatch = np.zeros((4,3))
newpatchll = np.zeros((4,3))
# determine which corners are in common, needs at least two
if ((patch1[0]==patch2[1]).all() and (patch1[3]==patch2[2]).all()): # patch2 is above patch1
newpatch[0,:] = patch2[0,:]; newpatchll[0,:] = patch2ll[0,:]
newpatch[1,:] = patch1[1,:]; newpatchll[1,:] = patch1ll[1,:]
newpatch[2,:] = patch1[2,:]; newpatchll[2,:] = patch1ll[2,:]
newpatch[3,:] = patch2[3,:]; newpatchll[3,:] = patch2ll[3,:]
elif ((patch1[3]==patch2[0]).all() and (patch1[2]==patch2[1]).all()): # patch2 is on the right of patch1
newpatch[0,:] = patch1[0,:]; newpatchll[0,:] = patch1ll[0,:]
newpatch[1,:] = patch1[1,:]; newpatchll[1,:] = patch1ll[1,:]
newpatch[2,:] = patch2[2,:]; newpatchll[2,:] = patch2ll[2,:]
newpatch[3,:] = patch2[3,:]; newpatchll[3,:] = patch2ll[3,:]
elif ((patch1[1]==patch2[0]).all() and (patch1[2]==patch2[3]).all()): # patch2 is under patch1
newpatch[0,:] = patch1[0,:]; newpatchll[0,:] = patch1ll[0,:]
newpatch[1,:] = patch2[1,:]; newpatchll[1,:] = patch2ll[1,:]
newpatch[2,:] = patch2[2,:]; newpatchll[2,:] = patch2ll[2,:]
newpatch[3,:] = patch1[3,:]; newpatchll[3,:] = patch1ll[3,:]
elif ((patch1[0]==patch2[3]).all() and (patch1[1]==patch2[2]).all()): # patch2 is on the left of patch1
newpatch[0,:] = patch2[0,:]; newpatchll[0,:] = patch2ll[0,:]
newpatch[1,:] = patch2[1,:]; newpatchll[1,:] = patch2ll[1,:]
newpatch[2,:] = patch1[2,:]; newpatchll[2,:] = patch1ll[2,:]
newpatch[3,:] = patch1[3,:]; newpatchll[3,:] = patch1ll[3,:]
else:
print('Patches do not have common corners...')
return
# Replace the patch 1 by the new patch
self.patch[p1] = newpatch
self.patchll[p1] = newpatchll
# Delete the patch 2
self.deletepatch(p2)
# All done
return
def readPatchesFromFile(self, filename):
'''
Read the patches from a GMT formatted file.
Args:
* filename : Name of the file.
'''
# create the lists
self.patch = []
self.patchll = []
self.index_parameter = []
self.slip = []
# open the file
fin = open(filename, 'r')
# read all the lines
A = fin.readlines()
# Loop over the file
i = 0
while i<len(A):
# Assert it works
assert A[i].split()[0]=='>', 'Not a patch, reformat your file...'
# Get the Patch Id
self.index_parameter.append([int(A[i].split()[3]),int(A[i].split()[4]),int(A[i].split()[5])])
# Get the slip value
if len(A[i].split()>7):
slip = np.array([float(A[i].split()[7]), float(A[i].split()[8]), float(A[i].split()[9])])
else:
slip = np.array([0.0, 0.0, 0.0])
self.slip.append(slip)
# build patches
p = np.zeros((4,3))
pll = np.zeros((4,3))
# get the values
lon1, lat1, z1 = A[i+1].split()
lon2, lat2, z2 = A[i+2].split()
lon3, lat3, z3 = A[i+3].split()
lon4, lat4, z4 = A[i+4].split()
# Pass as floating point
lon1 = float(lon1); lat1 = float(lat1); z1 = float(z1)
lon2 = float(lon2); lat2 = float(lat2); z2 = float(z2)
# Pass as floating point
lon1 = float(lon1); lat1 = float(lat1); z1 = float(z1)
lon2 = float(lon2); lat2 = float(lat2); z2 = float(z2)
lon3 = float(lon3); lat3 = float(lat3); z3 = float(z3)
lon4 = float(lon4); lat4 = float(lat4); z4 = float(z4)
# Store theme
pll[0,:] = [lon1, lat1, z1]
pll[1,:] = [lon2, lat2, z2]
pll[2,:] = [lon3, lat3, z3]
pll[3,:] = [lon4, lat4, z4]
# translate to utm
x1, y1 = self.ll2xy(lon1, lat1)
x2, y2 = self.ll2xy(lon2, lat2)
x3, y3 = self.ll2xy(lon3, lat3)
x4, y4 = self.ll2xy(lon4, lat4)
# Put these in m
x1 /= 1000.; y1 /= 1000.
x2 /= 1000.; y2 /= 1000.
x3 /= 1000.; y3 /= 1000.
x4 /= 1000.; y4 /= 1000.
# Store them
p[0,:] = [x1, y1, z1]
p[1,:] = [x2, y2, z2]
p[2,:] = [x3, y3, z3]
p[3,:] = [x4, y4, z4]
# Store these in the lists
self.patch.append(p)
self.patchll.append(pll)
# increase i
i += 5
# Close the file
fin.close()
# Translate slip to np.array
self.slip = np.array(self.slip)
self.index_parameter = np.array(self.index_parameter)
# All done
return
def writePatches2File(self, filename, add_slip=None, scale=1.0):
'''
Writes the patch corners in a file that can be used in psxyz.
Args:
* filename : Name of the file.
* add_slip : Put the slip as a value for the color. Can be None, strikeslip, dipslip, total.
* scale : Multiply the slip value by a factor.
'''
# Write something
print('Writing geometry to file {}'.format(filename))
# Open the file
fout = open(filename, 'w')
# Loop over the patches
for p in range(len(self.patchll)):
# Select the string for the color
string = ' '
if add_slip is not None:
if add_slip=='strikeslip':
slp = self.slip[p,0]*scale
string = '-Z{}'.format(slp)
elif add_slip=='dipslip':
slp = self.slip[p,1]*scale
string = '-Z{}'.format(slp)
elif add_slip=='total':
slp = np.sqrt(self.slip[p,0]**2 + self.slip[p,1]**2)*scale
string = '-Z{}'.format(slp)
# Put the parameter number in the file as well if it exists
parameter = ' '
if hasattr(self,'index_parameter'):
i = int(self.index_parameter[p,0])
j = int(self.index_parameter[p,1])
k = int(self.index_parameter[p,2])
parameter = '# {} {} {} '.format(i,j,k)
# Put the slip value
slipstring = ' # {} {} {} '.format(self.slip[p,0], self.slip[p,1], self.slip[p,2])
# Write the string to file
fout.write('> {} {} {} \n'.format(string,parameter,slipstring))
# Write the 4 patch corners (the order is to be GMT friendly)
p = self.patchll[p]
pp=p[1]; fout.write('{} {} {} \n'.format(pp[0], pp[1], pp[2]))
pp=p[0]; fout.write('{} {} {} \n'.format(pp[0], pp[1], pp[2]))
pp=p[3]; fout.write('{} {} {} \n'.format(pp[0], pp[1], pp[2]))
pp=p[2]; fout.write('{} {} {} \n'.format(pp[0], pp[1], pp[2]))
# Close th file
fout.close()
# All done
return
def getslip(self, p):
'''
Returns the slip vector for a patch.
'''
# output index
io = None
# Find the index of the patch
for i in range(len(self.patch)):
if (self.patch[i]==p).all():
io = i
# All done
return self.slip[io,:]
def writeSlipDirection2File(self, filename, scale=1.0, factor=1.0, neg_depth=False):
'''
Write a psxyz compatible file to draw lines starting from the center of each patch,
indicating the direction of slip.
Tensile slip is not used...
scale can be a real number or a string in 'total', 'strikeslip', 'dipslip' or 'tensile'
'''
# Copmute the slip direction
self.computeSlipDirection(scale=scale, factor=factor)
# Write something
print('Writing slip direction to file {}'.format(filename))
# Open the file
fout = open(filename, 'w')
# Loop over the patches
for p in self.slipdirection:
# Write the > sign to the file
fout.write('> \n')
# Get the center of the patch
xc, yc, zc = p[0]
lonc, latc = self.xy2ll(xc, yc)
if neg_depth:
zc = -1.0*zc
fout.write('{} {} {} \n'.format(lonc, latc, zc))
# Get the end of the vector
xc, yc, zc = p[1]
lonc, latc = self.xy2ll(xc, yc)
if neg_depth:
zc = -1.0*zc
fout.write('{} {} {} \n'.format(lonc, latc, zc))
# Close file
fout.close()
# all done
return
def computeSlipDirection(self, scale=1.0, factor=1.0):
'''
Computes the segment indicating the slip direction.
scale can be a real number or a string in 'total', 'strikeslip', 'dipslip' or 'tensile'
'''
# Create the array
self.slipdirection = []