-
Notifications
You must be signed in to change notification settings - Fork 32
/
Fault.py
3510 lines (2878 loc) · 124 KB
/
Fault.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 parent Fault class
Written by Z. Duputel, R. Jolivet, and B. Riel, March 2014
Edited by T. Shreve, May 2019
'''
# Import Externals stuff
import numpy as np
import pyproj as pp
import matplotlib.pyplot as plt
from . import triangularDisp as tdisp
from scipy.linalg import block_diag
import scipy.spatial.distance as scidis
import scipy.interpolate as sciint
import scipy.signal as scisig
import scipy.optimize as sciopt
import copy
import sys
import os
# Personals
from .SourceInv import SourceInv
from .EDKSmp import sum_layered
from .EDKSmp import dropSourcesInPatches as Patches2Sources
#class Fault
class Fault(SourceInv):
'''
Parent class implementing what is common in all fault objects.
You can specify either an official utm zone number or provide
longitude and latitude for a custom zone.
Args:
* name : Name of the fault.
* utmzone : UTM zone (optional, default=None)
* lon0 : Longitude defining the center of the custom utm zone
* lat0 : Latitude defining the center of the custom utm zone
* ellps : ellipsoid (optional, default='WGS84')
'''
# ----------------------------------------------------------------------
# Initialize class
def __init__(self, name, utmzone=None, ellps='WGS84', lon0=None, lat0=None, verbose=True):
# Base class init
super(Fault,self).__init__(name, utmzone=utmzone, ellps=ellps, lon0=lon0, lat0=lat0)
# Initialize the fault
if verbose:
print ("---------------------------------")
print ("---------------------------------")
print ("Initializing fault {}".format(self.name))
self.verbose = verbose
self.type = "Fault"
# Specify the type of patch
self.patchType = None
# Set the reference point in the x,y domain (not implemented)
self.xref = 0.0
self.yref = 0.0
# Allocate fault trace attributes
self.xf = None # original non-regularly spaced coordinates (UTM)
self.yf = None
self.xi = None # regularly spaced coordinates (UTM)
self.yi = None
self.loni = None # regularly spaced coordinates (geographical)
self.lati = None
self.lon = None
self.lat = None
# Allocate depth attributes
self.top = None # Depth of the top of the fault
self.depth = None # Depth of the bottom of the fault
# Allocate patches
self.patch = None
self.slip = None
self.N_slip = None # This will be the number of slip values
self.totalslip = None
self.Cm = None
self.mu = None
self.numz = None
# Remove files
self.cleanUp = True
# Create a dictionnary for the polysol
self.polysol = {}
# Create a dictionary for the Green's functions and the data vector
self.G = {}
self.d = {}
# Create structure to store the GFs and the assembled d vector
self.Gassembled = None
self.dassembled = None
# Adjacency map for the patches
self.adjacencyMap = None
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# Set up whats needed for an empty fault
def initializeEmptyFault(self):
'''
Initializes what is required for a fualt with no patches
Returns:
* None
'''
# Initialize
self.patch = []
self.patchll = []
self.N_slip = 0
self.initializeslip()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# Returns a copy of the fault
def duplicateFault(self):
'''
Returns a full copy (copy.deepcopy) of the fault object.
Return:
* fault : fault object
'''
return copy.deepcopy(self)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# Initialize the slip vector
def initializeslip(self, n=None, values=None):
'''
Re-initializes the fault slip array to zero values.
Slip array will be the size of the number of patches/tents times the
3 components of slip (strike-slip, dip slip and tensile).
- 1st Column is strike slip
- 2nd Column is dip slip
- 3rd Column is tensile
Kwargs:
* n : Number of slip values. If None, it'll take the number of patches.
* values : Can be 'depth', 'strike', 'dip', 'length', 'width', 'area', 'index' or a numpy array. The array can be of size (n,3) or (n,1)
Returns:
* None
'''
# Shape
if n is None:
self.N_slip = len(self.patch)
else:
self.N_slip = n
self.slip = np.zeros((self.N_slip,3))
# Values
if values is not None:
# string type
if type(values) is str:
if values == 'depth':
values = np.array([self.getpatchgeometry(p, center=True)[2] for p in self.patch])
elif values == 'strike':
values = np.array([self.getpatchgeometry(p, center=True)[5] for p in self.patch])
elif values == 'dip':
values = np.array([self.getpatchgeometry(p, center=True)[6] for p in self.patch])
elif values == 'length':
values = np.array([self.getpatchgeometry(p, center=True)[4] for p in self.patch])
elif values == 'width':
values = np.array([self.getpatchgeometry(p, center=True)[3] for p in self.patch])
elif values == 'area':
self.computeArea()
values = self.area
elif values == 'index':
values = np.array([float(self.getindex(p)) for p in self.patch])
self.slip[:,0] = values
# Numpy array
if type(values) is np.ndarray:
try:
self.slip[:,:] = values
except:
try:
self.slip[:,0] = values
except:
print('Wrong size for the slip array provided')
return
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# Add some fault traces to plot with self
def addfaults(self, filename):
'''
Add some other faults to plot with the modeled one.
Args:
* filename : Name of the file. File is ascii format. First column is longitude. Second column is latitude. Separator between faults is > as in GMT style
Return:
* None
'''
# 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 = []
elif A.split()[0] == '#':
pass # comment line, ignore
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 trace2xy(self):
'''
Transpose the fault trace lat/lon into the UTM reference.
UTM coordinates are stored in self.xf and self.yf in km
Returns:
* None
'''
# do it
self.xf, self.yf = self.ll2xy(self.lon, self.lat)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def trace2ll(self):
'''
Transpose the fault trace UTM coordinates into lat/lon.
Lon/Lat coordinates are stored in self.lon and self.lat in degrees
Returns:
* None
'''
# do it
self.lon, self.lat = self.xy2ll(self.xf, self.yf)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def patch2xy(self):
'''
Takes all the patches in self.patchll and convert them to xy
Patches are stored in self.patch
Returns:
* None
'''
# Create list
patch = []
# Iterate
for patchll in self.patchll:
# Create a patch
p = []
# Iterate again
for pll in patchll.tolist():
x, y = self.ll2xy(pll[0], pll[1])
p.append([x, y, pll[2]])
patch.append(np.array(p))
# Save
self.patch = patch
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def patch2ll(self):
'''
Takes all the patches in self.patch and convert them to lonlat.
Patches are stored in self.patchll
Returns:
* None
'''
# Create list
patchll = []
# Iterate
for patch in self.patch:
# Create a patch
pll = []
# Iterate again
for p in patch.tolist():
lon, lat = self.xy2ll(p[0], p[1])
pll.append([lon, lat, p[2]])
patchll.append(np.array(pll))
# Save
self.patchll = patchll
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setTrace(self,delta_depth=0., sort='y'):
'''
Uses the patches to build a fault trace. Fault trace is made of the
vertices that are shallower than fault top + delta_depth
Fault trace is in self.xf and self.yf
Args:
* delta_depth : Depth extension below top of the fault
'''
self.xf = []
self.yf = []
# Set top
if self.top is None:
depth = [[p[2] for p in patch] for patch in self.patch]
depth = np.unique(np.array(depth).flatten())
self.top = np.min(depth)
self.depth = np.max(depth)
minz = np.round(self.top+delta_depth,1)
for p in self.patch:
for v in p:
if np.round(v[2],1)>=minz:
continue
self.xf.append(v[0])
self.yf.append(v[1])
self.xf = np.array(self.xf)
self.yf = np.array(self.yf)
if sort=='y':
i = np.argsort(self.yf)
elif sort=='x':
i = np.argsort(self.xf)
self.xf = self.xf[i]
self.yf = self.yf[i]
# Set lon lat
self.trace2ll()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def trace(self, x, y, utm=False):
'''
Set the surface fault trace from Lat/Lon or UTM coordinates
Surface fault trace is stored in self.xf, self.yf (UTM) and
self.lon, self.lat (Lon/lat)
Args:
* Lon : Array/List containing the Lon points.
* Lat : Array/List containing the Lat points.
Kwargs:
* utm : If False, considers x and y are lon/lat. If True, considers x and y are utm in km
Returns:
* None
'''
# Set lon and lat
if utm:
self.xf = np.array(x)/1000.
self.yf = np.array(y)/1000.
# to lat/lon
self.trace2ll()
else:
self.lon = np.array(x)
self.lat = np.array(y)
# utmize
self.trace2xy()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def file2trace(self, filename, utm=False, header=0):
'''
Reads the fault trace from a text file (ascii 2 columns)
- If utm is False, format is Lon Lat
- If utm is True, format is X Y (in km)
Args:
* filename : Name of the fault file.
Kwargs:
* utm : Specify nature of coordinates
* header : Number of lines to skip at the beginning of the file
Returns:
* None
'''
# Open the file
fin = open(filename, 'r')
# Read the whole thing
A = fin.readlines()
# store these into Lon Lat
x = []
y = []
for i in range(header, len(A)):
x.append(float(A[i].split()[0]))
y.append(float(A[i].split()[1]))
# Create the trace
self.trace(x, y, utm)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def discretize(self, every=2., tol=0.01, fracstep=0.2, xaxis='x',
cum_error=True):
'''
Refine the surface fault trace by setting a constant distance between
each point. Pay attention, the fault cannot be exactly a straight
line north-south. Descretized fault trace is stored in self.xi and
self.yi
Kwargs:
* every : Spacing between each point (in km)
* tol : Tolerance in the spacing (in km)
* fracstep : fractional step in the chosen direction for the discretization optimization
* xaxis : Axis for the discretization. 'x'= use x as the axis, 'y'= use y as the axis
* cum_error : if True, accounts for cumulated error to define the axis bound for the last patch
Returns:
* None
'''
# Check if the fault is in UTM coordinates
if self.xf is None:
self.trace2xy()
if xaxis=='x':
xf = self.xf
yf = self.yf
else:
yf = self.xf
xf = self.yf
# Import the interpolation routines
import scipy.interpolate as scint
# Build the interpolation
od = np.argsort(xf)
f_inter = scint.interp1d(xf[od], yf[od], bounds_error=False)
# Initialize the list of equally spaced points
xi = [xf[od][0]] # Interpolated x fault
yi = [yf[od][0]] # Interpolated y fault
xlast = xf[od][-1] # Last point
ylast = yf[od][-1]
# First guess for the next point
xt = xi[-1] + every * fracstep
yt = f_inter(xt)
# Check if first guess is in the domain
if xt>xlast-tol:
xt = xlast
xi.append(xt)
yi.append(f_inter(xt))
# While the last point is not the last wanted point
total_error = 0.
mod_error = 0.
while (xi[-1] < xlast):
# 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:
maxcount = 10**6 #maximum number of iteration
count = 0
# 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 += (every-d)*fracstep
# If I passed the last point (accounting for error in previous steps)
if (np.round(xt,decimals=2)>=np.round(xlast-mod_error-tol,decimals=2)):
xt = xlast
elif (xt<xi[-1]): # If I passed the previous point
xt = xi[-1] + every
# I compute the corresponding yt
yt = f_inter(xt)
# I compute the corresponding distance
d = np.sqrt( (xt-xi[-1])**2 + (yt-yi[-1])**2 )
if count > maxcount:
print("ERROR: looks like you are in an infinite loop")
print("You should change parameters like fracstep and every")
assert False
count+=1
# When I stepped out of that loop, append
if cum_error:
total_error += every - d
mod_error = np.abs(total_error)%(0.5*every)
xi.append(xt)
yi.append(yt)
# Next guess for the loop
xt = xi[-1] + every * fracstep
# Store the result in self
if xaxis=='x':
self.xi = np.array(xi)
self.yi = np.array(yi)
else:
self.yi = np.array(xi)
self.xi = np.array(yi)
# Compute the lon/lat
self.loni, self.lati = self.xy2ll(self.xi, self.yi)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def smoothTrace(self, winsize=10, std=1., discretized=True):
'''
Smoothes the trace of the fault using a median filter (scipy.signal.medfilt)
Kwargs:
* std : Standard deviation of the Gaussian kernel in km
* discretized : Use the discretized fault trace (self.xi and self.yi) (default True)
Returns:
* None
'''
# Get the fault trace
if discretized:
xt = self.xi
yt = self.yi
else:
xt = self.xf
yt = self.yf
# Smooth it
win = scisig.windows.gaussian(winsize, std)
x = scisig.convolve(np.concatenate((xt[::-1], xt, xt[::-1])), win,
mode='same', method='fft')/sum(win)
y = scisig.convolve(np.concatenate((yt[::-1], yt, yt[::-1])), win,
mode='same', method='fft')/sum(win)
# Keep what I need
x = x[len(xt):2*len(xt)]
y = y[len(yt):2*len(yt)]
# Save it
if discretized:
self.xi = x
self.yi = y
self.loni, self.lati = self.xy2ll(self.xi, self.yi)
else:
self.xf = x
self.yf = y
self.lon, self.lat = self.xy2ll(self.xi, self.yi)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def strikeOfTrace(self, discretized=True, npoints=4):
'''
Computes the strike of the fault trace from the discretized (default)
fault trace.
Kwargs:
* discretized : Use the discretized fault trace (self.xi and self.yi) (default True)
* npoints : Number of points to average strike
Return:
* None. Stores the strike in self.strike
'''
# Get the fault trace
if discretized:
xt = self.xi
yt = self.yi
else:
xt = self.xf
yt = self.yf
# Iterate over these guys
strike = []
for i in range(len(xt)):
s = []
for n in range(1, npoints):
istart = np.max((0, i-n))
iend = np.min((len(xt)-1, i+n))
s.append(np.pi/2.-np.arctan2(yt[iend]-yt[istart],xt[iend]-xt[istart]))
strike.append(np.mean(s))
# Save strike
self.strike = strike
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cumdistance(self, discretized=False, recompute=True):
'''
Computes the distance between the first point of the fault and every
other point. The distance is cumulative along the fault.
Args:
* discretized : if True, use the discretized fault trace (default False)
* recompute : if False, just returns the attribute cumdis
Returns:
* dis : Cumulative distance array
'''
# Check
if not recompute:
return self.cumdis
# Get the x and y positions
if discretized:
x = self.xi
y = self.yi
else:
x = self.xf
y = self.yf
# initialize
dis = np.zeros((x.shape[0]))
# Loop
for i in range(1,x.shape[0]):
d = np.sqrt((x[i]-x[i-1])**2 + (y[i]-y[i-1])**2)
dis[i] = dis[i-1] + d
# Save
self.cumdis = dis
# all done
return dis
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cumdis2xy(self, distance, recompute=True, mode='lonlat', discretized=False):
'''
For a given {distance}, returns the x and y position along strike.
Args:
* distance : Along strike distance
Kwargs:
* recompute : recompute the interpolator
* mode : 'lonlat' returns lon/lat while 'xy' returns x and y
* discretized : use the discretized fault trace
Returns:
* xy : tuple of floats
'''
# Get the coordinates
if discretized:
x,y = self.xi,self.yi
else:
x,y = self.xf,self.yf
# Cumulative distance is needed
cumdis = self.cumdistance(discretized=discretized, recompute=recompute)
# Make the interpolator
if recompute:
self.intcumdis = sciint.LinearNDInterpolator(np.vstack((x, y)).T, self.cumdis, fill_value=0.)
assert hasattr(self, 'intcumdis'), 'An interpolator is needed'
# Make a function with this
def norm(m):
return (self.intcumdis(m[0], m[1])-distance)**2
# Minimize from a starting point that is close to the good point
istart = np.argmin(np.abs(cumdis-distance))
startm = np.array([x[istart], y[istart]])
m = sciopt.minimize(norm, startm)
# All done
return tuple(m.x)
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def distance2trace(self, lon, lat, discretized=False, coord='ll', recompute=True):
'''
Computes the distance between a point and the trace of a fault.
This is a slow method, so it has been recoded in a few places
throughout the whole library.
Args:
* lon : Longitude of the point.
* lat : Latitude of the point.
Kwargs:
* discretized : Uses the discretized trace.
* recompute : recompute the cumulative distance
* coord : if 'll' or 'lonlat', input in degree. If 'xy' or 'utm', input in km
Returns:
* dalong : Distance to the first point of the fault along the fault
* dacross : Shortest distance between the point and the fault
'''
# Get the cumulative distance along the fault
cumdis = self.cumdistance(discretized=discretized, recompute=recompute)
# ll2xy
if coord in ('ll', 'lonlat'):
x, y = self.ll2xy(lon, lat)
elif coord in ('xy', 'utm'):
x,y = lon, lat
# Fault coordinates
if discretized:
xf = self.xi
yf = self.yi
else:
xf = self.xf
yf = self.yf
# Compute the distance between the point and all the points
d = scidis.cdist([[x,y]], [[xf[i], yf[i]] for i in range(len(xf))])[0]
# Get the two closest points
imin1 = d.argmin()
dmin1 = d[imin1]
d[imin1] = 999999.
imin2 = d.argmin()
dmin2 = d[imin2]
d[imin2] = 999999.
dtot = dmin1+dmin2
# Along the fault?
xc = (xf[imin1]*dmin1 + xf[imin2]*dmin2)/dtot
yc = (yf[imin1]*dmin1 + yf[imin2]*dmin2)/dtot
# Distance
if dmin1<dmin2:
jm = imin1
else:
jm = imin2
dalong = cumdis[jm] + np.sqrt( (xc-xf[jm])**2 + (yc-yf[jm])**2 )
dacross = np.sqrt((xc-x)**2 + (yc-y)**2)
# All done
return dalong, dacross
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getindex(self, p):
'''
Returns the index of a patch.
Args:
* p : Patch from a fault object.
Returns:
* iout : index of the patch
'''
# output index
iout = None
# Find the index of the patch
for i in range(len(self.patch)):
try:
if (self.patch[i] == p).all():
iout = i
except:
if self.patch[i]==p:
iout = i
# All done
return iout
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getslip(self, p):
'''
Returns the slip vector for a patch or tent
Args:
* p : patch or tent
Returns:
* iout : Index of the patch or tent
'''
# Get patch index
io = self.getindex(p)
# All done
return self.slip[io,:]
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeTrace2File(self, filename, ref='lonlat'):
'''
Writes the trace to a file. Format is ascii with two columns with
either lon/lat (in degrees) or x/y (utm in km).
Args:
* filename : Name of the file
Kwargs:
* ref : can be lonlat or utm.
Returns:
* None
'''
# Get values
if ref in ('utm'):
x = self.xf*1000.
y = self.yf*1000.
elif ref in ('lonlat'):
x = self.lon
y = self.lat
# Open file
fout = open(filename, 'w')
# Write
for i in range(x.shape[0]):
fout.write('{} {} \n'.format(x[i], y[i]))
# Close file
fout.close()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def saveGFs(self, dtype='d', outputDir='.',
suffix={'strikeslip':'SS',
'dipslip':'DS',
'tensile':'TS',
'coupling': 'Coupling'}):
'''
Saves the Green's functions in different files.
Kwargs:
* dtype : Format of the binary data saved. 'd' for double. 'f' for np.float32
* outputDir : Directory to save binary data.
* suffix : suffix for GFs name (dictionary)
Returns:
* None
'''
# Print stuff
if self.verbose:
print('Writing Greens functions to file for fault {}'.format(self.name))
# Loop over the keys in self.G
for data in self.G.keys():
# Get the Green's function
G = self.G[data]
# Create one file for each slip componenets
for c in G.keys():
if G[c] is not None:
g = G[c].flatten()
n = self.name.replace(' ', '_')
d = data.replace(' ', '_')
filename = '{}_{}_{}.gf'.format(n, d, suffix[c])
g = g.astype(dtype)
g.tofile(os.path.join(outputDir, filename))
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def saveData(self, dtype='d', outputDir='.'):
'''
Saves the Data in binary files.
Kwargs:
* dtype : Format of the binary data saved. 'd' for double. 'f' for np.float32
* outputDir : Directory to save binary data
Returns:
* None
'''
# Print stuff
if self.verbose:
print('Writing Greens functions to file for fault {}'.format(self.name))
# Loop over the data names in self.d
for data in self.d.keys():
# Get data
D = self.d[data]
# Write data file
filename = '{}_{}.data'.format(self.name, data)
D.tofile(os.path.join(outputDir, filename))
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def buildGFs(self, data, vertical=True, slipdir='sd',
method='homogeneous', verbose=True, convergence=None):
'''
Builds the Green's function matrix based on the discretized fault.
The Green's function matrix is stored in a dictionary.
Each entry of the dictionary is named after the corresponding dataset.
Each of these entry is a dictionary that contains 'strikeslip', 'dipslip',
'tensile' and/or 'coupling'
Args:
* data : Data object (gps, insar, optical, ...)
Kwargs:
* vertical : If True, will produce green's functions for the vertical displacements in a gps object.
* slipdir : Direction of slip along the patches. Can be any combination of s (strikeslip), d (dipslip), t (tensile) and c (coupling)
* method : Can be 'okada' (Okada, 1982) (rectangular patches only), 'meade' (Meade 2007) (triangular patches only), 'edks' (Zhao & Rivera, 2002), 'homogeneous' (Okada for rectangles, Meade for triangles)
* verbose : Writes stuff to the screen (overwrites self.verbose)
* convergence : If coupling case, needs convergence azimuth and rate [azimuth in deg, rate]
Returns:
* None
**********************
TODO: Implement the homogeneous case for the Node-based triangular GFs
**********************
'''
# If the data set is surfaceslip, that's where we build the GFs
if data.dtype == 'surfaceslip' and method not in ('empty'):
G = self.surfaceGFs(data, slipdir=slipdir)
data.setGFsInFault(self, G, vertical=vertical)
return
# Chech something
if self.patchType == 'triangletent' and method not in ('empty'):